text:
#include <cstdlib> // NULL

#include "m4gfx/sis/defines.h"
#include "m4gfx/sis/x_info.hpp"
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>

m4gfx::x_info::x_info() : _tag(boost::uuids::to_string(boost::uuids::random_generator()())),
_type(m4gfx::XIC_NONE){
    }

m4gfx::x_info::x_info(m4gfx::XINFOCLASS x_type) : _tag(boost::uuids::to_string(boost::uuids::random_generator()())),
_type(x_type){
    }

m4gfx::x_info::x_info(m4gfx::XINFOCLASS type, rapidjson::Document& info,
std::set<std::string> attrs ) : _tag(boost::uuids::to_string(boost::uuids::random_generator()())),
_type(type), _attrs(attrs){
    xis_info.CopyFrom(info, xis_info.GetAllocator());
    }

m4gfx::x_info::x_info(const x_info& rhs){
        _tag = rhs._tag;
        _type = rhs._type;
        xis_info.CopyFrom(rhs.xis_info, xis_info.GetAllocator());
        _attrs = rhs._attrs;
    }

XINFO_API  const void m4gfx::x_info::insert_json(const rapidjson::Document& d){
    xis_info.CopyFrom(d, xis_info.GetAllocator());
}

XINFO_API  const void m4gfx::x_info::insert_info(std::string info_path, const x_info&  data){
    rapidjson::Pointer(info_path).Set(xis_info, data.xis_info);
     _attrs.insert(info_path);
    for(auto s : data._attrs){
        std::string attr_path = info_path + s;
        _attrs.insert(attr_path);
    }
}

max_stars_repo_name: sheldonrobinson/xinfo

max_issues_repo_name: sheldonrobinson/xinfo

max_forks_repo_name: sheldonrobinson/xinfo


text:
//   Copyright (c) 2009 Matthias Vallentin
//
//   Distributed under the Boost Software License, Version 1.0. (See accompanying
//   file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/config/warning_disable.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/iterator/indirect_iterator.hpp>
#include <boost/make_shared.hpp>
#include <boost/noncopyable.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/karma_format.hpp>

#include <sstream>
#include <string>
#include <vector>

struct foo : boost::noncopyable
{
    foo()
      : str("foo")
    {
    }

    std::string str;
};

template <typename Stream>
Stream& operator<<(Stream& out, const foo& f)
{
    out << f.str;
    return out;
}

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

    typedef boost::shared_ptr<foo> foo_ptr;
    std::vector<foo_ptr> v;

    std::size_t i = 10;
    while (i--)
        v.push_back(boost::make_shared<foo>());

    typedef boost::indirect_iterator<std::vector<foo_ptr>::const_iterator>
        iterator_type;

    std::stringstream strm;
    strm
        << karma::format(stream % ',',
            boost::iterator_range<iterator_type>(
                iterator_type(v.begin()), iterator_type(v.end())
                )
            );
    BOOST_TEST(strm.str() == "foo,foo,foo,foo,foo,foo,foo,foo,foo,foo");

    return boost::report_errors();
}

ext: cpp

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:
/***********************************************************************************************************************
 *  OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 *  following conditions are met:
 *
 *  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
 *  disclaimer.
 *
 *  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 *  following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 *  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
 *  products derived from this software without specific prior written permission from the respective party.
 *
 *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
 *  works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
 *  specific prior written permission from Alliance for Sustainable Energy, LLC.
 *
 *  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 HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR
 *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **********************************************************************************************************************/

#include "LogMessage.hpp"

#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

namespace openstudio{

  LogMessage::LogMessage(LogLevel logLevel, const LogChannel& logChannel, const std::string& logMessage)
    : m_logLevel(logLevel), m_logChannel(logChannel), m_logMessage(logMessage)
  {}

  std::vector<LogMessage> LogMessage::parseLogText(const std::string& logText)
  {
    std::vector<LogMessage> result;

    std::string text = logText;

    // get preceding comments
    boost::smatch matches;
    boost::regex messageRegex("\\[([^\\]]*)\\]\\s*<([\\-0-9]+)>([^\\[]*)(.*)");
    while(boost::regex_search(text, matches, messageRegex)){
      std::string channel(matches[1].first, matches[1].second); boost::trim(channel);
      std::string levelString(matches[2].first, matches[2].second); boost::trim(levelString);
      std::string message(matches[3].first, matches[3].second); boost::trim(message);
      std::string remainingText(matches[4].first, matches[4].second); boost::trim(remainingText);

      int level = boost::lexical_cast<int>(levelString);

      result.push_back(LogMessage((LogLevel)level, channel, message));

      // reduce the parsed text
      text = remainingText;
    }

    return result;
  }

  LogLevel LogMessage::logLevel() const
  {
    return m_logLevel;
  }

  LogChannel LogMessage::logChannel() const
  {
    return m_logChannel;
  }

  std::string LogMessage::logMessage() const
  {
    return m_logMessage;
  }

} // openstudio

max_stars_repo_name: hongyuanjia/OpenStudio

max_issues_repo_name: hongyuanjia/OpenStudio

max_forks_repo_name: hongyuanjia/OpenStudio


text:
#include <bio/svg_match.h>
#include <bio/biobase_match.h>
USING_BIO_NS

#include <boost/progress.hpp>
#include <boost/test/unit_test.hpp>
using namespace boost::unit_test;
using namespace boost;

#include <xercesc/util/PlatformUtils.hpp>
XERCES_CPP_NAMESPACE_USE

#include <iostream>
using namespace std;

void check_create_match_svg() {

	cout << "******* check_create_match_svg()" << endl;

#ifdef VERBOSE_CHECKING
	progress_timer timer;
#endif

	XMLPlatformUtils::Initialize();

	const BIO_NS::float_t match_threshold = .05f;
	const std::string title = "Test";
	const seq_t seq = "atcagtcgatcagctagctagtcagc";
	const bool show_titles = true;
	SvgDomDocument doc(seq.size(), match_threshold, 1.0f, title, seq, show_titles);

	dom_print(doc.doc->getDocumentElement(), "test.svg");

	XMLPlatformUtils::Terminate();
}

void register_create_match_svg_tests(test_suite * test)
{
	test->add(BOOST_TEST_CASE(&check_create_match_svg), 0);
}

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy


text:
#include "stdafx.h"
#include <boost/test/unit_test.hpp>
#include "..\\Lab2Task4Var4\GeneratePrimeNumbersSet.h"

BOOST_AUTO_TEST_SUITE(GeneratePrimeNumbersSet_function)
	BOOST_AUTO_TEST_CASE(NO_PRIME_NUMBERS)
	{
		std::set<int> primeSet = GeneratePrimeNumbersSet(1);
		BOOST_CHECK(primeSet.size() == 0);
	}

	BOOST_AUTO_TEST_CASE(SOME_PRIME_NUMBERS)
	{
		std::set<int> primeSet = GeneratePrimeNumbersSet(9);
		std::set<int> checkPrimeSet = { 2, 3, 5, 7 };
		BOOST_CHECK(primeSet == checkPrimeSet);
	}

	BOOST_AUTO_TEST_CASE(HUNDRED_MILLION_COUNT_OF_PRIME_NUMBERS)
	{
		std::set<int> primeSet = GeneratePrimeNumbersSet(100000000);
		BOOST_CHECK(primeSet.size() == 5761455);
	}
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: AlexanderChibirev/OOP

max_issues_repo_name: AlexanderChibirev/OOP

max_forks_repo_name: AlexanderChibirev/OOP


text:
/*
 * copyright 2016 mike vasiljevs (contact@michaelvasiljevs.com)
 * ShapeFitting SU plugin
 */

#include "Adaptive.h"
#include "../io/import.h"
#include "../io/export.h"
#include <iostream>

#define BOOST_TEST_MODULE My Test
//#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
//#include <boost/test/included/unit_test.hpp>

namespace bt = boost::unit_test;
using namespace std;

//#define BOOST_LIB_TOOLSET "vc120"
//#define BOOST_AUTO_TEST_MAIN
//#define BOOST_TEST_MODULE MyTest
//#include <boost/test/unit_test.hpp>
//
//BOOST_AUTO_TEST_CASE(my_test)
//{
//	BOOST_CHECK(1 == 2);
//}

struct ArgsFixture
{
	const std::string base_path = "../../sample_geometry/";
	vector<std::string> filepath_list;
	vector<std::string> filename_list;
	void addFile(char const *filename)
	{
		filename_list.push_back(filename);
		filepath_list.push_back(base_path + filename);
	}

	ArgsFixture()
	{
		// add any additional files from cmd args
		auto num_files = bt::framework::master_test_suite().argc - 1;
		cout << "number of files: " << num_files << endl;
		for (int i = 1; i <= num_files; ++i)
		{
			addFile(bt::framework::master_test_suite().argv[i]);

		}
	}
};

BOOST_FIXTURE_TEST_CASE(adaptive_test, ArgsFixture)
{
	//using tt = boost::test_tools;
	namespace tt = boost::test_tools;

	Pts_t poly_in, poly_out;

	BOOST_REQUIRE(!filepath_list.empty());

	int i = 0;
	for (auto &filepath : filepath_list)
	{
		// read and test
		readObj1(filepath.c_str(), poly_in);
		// dont bother with quads (...and lower)
		if (poly_in.size() <= 4)
			continue;
		BOOST_TEST(poly_in.size() >= 4);

		// compute output poly - quad
		try
		{
			fitPolyAdaptive(poly_in, poly_out);
			cout << "ok\n";
		} catch (std::exception const &ex)
		{
			cout << "failed for file " << filename_list[i] << endl;
		}

		BOOST_TEST(poly_out.size() == 4);

		// write out!
		string filename = "output" + to_string(i) + "_" + filename_list[i];
		writeObj1(filename.c_str(), poly_out);
		++i;
	}
}


text:
//==================================================================================================
/*
  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)
*/
//==================================================================================================

#include <vector>
#include <boost/simd/meta/is_iterator.hpp>
#include <simd_test.hpp>

STF_CASE( "Check is_iterator support" )
{
  using boost::simd::is_iterator;
  STF_EQUAL(is_iterator<int*>::value, true);
  STF_EQUAL(is_iterator<int const*>::value, true);
  STF_EQUAL(is_iterator<std::vector<int>::const_iterator>::value, true);
  STF_EQUAL(is_iterator<std::vector<int>::iterator>::value, true);
  STF_EQUAL(is_iterator<int>::value, false);
  STF_EQUAL(is_iterator<std::vector<int>>::value, false);
}


text:
#include <Aquila/core/Algorithm.hpp>

#include "MetaObject/core/detail/Allocator.hpp"
#include "MetaObject/object/MetaObjectFactory.hpp"
#include "MetaObject/object/detail/IMetaObjectImpl.hpp"
#include "MetaObject/object/detail/MetaObjectMacros.hpp"
#include "MetaObject/params/ParamMacros.hpp"
#include "MetaObject/params/TSubscriberPtr.hpp"
#include <MetaObject/core/AsyncStreamFactory.hpp>

#include <boost/fiber/operations.hpp>
#include <boost/thread.hpp>

#include "gtest/gtest.h"

#include <iostream>
using namespace aq;

int main(int argc, char** argv)
{
    std::shared_ptr<SystemTable> table;
    bool make_table = true;
    for (int i = 0; i < argc; ++i)
    {
        if (std::string("--gtest_list_tests") == argv[i])
        {
            make_table = false;
        }
    }
    ::testing::InitGoogleTest(&argc, argv);
    if (make_table)
    {
        table = SystemTable::instance();
        mo::MetaObjectFactory::instance()->registerTranslationUnit();
    }

    return RUN_ALL_TESTS();
}

class int_output : public Algorithm
{
  public:
    bool processImpl() override
    {
        value.publish(++counter);
        return true;
    }
    MO_BEGIN(int_output)
        OUTPUT(int, value, 0)
    MO_END;
    int counter = 0;
};

class int_input : public Algorithm
{
  public:
    bool processImpl() override
    {
        if (input)
        {
            value = *input;
        }
        return true;
    }

    MO_BEGIN(int_input)
        INPUT(int, input)
    MO_END;
    int value;
};

class synced_input : public Algorithm
{
  public:
    bool processImpl() override
    {
        // TODO fix
        // EXPECT_EQ(timestamp,
        // std::chrono::duration_cast<std::chrono::seconds>(*input_param.getTimestamp()).count());
        return true;
    }
    MO_BEGIN(synced_input)
        INPUT(int, input);
    MO_END;
    int timestamp;
};

class multi_input : public Algorithm
{
  public:
    bool processImpl() override
    {
        EXPECT_EQ(*input1, *input2);
        last = *input1;
        first.push_back(*input1);
        second.push_back(*input2);
        return true;
    }

    MO_BEGIN(multi_input)
        INPUT(int, input1)
        INPUT(int, input2)
    MO_END;
    int last = 0;
    std::vector<int> first;
    std::vector<int> second;
};

MO_REGISTER_OBJECT(int_output);
MO_REGISTER_OBJECT(int_input);
MO_REGISTER_OBJECT(multi_input);

TEST(algorithm, no_input)
{
    auto ctx = mo::AsyncStreamFactory::instance()->create();
    auto obj = rcc::shared_ptr<int_output>::create();
    for (int i = 0; i < 100; ++i)
    {
        obj->process();
    }

    EXPECT_EQ(obj->counter, 100);
}

TEST(algorithm, counting_input)
{
    auto ctx = mo::AsyncStreamFactory::instance()->create();
    auto output = rcc::shared_ptr<int_output>::create();
    auto input = rcc::shared_ptr<int_input>::create();
    auto output_param = output->getOutput("value");
    auto input_param = input->getInput("input");
    EXPECT_NE(output_param, nullptr);
    EXPECT_NE(input_param, nullptr);
    EXPECT_EQ(input_param->setInput(output_param), true);
    for (int i = 0; i < 100; ++i)
    {
        output->process();
        input->process();
        EXPECT_EQ(output->counter, *input->input);
    }
}

TEST(algorithm, synced_input)
{
    auto ctx = mo::AsyncStreamFactory::instance()->create();
    mo::TPublisher<int> output;
    output.publish(10, mo::Header(0));
    auto input = rcc::shared_ptr<int_input>::create();
    input->input_param.setInput(&output);
    input->setSyncInput("input");
    for (int i = 0; i < 100; ++i)
    {
        output.publish(i + 1, i);
        EXPECT_EQ(input->process(), true);

        auto header = mo::Header(mo::FrameNumber(i));
        auto data = output.getData(&header, ctx.get());

        EXPECT_TRUE(data) << "Unable to retrieve data at fn=" << i + 1 << " what does exist is "
                          << output.getAvailableHeaders();
        auto ptr = data->ptr<int>();
        ASSERT_TRUE(ptr);
        EXPECT_EQ(input->value, *ptr) << "retrieved value does not match what we published";
        EXPECT_EQ(*ptr, i + 1);
        EXPECT_EQ(*input->input, input->value);
    }
}

TEST(algorithm, threaded_input)
{
    auto ctx = mo::AsyncStreamFactory::instance()->create();
    mo::TPublisher<int> output;
    output.setName("test");
    output.setStream(*ctx);
    // mo::getDefaultLogger().set_level(spdlog::level::trace);
    auto obj = rcc::shared_ptr<int_input>::create();
    std::atomic<int> success_count(0);
    boost::thread thread([&obj, &output, &success_count]() -> void {
        auto thread_stream = mo::AsyncStreamFactory::instance()->create();
        obj->setStream(thread_stream);
        ASSERT_TRUE(obj->connectInput(&obj->input_param, nullptr, &output));
        auto pub = obj->input_param.getPublisher();
        ASSERT_TRUE(pub);
        ASSERT_TRUE(pub->checkFlags(mo::ParamFlags::kBUFFER)) << "Failed to setup a buffered connection";

        while (success_count < 1000 && !boost::this_thread::interruption_requested())
        {
            if (obj->process())
            {
                ++success_count;
            }
        }
        obj->setStream(nullptr);
        boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
    });

    for (int i = 0; i < 1000; ++i)
    {
        output.publish(i, mo::Header(i));
        boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
    }

    const bool finished = thread.try_join_for(boost::chrono::seconds(5));
    EXPECT_TRUE(finished) << "expected to perform 1000 iterations, but instead performed only " << success_count;
    if (!finished)
    {
        thread.interrupt();
        thread.join();
    }

    // mo::getDefaultLogger().set_level(spdlog::level::info);
}

TEST(algorithm, desynced_input)
{
    const int iterations = 50;
    auto stream0 = mo::AsyncStreamFactory::instance()->create();
    auto stream1 = mo::AsyncStreamFactory::instance()->create();
    auto stream2 = mo::AsyncStreamFactory::instance()->create();

    ASSERT_NE(stream0.get(), stream1.get());
    ASSERT_NE(stream1.get(), stream2.get());

    mo::TPublisher<int> fast_output;
    mo::TPublisher<int> slow_output;

    fast_output.setName("fast");
    slow_output.setName("slow");

    slow_output.setStream(*stream1);
    fast_output.setStream(*stream0);

    fast_output.publish(0);
    slow_output.publish(0);

    auto data1 = fast_output.getData();
    auto data2 = slow_output.getData();

    auto obj = rcc::shared_ptr<multi_input>::create();

    boost::this_fiber::sleep_for(std::chrono::milliseconds(10));
    stream1->pushWork([&slow_output, iterations]() -> void {
        for (int i = 0; i < iterations; ++i)
        {
            slow_output.publish(i, mo::Header(i));
            boost::this_fiber::sleep_for(std::chrono::milliseconds(10));
        }
        // slow_output.setStream(nullptr);
        MO_LOG(info, "Publishing thread finished");
    });

    obj->setStream(stream2);

    stream2->pushWork([&obj, &fast_output, &slow_output, iterations]() -> void {
        EXPECT_TRUE(obj->connectInput(&obj->input1_param, nullptr, &fast_output));
        EXPECT_TRUE(obj->connectInput(&obj->input2_param, nullptr, &slow_output));

        auto pub1 = obj->input1_param.getPublisher();
        auto pub2 = obj->input2_param.getPublisher();

        ASSERT_NE(pub1, nullptr) << "Did not correctly connect a publisher to this subscriber";
        ASSERT_NE(pub2, nullptr) << "Did not correctly connect a publisher to this subscriber";

        EXPECT_TRUE(pub1->checkFlags(mo::ParamFlags::kBUFFER)) << "Did not correctly negotiate a buffered connection";
        EXPECT_TRUE(pub2->checkFlags(mo::ParamFlags::kBUFFER)) << "Did not correctly negotiate a buffered connection";

        int success_count = 0;

        // mo::getDefaultLogger().set_level(spdlog::level::trace);
        while (success_count < iterations - 1)
        {
            if (obj->process())
            {
                ++success_count;
            }
            else
            {
                boost::this_fiber::sleep_for(std::chrono::milliseconds(30));
            }
        }
        MO_LOG(info, "Subscribing thread finished");
    });

    for (int i = 0; i < iterations; ++i)
    {
        fast_output.publish(i, mo::Header(i));
        boost::this_fiber::sleep_for(std::chrono::milliseconds(1));
    }
    boost::this_fiber::sleep_for(std::chrono::milliseconds(100));
}

max_stars_repo_name: dtmoodie/Acquilla

max_issues_repo_name: dtmoodie/Acquilla

max_forks_repo_name: dtmoodie/Acquilla


text:
// ****************************************************************************
// test/entity_lifetimes.cpp
//
// Part of the test harness for entity.
//
// Copyright Chris Glover 2014-2016
//
// 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 "entity/component/saturated_pool.hpp"
#include "entity/entity_pool.hpp"
#include "entity/entity.hpp"

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

BOOST_AUTO_TEST_CASE( manual_ownership )
{
	entity::entity_pool entities;
	entities.create();
	BOOST_CHECK_EQUAL(entities.size(), 1);
	entities.create();
	BOOST_CHECK_EQUAL(entities.size(), 2);
	entities.destroy(entity::make_entity(0));
	BOOST_CHECK_EQUAL(entities.size(), 1);
	entities.destroy(entity::make_entity(0));
	BOOST_CHECK(entities.empty());
}

BOOST_AUTO_TEST_CASE( unique_ownership )
{
	// Doesnt compile on MSVC < 1900 due
	// to that compiler not correctly generating
	// implicit move operations.
#if _MSC_VER >= 1900
	entity::entity_pool entities;
	entity::unique_entity e = entities.create_unique();
	BOOST_CHECK_EQUAL(entities.size(), 1);
	entity::unique_entity e2 = entities.create_unique();
	BOOST_CHECK_EQUAL(entities.size(), 2);
	e = std::move(e2);
	BOOST_CHECK_EQUAL(entities.size(), 1);
	e2.clear();
	BOOST_CHECK_EQUAL(entities.size(), 1);
	e.clear();
	BOOST_CHECK(entities.empty());
#endif
}

BOOST_AUTO_TEST_CASE( shared_ownership )
{
	entity::entity_pool entities;
	entity::shared_entity e = entities.create_shared();
	BOOST_CHECK_EQUAL(entities.size(), 1);
	entity::shared_entity e2 = entities.create_shared();
	BOOST_CHECK_EQUAL(entities.size(), 2);
	e = e2;
	BOOST_CHECK_EQUAL(entities.size(), 1);
	e.clear();
	BOOST_CHECK_EQUAL(entities.size(), 1);
	e2.clear();
	BOOST_CHECK(entities.empty());
}

max_stars_repo_name: cdglove/entity

max_issues_repo_name: cdglove/entity

max_forks_repo_name: cdglove/entity


text:
/*
	Copyright (c) 2007, Cory Nelson
	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 Int64.org 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 REGENTS 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 REGENTS AND 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.

	Contact Info:
		email:   phrosty@gmail.com
		website: http://www.int64.org
*/

#ifndef UNICODE_HPP
#define UNICODE_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif

#include <cstddef>
#include <iterator>
#include <algorithm>
#include <stdexcept>
#include <boost/cstdint.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/sizeof.hpp>

namespace unicode {
	typedef boost::uint8_t utf8_t;
	typedef boost::uint16_t utf16_t;
	typedef boost::uint32_t utf32_t;

	class unicode_error : public std::exception {
	private:
		const char* const m_msg;

	public:
		unicode_error(const char *msg) : m_msg(msg) {}
		const char* what() const throw() { return m_msg; }
	};

	class utf8 {
	private:
		template<typename InputIterator>
		static utf32_t decode_part(InputIterator &iter, InputIterator &end) {
			if(iter == end) {
				throw unicode_error("incomplete utf-8 sequence");
			}

			utf32_t part = static_cast<utf8_t>(*iter);

			if((part & 0xC0) != 0x80) {
				throw unicode_error("invalid utf-8 octet");
			}

			++iter;
			return part & 0x3F;
		}

	public:
		typedef utf8_t char_type;
		static const unsigned int max_encodelen = 4;

		template<typename InputIterator>
		static utf32_t decode(InputIterator &iter, InputIterator &end) {
			utf32_t part, val = 0;

			if(iter == end) {
				throw unicode_error("empty iterator range");
			}

			part = static_cast<utf8_t>(*iter);
			if(!(part & 0x80)) { // 1 octet
				++iter;
				val = part;
			}
			else if((part & 0xE0) == 0xC0) { // 2 octets
				++iter;
				val = (part & 0x1F) << 6;
				val |= decode_part(iter, end);

				if(val < 0x80) {
					throw unicode_error("overlong utf-8 sequence");
				}
			}
			else if((part & 0xF0) == 0xE0) { // 3 octets
				++iter;
				val = (part & 0xF) << 12;
				val |= decode_part(iter, end) << 6;
				val |= decode_part(iter, end);

				if(val < 0x800) {
					throw unicode_error("overlong utf-8 sequence");
				}
			}
			else if((part & 0xF8) == 0xF0) { // 4 octets
				++iter;
				val = (part & 0x7) << 18;
				val |= decode_part(iter, end) << 12;
				val |= decode_part(iter, end) << 6;
				val |= decode_part(iter, end);

				if(val < 0x10000) {
					throw unicode_error("overlong utf-8 sequence");
				}
			}
			else {
				throw unicode_error("invalid utf-8 octet");
			}

			if(val > 0x10FFFF) {
				throw unicode_error("invalid unicode character");
			}

			return val;
		}

		template<typename OutputIterator>
		static OutputIterator encode(utf32_t val, OutputIterator iter) {
			if(val <= 0x7F) {
				*iter = static_cast<utf8_t>(val); ++iter;
			}
			else if(val <= 0x7FF) {
				*iter = static_cast<utf8_t>(0xC0 | ((val & 0x7C0) >> 6)); ++iter;
				*iter = static_cast<utf8_t>(0x80 | (val & 0x3F)); ++iter;
			}
			else if(val <= 0xFFFF) {
				*iter = static_cast<utf8_t>(0xE0 | ((val & 0xF000) >> 12)); ++iter;
				*iter = static_cast<utf8_t>(0x80 | ((val & 0xFC0) >> 6)); ++iter;
				*iter = static_cast<utf8_t>(0x80 | (val & 0x3F)); ++iter;
			}
			else if(val <= 0x10FFFF) {
				*iter = static_cast<utf8_t>(0xF0 | ((val & 0x1C0000) >> 18)); ++iter;
				*iter = static_cast<utf8_t>(0x80 | ((val & 0x3F000) >> 12)); ++iter;
				*iter = static_cast<utf8_t>(0x80 | ((val & 0xFC0) >> 6)); ++iter;
				*iter = static_cast<utf8_t>(0x80 | (val & 0x3F)); ++iter;
			}
			else {
				throw unicode_error("invalid unicode character");
			}

			return iter;
		}
	};

	struct host_endian {
		static utf16_t swap(utf16_t i) { return i; }
		static utf32_t swap(utf32_t i) { return i; }
	};

	struct swap_endian {
		static utf16_t swap(utf16_t i) { return (i >> 8) | (i << 8); }

		static utf32_t swap(utf32_t i) {
			return (
				(i >> 24) |
				((i & 0x00FF0000) >> 8) |
				((i & 0x0000FF00) << 8) |
				(i << 24)
			);
		}
	};

#ifdef BIG_ENDIAN
	typedef swap_endian little_endian;
	typedef host_endian big_endian;
#else
	typedef host_endian little_endian;
	typedef swap_endian big_endian;
#endif

	template<typename Endian>
	class utf16 {
	public:
		typedef utf16_t char_type;
		static const unsigned int max_encodelen = 2;

		template<typename InputIterator>
		static utf32_t decode(InputIterator &iter, InputIterator &end) {
			utf32_t part, val = 0;

			if(iter == end) {
				throw unicode_error("empty iterator range");
			}

			part = Endian::swap(static_cast<utf16_t>(*iter));
			if(part < 0xD800 || part > 0xDFFF) {
				val = part;
			}
			else {
				val = (part & 0x3FF) << 10;

				if(++iter == end) {
					throw unicode_error("incomplete utf-16 surrogate pair");
				}

				part = Endian::swap(static_cast<utf16_t>(*iter));
				val |= (part & 0x3FF);
			}

			++iter;

			if(val > 0x10FFFF) {
				throw unicode_error("invalid unicode character");
			}

			return val;
		}

		template<typename OutputIterator>
		static OutputIterator encode(utf32_t val, OutputIterator iter) {
			if(val <= 0xFFFF) {
				*iter = Endian::swap(static_cast<utf16_t>(val)); ++iter;
			}
			else if(val <= 0x10FFFF) {
				val -= 0x10000;

				*iter = Endian::swap(static_cast<utf16_t>(0xD800 | (val >> 10))); ++iter;
				*iter = Endian::swap(static_cast<utf16_t>(0xDC00 | (val & 0x3FF))); ++iter;
			}
			else {
				throw unicode_error("invalid unicode character");
			}

			return iter;
		}
	};

	typedef utf16<little_endian> utf16le;
	typedef utf16<big_endian> utf16be;

	template<typename Endian>
	class utf32 {
	public:
		typedef utf32_t char_type;
		static const unsigned int max_encodelen = 1;

		template<typename InputIterator>
		static utf32_t decode(InputIterator &iter, InputIterator &end) {
			if(iter == end) {
				throw unicode_error("empty iterator range");
			}

			utf32_t val = Endian::swap(static_cast<utf32_t>(*iter)); ++iter;

			if(val > 0x10FFFF) {
				throw unicode_error("invalid unicode character");
			}

			return val;
		}

		template<typename OutputIterator>
		static OutputIterator encode(utf32_t val, OutputIterator iter) {
			if(val > 0x10FFFF) {
				throw unicode_error("invalid unicode character");
			}

			*iter = Endian::swap(val);
			return ++iter;
		}
	};

	typedef utf32<little_endian> utf32le;
	typedef utf32<big_endian> utf32be;

	// wchar_encoding is a typedef for the proper encoding for your platform.  assumes wchar_t is UTF-16 or UTF-32.
	typedef boost::mpl::if_<
		boost::mpl::equal_to<boost::mpl::sizeof_<wchar_t>, boost::mpl::sizeof_<utf16_t> >,
		utf16<host_endian>,
		utf32<host_endian>
	>::type wchar_encoding;

	template<typename InEnc, typename OutEnc, typename InputIterator>
	class transcode_iterator : public std::iterator<std::input_iterator_tag, typename OutEnc::char_type> {
	public:
		typedef InEnc input_encoding;
		typedef OutEnc output_encoding;
		typedef InputIterator iterator_type;

		typedef std::iterator<std::input_iterator_tag, typename OutEnc::char_type> base_type;
		typedef transcode_iterator<input_encoding, output_encoding, iterator_type> this_type;

	private:
		iterator_type m_iter, m_end;
		typename base_type::value_type m_out[OutEnc::max_encodelen];
		unsigned int m_outpos, m_outlen;
		typename base_type::value_type m_ch;
		bool m_done;

		void getval() {
			if(!m_done) {
				if(m_outlen) {
					m_ch = m_out[m_outpos];

					if(++m_outpos == m_outlen) {
						m_outlen = 0;
					}
				}
				else {
					if(m_iter != m_end) {
						utf32_t ch = InEnc::decode(m_iter, m_end);

						typename base_type::value_type *end = OutEnc::encode(ch, m_out);

						if(OutEnc::max_encodelen > 1) {
							unsigned int len = static_cast<unsigned int>(std::distance(m_out, end));

							if(len > 1) {
								m_outpos = 1;
								m_outlen = len;
							}
						}

						m_ch = m_out[0];
					}
					else {
						m_done = true;
					}
				}
			}
		}

	public:
		transcode_iterator() : m_done(true) {}
		transcode_iterator(iterator_type iter, iterator_type end) : m_iter(iter),m_end(end),m_outpos(0),m_outlen(0),m_done(false) {
			getval();
		}

		this_type& operator++() {
			getval();
			return *this;
		}

		this_type operator++(int) {
			this_type ret = *this;
			++*this;
			return ret;
		}

		bool operator==(const this_type &iter) const { return m_done == iter.m_done; }
		bool operator!=(const this_type &iter) const { return m_done != iter.m_done; }

		const typename base_type::value_type operator*() const { return m_ch; }
	};

	template<typename InEnc, typename OutEnc, typename InputIterator, typename OutputIterator>
	OutputIterator transcode(InputIterator iter, InputIterator end, OutputIterator out) {
		while(iter != end) {
			utf32_t ch = InEnc::decode(iter, end);
			out = OutEnc::encode(ch, out);
		}

		return out;
	}

	namespace detail {
		template<typename LengthT, typename CharT>
		class length_iterator : public std::iterator<std::output_iterator_tag, CharT> {
		public:
      typedef std::iterator<std::output_iterator_tag, CharT> base_type;
			typedef length_iterator<LengthT, CharT> this_type;

		private:
			LengthT m_len;
			CharT m_ch;

		public:
			length_iterator() : m_len(0) {}

			this_type& operator++() { return *this; }

			this_type operator++(int) {
				this_type ret = *this;
				++*this;
				return ret;
			}

			typename base_type::value_type& operator*() { return m_ch; }

			LengthT length() const { return m_len; }
		};
	}

	template<typename InEnc, typename OutEnc, typename InputIterator>
	typename std::iterator_traits<InputIterator>::difference_type transcode_length(InputIterator iter, InputIterator end) {
		typedef typename std::iterator_traits<InputIterator>::difference_type length_type;
		typedef detail::length_iterator<length_type, typename OutEnc::char_type> length_iterator;

		return transcode<InEnc, OutEnc, InputIterator>(iter, end, length_iterator()).length();
	}

	template<typename InEnc, typename InputIterator>
	typename std::iterator_traits<InputIterator>::difference_type length(InputIterator iter, InputIterator end) {
		typename std::iterator_traits<InputIterator>::difference_type len = 0;

		while(iter != end) {
			InEnc::decode(iter, end);
			++len;
		}

		return len;
	}
}

#endif

ext: hpp

max_stars_repo_name: xeddmc/Halite

max_issues_repo_name: ialexsilva/Halite

max_forks_repo_name: ialexsilva/Halite


text: #include <boost/mpi/collectives/all_reduce.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (C) 2014-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef VSOMEIP_V3_CONFIGURATION_HPP
#define VSOMEIP_V3_CONFIGURATION_HPP

#include <map>
#include <memory>
#include <set>
#include <string>
#include <chrono>

#include <boost/asio/ip/address.hpp>
#include <boost/icl/interval_set.hpp>

#include <vsomeip/export.hpp>
#include <vsomeip/defines.hpp>
#include <vsomeip/plugin.hpp>
#include <vsomeip/primitive_types.hpp>

#include "trace.hpp"

#include "../../e2e_protection/include/e2exf/config.hpp"
#include "e2e.hpp"

#include "debounce.hpp"

#ifdef ANDROID
#include "internal_android.hpp"
#else
#include "internal.hpp"
#endif // ANDROID

#include "../../security/include/policy.hpp"

#define VSOMEIP_CONFIG_PLUGIN_VERSION              1

namespace vsomeip_v3 {

class event;

class configuration {
public:
    virtual ~configuration()
#ifndef ANDROID
    {}
#else
    ;
#endif

    virtual bool load(const std::string &_name) = 0;
    virtual bool remote_offer_info_add(service_t _service,
                                       instance_t _instance,
                                       std::uint16_t _port,
                                       bool _reliable,
                                       bool _magic_cookies_enabled) = 0;
    virtual bool remote_offer_info_remove(service_t _service,
                                          instance_t _instance,
                                          std::uint16_t _port,
                                          bool _reliable,
                                          bool _magic_cookies_enabled,
                                          bool* _still_offered_remote) = 0;

    virtual const std::string &get_network() const = 0;

    virtual const boost::asio::ip::address & get_unicast_address() const = 0;
    virtual const boost::asio::ip::address& get_netmask() const = 0;
    virtual const std::string &get_device() const = 0;
    virtual diagnosis_t get_diagnosis_address() const = 0;
    virtual diagnosis_t get_diagnosis_mask() const = 0;
    virtual bool is_v4() const = 0;
    virtual bool is_v6() const = 0;

    virtual bool has_console_log() const = 0;
    virtual bool has_file_log() const = 0;
    virtual bool has_dlt_log() const = 0;
    virtual const std::string & get_logfile() const = 0;
    virtual logger::level_e get_loglevel() const = 0;

    virtual const std::string & get_routing_host() const = 0;

    virtual std::string get_unicast_address(service_t _service,
            instance_t _instance) const = 0;
    virtual uint16_t get_reliable_port(service_t _service,
            instance_t _instance) const = 0;
    virtual bool has_enabled_magic_cookies(std::string _address,
            uint16_t _port) const = 0;
    virtual uint16_t get_unreliable_port(service_t _service,
            instance_t _instance) const = 0;

    virtual major_version_t get_major_version(service_t _service,
            instance_t _instance) const = 0;
    virtual minor_version_t get_minor_version(service_t _service,
            instance_t _instance) const = 0;
    virtual ttl_t get_ttl(service_t _service,
            instance_t _instance) const = 0;

    virtual void get_configured_timing_requests(
            service_t _service, std::string _ip_target,
            std::uint16_t _port_target, method_t _method,
            std::chrono::nanoseconds *_debounce_time,
            std::chrono::nanoseconds *_max_retention_time) const = 0;
    virtual void get_configured_timing_responses(
            service_t _service, std::string _ip_service,
            std::uint16_t _port_service, method_t _method,
            std::chrono::nanoseconds *_debounce_time,
            std::chrono::nanoseconds *_max_retention_time) const = 0;

    virtual bool is_someip(service_t _service, instance_t _instance) const = 0;

    virtual bool get_client_port(service_t _service, instance_t _instance,
            uint16_t _remote_port, bool _reliable,
            std::map<bool, std::set<uint16_t> > &_used_client_ports, uint16_t &_client_port) const = 0;

    virtual std::set<std::pair<service_t, instance_t> > get_remote_services() const = 0;

    virtual bool get_multicast(service_t _service, instance_t _instance,
            eventgroup_t _eventgroup, std::string &_address, uint16_t &_port) const = 0;

    virtual uint8_t get_threshold(service_t _service, instance_t _instance,
            eventgroup_t _eventgroup) const = 0;

    virtual client_t get_id(const std::string &_name) const = 0;
    virtual bool is_configured_client_id(client_t _id) const = 0;

    virtual std::size_t get_max_dispatchers(const std::string &_name) const = 0;
    virtual std::size_t get_max_dispatch_time(const std::string &_name) const = 0;
    virtual std::size_t get_io_thread_count(const std::string &_name) const = 0;
    virtual int get_io_thread_nice_level(const std::string &_name) const = 0;
    virtual std::size_t get_request_debouncing(const std::string &_name) const = 0;
#ifdef VSOMEIP_HAS_SESSION_HANDLING_CONFIG
    virtual bool has_session_handling(const std::string &_name) const = 0;
#endif // VSOMEIP_HAS_SESSION_HANDLING_CONFIG

    virtual std::uint32_t get_max_message_size_local() const = 0;
    virtual std::uint32_t get_max_message_size_reliable(const std::string& _address,
                                                    std::uint16_t _port) const = 0;
    virtual std::uint32_t get_max_message_size_unreliable() const = 0;
    virtual std::uint32_t get_buffer_shrink_threshold() const = 0;

    virtual bool supports_selective_broadcasts(boost::asio::ip::address _address) const = 0;

    virtual bool is_offered_remote(service_t _service, instance_t _instance) const = 0;

    virtual bool is_local_service(service_t _service, instance_t _instance) const = 0;

    virtual reliability_type_e get_event_reliability(
            service_t _service, instance_t _instance, event_t _event) const = 0;
    virtual reliability_type_e get_service_reliability(
            service_t _service, instance_t _instance) const = 0;

    // Service Discovery configuration
    virtual bool is_sd_enabled() const = 0;

    virtual const std::string & get_sd_multicast() const = 0;
    virtual uint16_t get_sd_port() const = 0;
    virtual const std::string & get_sd_protocol() const = 0;

    virtual uint32_t get_sd_initial_delay_min() const = 0;
    virtual uint32_t get_sd_initial_delay_max() const = 0;
    virtual int32_t get_sd_repetitions_base_delay() const = 0;
    virtual uint8_t get_sd_repetitions_max() const = 0;
    virtual ttl_t get_sd_ttl() const = 0;
    virtual int32_t get_sd_cyclic_offer_delay() const = 0;
    virtual int32_t get_sd_request_response_delay() const = 0;
    virtual std::uint32_t get_sd_offer_debounce_time() const = 0;

    // Trace configuration
    virtual std::shared_ptr<cfg::trace> get_trace() const = 0;

    // Watchdog
    virtual bool is_watchdog_enabled() const = 0;
    virtual uint32_t get_watchdog_timeout() const = 0;
    virtual uint32_t get_allowed_missing_pongs() const = 0;

    // File permissions
    virtual std::uint32_t get_permissions_uds() const = 0;
    virtual std::uint32_t get_permissions_shm() const = 0;

    virtual bool log_version() const = 0;
    virtual uint32_t get_log_version_interval() const = 0;

    // Plugins
    virtual std::map<plugin_type_e, std::set<std::string>> get_plugins(
            const std::string &_name) const = 0;

    virtual void set_configuration_path(const std::string &_path) = 0;

    //E2E
    virtual std::map<e2exf::data_identifier_t, std::shared_ptr<cfg::e2e>> get_e2e_configuration() const = 0;
    virtual bool is_e2e_enabled() const = 0;

    virtual bool log_memory() const = 0;
    virtual uint32_t get_log_memory_interval() const = 0;

    virtual bool log_status() const = 0;
    virtual uint32_t get_log_status_interval() const = 0;

    // TTL factor
    typedef std::uint32_t ttl_factor_t;
    typedef std::map<service_t, std::map<instance_t, ttl_factor_t>> ttl_map_t;
    virtual ttl_map_t get_ttl_factor_offers() const = 0;
    virtual ttl_map_t get_ttl_factor_subscribes() const = 0;

    // Debouncing
    virtual std::shared_ptr<cfg::debounce> get_debounce(
            service_t _service, instance_t _instance, event_t _event) const = 0;

    // Queue size limit endpoints
    typedef std::uint32_t endpoint_queue_limit_t;
    virtual endpoint_queue_limit_t get_endpoint_queue_limit(
            const std::string& _address, std::uint16_t _port) const = 0;
    virtual endpoint_queue_limit_t get_endpoint_queue_limit_local() const = 0;

    virtual std::uint32_t get_max_tcp_restart_aborts() const = 0;
    virtual std::uint32_t get_max_tcp_connect_time() const = 0;

    // Acceptance handling
    virtual bool is_protected_device(
            const boost::asio::ip::address& _address) const = 0;
    virtual bool is_protected_port(
            const boost::asio::ip::address& _address, std::uint16_t _port,
            bool _reliable) const = 0;
    virtual bool is_secure_port(
                const boost::asio::ip::address& _address, std::uint16_t _port,
                bool _reliable) const = 0;

    typedef std::pair<std::uint16_t, std::uint16_t> port_range_t;
    virtual void set_sd_acceptance_rule(
            const boost::asio::ip::address &_address,
            port_range_t _port_range, port_type_e _type,
            const std::string &_path, bool _reliable, bool _enable, bool _default) = 0;

    typedef std::map<
        boost::asio::ip::address, // other device
        std::pair<
            std::string, // path to file that determines whether or not IPsec is active
            std::map<
                bool, // false = unreliable (aka UDP), true = reliable (aka TCP)
                std::pair<
                    boost::icl::interval_set<std::uint16_t>, // optional (aka semi-secure) port range
                    boost::icl::interval_set<std::uint16_t>  // secure port range
                >
            >
        >
    > sd_acceptance_rules_t;
    virtual void set_sd_acceptance_rules(const sd_acceptance_rules_t& _rules,
                                         bool _enable) = 0;
    virtual sd_acceptance_rules_t get_sd_acceptance_rules() = 0;
    virtual void set_sd_acceptance_rules_active(
            const boost::asio::ip::address& _address, bool _enable) = 0;

    virtual bool is_secure_service(service_t _service, instance_t _instance) const = 0;

    virtual std::uint32_t get_udp_receive_buffer_size() const = 0;

    virtual bool check_routing_credentials(client_t _client, uint32_t _uid, uint32_t _gid) const = 0;

    // SOME/IP-TP
    virtual bool tp_segment_messages_client_to_service(
            service_t _service, std::string _ip_target,
            std::uint16_t _port_target, method_t _method) const = 0;
    virtual bool tp_segment_messages_service_to_client(
            service_t _service, std::string _ip_service,
            std::uint16_t _port_service, method_t _method) const = 0;

    // routing shutdown timeout
    virtual std::uint32_t get_shutdown_timeout() const = 0;

    virtual bool log_statistics() const = 0;
    virtual uint32_t get_statistics_interval() const = 0;
    virtual uint32_t get_statistics_min_freq() const = 0;
    virtual uint32_t get_statistics_max_messages() const = 0;
};

} // namespace vsomeip_v3

#endif // VSOMEIP_V3_CONFIGURATION_HPP

max_stars_repo_name: lixiaolia/ndk-someip-lib

max_issues_repo_name: lixiaolia/ndk-someip-lib

max_forks_repo_name: lixiaolia/ndk-someip-lib


text:
/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2018, Locus Robotics
 *  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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */
#include <fuse_models/unicycle_2d_state_cost_function.h>
#include <fuse_models/unicycle_2d_state_cost_functor.h>

#include <gtest/gtest.h>
#include <fuse_core/eigen_gtest.h>

#include <ceres/autodiff_cost_function.h>
#include <ceres/gradient_checker.h>
#include <Eigen/Dense>

#include <limits>
#include <vector>

TEST(CostFunction, evaluateCostFunction)
{
  // Create cost function
  const double process_noise_diagonal[] = { 1e-3, 1e-3, 1e-2, 1e-6, 1e-6, 1e-4, 1e-9, 1e-9 };
  const fuse_core::Matrix8d covariance = fuse_core::Vector8d(process_noise_diagonal).asDiagonal();

  const double dt{ 0.1 };
  const fuse_core::Matrix8d sqrt_information{ covariance.inverse().llt().matrixU() };

  const fuse_models::Unicycle2DStateCostFunction cost_function{ dt, sqrt_information };

  // Evaluate cost function
  const double position1[] = {0.0, 0.0};
  const double yaw1[] = {0.0};
  const double vel_linear1[] = {1.0, 0.0};
  const double vel_yaw1[] = {1.570796327};
  const double acc_linear1[] = {1.0, 0.0};

  const double position2[] = {0.105, 0.0};
  const double yaw2[] = {0.1570796327};
  const double vel_linear2[] = {1.1, 0.0};
  const double vel_yaw2[] = {1.570796327};
  const double acc_linear2[] = {1.0, 0.0};

  const double* parameters[] =
  {
    position1, yaw1, vel_linear1, vel_yaw1, acc_linear1,
    position2, yaw2, vel_linear2, vel_yaw2, acc_linear2
  };

  fuse_core::Vector8d residuals;

  const auto& block_sizes = cost_function.parameter_block_sizes();
  const auto num_parameter_blocks = block_sizes.size();

  const auto num_residuals = cost_function.num_residuals();

  std::vector<fuse_core::MatrixXd> J(num_parameter_blocks);
  std::vector<double*> jacobians(num_parameter_blocks);

  for (size_t i = 0; i < num_parameter_blocks; ++i)
  {
    J[i].resize(num_residuals, block_sizes[i]);
    jacobians[i] = J[i].data();
  }

  EXPECT_TRUE(cost_function.Evaluate(parameters, residuals.data(), jacobians.data()));

  // We cannot use std::numeric_limits<double>::epsilon() tolerance because with the expected state2 above the residuals
  // are not zero for position2.x = -4.389e-16 and yaw2 = -2.776e-16
  EXPECT_MATRIX_NEAR(fuse_core::Vector8d::Zero(), residuals, 1e-15);

  // Check jacobians are correct using a gradient checker
  ceres::NumericDiffOptions numeric_diff_options;
  ceres::GradientChecker gradient_checker(&cost_function, NULL, numeric_diff_options);

  // We cannot use std::numeric_limits<double>::epsilon() tolerance because the worst relative error is 5.26356e-10
  ceres::GradientChecker::ProbeResults probe_results;
  // TODO(efernandez) probe_results segfaults when it's destroyed at the end of this TEST function, but Probe actually
  // returns true and the jacobians are correct according to the gradient checker numeric differentiation
  // EXPECT_TRUE(gradient_checker.Probe(parameters, 1e-9, &probe_results)) << probe_results.error_log;

  // Create cost function using automatic differentiation on the cost functor
  ceres::AutoDiffCostFunction<fuse_models::Unicycle2DStateCostFunctor, 8, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2>
      cost_function_autodiff(new fuse_models::Unicycle2DStateCostFunctor(dt, sqrt_information));

  // Evaluate cost function that uses automatic differentiation
  std::vector<fuse_core::MatrixXd> J_autodiff(num_parameter_blocks);
  std::vector<double*> jacobians_autodiff(num_parameter_blocks);

  for (size_t i = 0; i < num_parameter_blocks; ++i)
  {
    J_autodiff[i].resize(num_residuals, block_sizes[i]);
    jacobians_autodiff[i] = J_autodiff[i].data();
  }

  EXPECT_TRUE(cost_function_autodiff.Evaluate(parameters, residuals.data(), jacobians_autodiff.data()));

  const Eigen::IOFormat HeavyFmt(
      Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[", "]");

  for (size_t i = 0; i < num_parameter_blocks; ++i)
  {
    EXPECT_MATRIX_NEAR(J_autodiff[i], J[i], std::numeric_limits<double>::epsilon())
      << "Autodiff Jacobian[" << i << "] =\n" << J_autodiff[i].format(HeavyFmt)
      << "\nAnalytic Jacobian[" << i << "] =\n" << J[i].format(HeavyFmt);
  }
}

int main(int argc, char **argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

max_stars_repo_name: mcx/fuse

max_issues_repo_name: mcx/fuse

max_forks_repo_name: mcx/fuse


text:
//
#include "spack.h"

#include <cstdint>
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/replace.hpp>

#include "sections_packer.h"
#include "import_packer.h"
#include "stub_packer.h"
#include "loader_packer.h"
#include "new_pe_builder.h"
#include "file_utils.h"
#include "tiny_logger.h"

typedef std::shared_ptr<PeLib::PeFile> PeFilePtr;

template <class PeFileType>
void LoadPeFile(PeFileType& pef)
{
  pef->readMzHeader();
  pef->readPeHeader();

  pef->readExportDirectory();
  pef->readImportDirectory();
  pef->readResourceDirectory();
  pef->readExportDirectory();
  // <-- security directory ???
  pef->readRelocationsDirectory();
  pef->readDebugDirectory();
  // <-- Architecture Specific Data ???
  // <-- RVA of GP
  pef->readTlsDirectory();
  // <-- Load Config Directory ???
  pef->readBoundImportDirectory();
  pef->readIatDirectory();
  // <-- Delay Import Descriptors ???
  pef->readComHeaderDirectory();
  // <-- Reserved ???
}

ErrorCode PackExecutable(const std::string& srcFileName, const std::string& outFileName)
{
  try
  {
    if (!boost::filesystem::exists(srcFileName))
    {
      return ErrorCode::FILE_NOT_FOUND;
    }

    auto sourceFileBuff = file_utils::readFile(srcFileName.c_str());
    decltype(sourceFileBuff) outFileBuff;

    if (boost::filesystem::exists(outFileName))
    {
      boost::filesystem::remove(outFileName);
    }

    auto pef = PeLib::openPeFile(srcFileName);
    if (!pef)
    {
      std::cout << "Invalid PE File" << std::endl;
      return ErrorCode::INVALID_PE_FILE;
    }

    // stores data sizes required by different packers
    std::vector<RequiredDataBlock> additionalSizeRequest;

    LoadPeFile(pef);
    //-----------------------------------------------------

    ImportPacker importPacker(pef);
    auto requiredImportDataBlocks = importPacker.GetRequiredDataBlocks();
    // moving required import blocks
    additionalSizeRequest = std::move(requiredImportDataBlocks);

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

    LoaderPacker loaderPacker(pef);
    auto requiredLoaderBlock = loaderPacker.GetRequiredDataBlocks();
    std::move(requiredLoaderBlock.begin(), requiredLoaderBlock.end(), std::back_inserter(additionalSizeRequest));

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

    StubPacker stubPacker(pef);
    auto stubRequiredBlocks = stubPacker.GetRequiredDataBlocks();
    std::move(stubRequiredBlocks.begin(), stubRequiredBlocks.end(), std::back_inserter(additionalSizeRequest));

    SectionsPacker sectionsPacker(pef);

    //-----------------------------------------------------
    // generating output file contents

    NewPEBuilder newPEBuilder(pef, sourceFileBuff, additionalSizeRequest, &importPacker, &stubPacker, &sectionsPacker, &loaderPacker);

    auto outBuffer = newPEBuilder.GenerateOutputPEFile().get();

    file_utils::writeFile(outFileName.c_str(), 0, reinterpret_cast<const char*>(outBuffer.data()), outBuffer.size());

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

    return ErrorCode::ERROR_SUCC;
  }
  catch (std::runtime_error& err)
  {
    std::cout << err.what();
  }

  return ErrorCode::FATAL_ERROR;
}

max_stars_repo_name: ChaitanyaHaritash/PackerPE

max_issues_repo_name: ChaitanyaHaritash/PackerPE

max_forks_repo_name: azerg/PackerPE


text:
#include <boost/python.hpp>
#include "laplacian_foveation.hpp"

using namespace boost::python;
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(foveate, LaplacianBlending::Foveate, 1, 2)

BOOST_PYTHON_MODULE(yolt_python)
{
    class_< LaplacianBlending >("LaplacianBlending", init<const int,const int,const int,const int,const int >())
      .def("foveate", &LaplacianBlending::Foveate)//args("center"), "foveation function"));
      .def("update_fovea", &LaplacianBlending::CreateFilterPyr);//args("center"), "foveation function"));
}

max_stars_repo_name: pedro-abreu/twostream-attention

max_issues_repo_name: pedro-abreu/twostream-attention

max_forks_repo_name: pedro-abreu/twostream-attention


text:
/*
* Software License Agreement (BSD License)
*
*  Copyright (c) 2014-2015, Timm Linder, Fabian Girrbach, Social Robotics Lab, University of Freiburg
*  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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE
*  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
*  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
*  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <srl_nearest_neighbor_tracker/data_association/basic_nearest_neighbor_data_association.h>

#include <srl_nearest_neighbor_tracker/base/defs.h>
#include <srl_nearest_neighbor_tracker/base/stl_helpers.h>
#include <srl_nearest_neighbor_tracker/ros/params.h>
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH

#include <Eigen/LU>
#include <limits>
#include <map>

namespace srl_nnt {

void BasicNearestNeighborDataAssociation::initializeDataAssociation(const ros::NodeHandle& nodeHandle, const ros::NodeHandle& privateNodeHandle) {
    m_nodeHandle = nodeHandle;
    m_privateNodeHandle = privateNodeHandle;
}

Pairings BasicNearestNeighborDataAssociation::performDataAssociation(Tracks& tracks, const Observations& observations){

    ROS_DEBUG("Performing data association");

    //
    // Step 0: Make sure observations are in a good state
    //

    foreach(Observation::Ptr observation, observations) {
        observation->matched = false;
    }

    Pairings compatiblePairings;

    //
    // Step 1: go through all possible associations and store compatible ones
    //

    const double MATRIX_LN_EPS = -1e8;
    const double MAX_GATING_DISTANCE = Params::get<double>("max_gating_distance", 1.0);

    typedef multimap<track_id, Pairing::Ptr> TrackSpecificPairings;
    TrackSpecificPairings trackSpecificPairings;

    ObsVector v;
    foreach(Track::Ptr track, tracks)
    {
        foreach(Observation::Ptr observation, observations)
                                                                                {
            v = observation->z - track->state->zp();

            if(v.norm() < MAX_GATING_DISTANCE)
            {
                // Create a new pairing
                Pairing::Ptr pairing( new Pairing );

                pairing->track = track;
                pairing->observation = observation;
                pairing->validated = false;

                // Calculate innovation v and inverse of innovation covariance S
                pairing->v = v;

                ObsMatrix S = track->state->H() * track->state->Cp() * track->state->H().transpose() + observation->R;
                Eigen::FullPivLU<ObsMatrix> lu(S);
                double ln_det_S = log(lu.determinant());

                // Calculate inverse of innovation covariance if possible
                if (ln_det_S > MATRIX_LN_EPS) {
                    pairing->Sinv = lu.inverse();
                    pairing->d = (pairing->v.transpose() * pairing->Sinv * pairing->v)(0,0);
                    pairing->singular = pairing->d < 0.0;
                }
                else {
                    pairing->Sinv = ObsMatrix::Constant(OBS_DIM, OBS_DIM, numeric_limits<double>::quiet_NaN());
                    pairing->d = numeric_limits<double>::quiet_NaN();
                    pairing->singular = true;

                    ROS_WARN_STREAM("Singular pairing encountered!\nTrack " << track->id << " measurement prediction:\n" << track->state->zp() << "\nTrack covariance prediction:\n" << track->state->Cp()
                                    << "\nObservation " << observation->id << " mean:\n" << observation->z << "\nObservation covariance:\n" << observation->R );
                }

                // Perform gating
                if(!pairing->singular && pairing->d < CHI2INV_99[OBS_DIM]) {
                    // Store in list of compatible pairings
                    trackSpecificPairings.insert( make_pair(track->id, pairing) );
                }
            }
                                                                                }
    }

    ROS_DEBUG("%zu compatible pairings have been found for %zu existing tracks and %zu new observations!", compatiblePairings.size(), tracks.size(), observations.size() );

    //
    // Step 2: go through all tracks, choose and mark nearest neighbour
    //

    foreach(Track::Ptr track, tracks)
    {
        // Store best pairing for this track
        double best_d = numeric_limits<double>::max();
        Pairing::Ptr bestPairing;

        // Iterate over all pairings for this track
        pair<TrackSpecificPairings::iterator, TrackSpecificPairings::iterator> pairingsForThisTrack = trackSpecificPairings.equal_range(track->id);
        for(TrackSpecificPairings::iterator it = pairingsForThisTrack.first; it != pairingsForThisTrack.second; it++) {
            Pairing::Ptr pairing = it->second;

            // Allow that a observation can be matched to several tracks
            // is better than what we have seen so far.
            if(pairing->d < best_d) {
                best_d = pairing->d;
                bestPairing = pairing;
            }
        }

        // See if we found a compatible pairing for this track.
        if(bestPairing) {
            compatiblePairings.push_back(bestPairing);
            markAsMatched(track, bestPairing);
        }
        else if (track->trackStatus == Track::OCCLUDED){
            // Track is occluded
            track->observation.reset();
            track->trackStatus = Track::OCCLUDED;
            track->numberOfConsecutiveOcclusions++;
        }
        else{
            // Track is missed
            track->observation.reset();
            track->trackStatus = Track::MISSED;
            track->numberOfConsecutiveMisses++;
        }
    }

    return compatiblePairings;
}

}

max_stars_repo_name: CodeToPoem/HumanAwareRobotNavigation

max_issues_repo_name: dmr-goncalves/HumanAwareRobotNavigation

max_forks_repo_name: dmr-goncalves/HumanAwareRobotNavigation


text:
// Copyright (C) 2014 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)

// BSD 3-Clause License

// Copyright (c) 2020, Chenyu
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:

// 1. Redistributions of source code must retain the above copyright notice,
// this
//    list of conditions and the following disclaimer.

// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.

// 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "math/sparse_cholesky_llt.h"

#include <cholmod.h>
#include <glog/logging.h>

#include <Eigen/Core>
#include <Eigen/SparseCore>

// UF_long is deprecated but SuiteSparse_long is only available in
// newer versions of SuiteSparse. So for older versions of
// SuiteSparse, we define SuiteSparse_long to be the same as UF_long,
// which is what recent versions of SuiteSparse do anyways.
#ifndef SuiteSparse_long
#define SuiteSparse_long UF_long
#endif

namespace DAGSfM {
namespace {

cholmod_sparse ViewAsCholmod(const Eigen::SparseMatrix<double>& const_mat) {
  Eigen::SparseMatrix<double>& mat =
      const_cast<Eigen::SparseMatrix<double>&>(const_mat);
  cholmod_sparse res;
  res.nzmax = mat.nonZeros();
  res.nrow = mat.rows();
  res.ncol = mat.cols();
  res.p = mat.outerIndexPtr();
  res.i = mat.innerIndexPtr();
  res.x = mat.valuePtr();
  res.sorted = 1;
  if (mat.isCompressed()) {
    res.packed = 1;
  } else {
    res.packed = 0;
    res.nz = mat.innerNonZeroPtr();
  }

  // Set to 0 if the matrix is not symmetric.
  res.stype = 1;
  res.itype = CHOLMOD_INT;
  res.xtype = CHOLMOD_REAL;
  res.dtype = CHOLMOD_DOUBLE;
  return res;
}

cholmod_dense ViewAsCholmod(const Eigen::VectorXd& const_vec) {
  Eigen::VectorXd& vec = const_cast<Eigen::VectorXd&>(const_vec);
  cholmod_dense res;
  res.nrow = vec.rows();
  res.ncol = vec.cols();
  res.nzmax = res.nrow * res.ncol;
  res.d = vec.size();
  res.x = reinterpret_cast<void*>(vec.data());
  res.z = 0;
  res.xtype = CHOLMOD_REAL;
  return res;
}
}  // namespace

// A class for performing the choleksy decomposition of a sparse matrix using
// CHOLMOD from SuiteSparse. This allows us to utilize the supernodal algorithms
// which are not included with Eigen. The interface is meant to mimic the Eigen
// linear solver interface except that it is not templated and requires sparse
// matrices.
SparseCholeskyLLt::SparseCholeskyLLt(const Eigen::SparseMatrix<double>& mat)
    : cholmod_factor_(nullptr),
      is_factorization_ok_(false),
      is_analysis_ok_(false),
      info_(Eigen::Success) {
  cholmod_start(&cc_);
  Compute(mat);
}

SparseCholeskyLLt::SparseCholeskyLLt()
    : cholmod_factor_(nullptr),
      is_factorization_ok_(false),
      is_analysis_ok_(false),
      info_(Eigen::Success) {
  cholmod_start(&cc_);
}

SparseCholeskyLLt::~SparseCholeskyLLt() {
  if (cholmod_factor_ != nullptr) {
    cholmod_free_factor(&cholmod_factor_, &cc_);
  }
  cholmod_finish(&cc_);
}

void SparseCholeskyLLt::AnalyzePattern(const Eigen::SparseMatrix<double>& mat) {
  // Release the current decomposition if there is one.
  if (cholmod_factor_ != nullptr) {
    cholmod_free_factor(&cholmod_factor_, &cc_);
  }

  // Get the cholmod view of the sparse matrix.
  cholmod_sparse A = ViewAsCholmod(mat);

  // Cholmod can try multiple re-ordering strategies to find a fill
  // reducing ordering. Here we just tell it use AMD with automatic
  // matrix dependence choice of supernodal versus simplicial
  // factorization.
  cc_.nmethods = 1;
  cc_.method[0].ordering = CHOLMOD_AMD;
  cc_.supernodal = CHOLMOD_AUTO;

  // Perform symbolic analysis of the matrix.
  cholmod_factor_ = cholmod_analyze(&A, &cc_);
  if (VLOG_IS_ON(2)) {
    cholmod_print_common(const_cast<char*>("Symbolic Analysis"), &cc_);
  }

  if (cc_.status != CHOLMOD_OK) {
    VLOG(2) << "cholmod_analyze failed. error code: %d" << cc_.status;
    info_ = Eigen::NumericalIssue;
    return;
  }

  is_analysis_ok_ = true;
  is_factorization_ok_ = false;
  info_ = Eigen::Success;
}

void SparseCholeskyLLt::Factorize(const Eigen::SparseMatrix<double>& mat) {
  CHECK_NOTNULL(cholmod_factor_);
  CHECK(is_analysis_ok_) << "Cannot call Factorize() because symbolic analysis "
                            "of the matrix (i.e. AnalyzePattern()) failed!";
  cholmod_sparse A = ViewAsCholmod(mat);

  // Save the current print level and silence CHOLMOD, otherwise
  // CHOLMOD is prone to dumping stuff to stderr, which can be
  // distracting when the error (matrix is indefinite) is not a fatal
  // failure.
  const int old_print_level = cc_.print;
  cc_.print = 0;

  cc_.quick_return_if_not_posdef = 1;
  int cholmod_status = cholmod_factorize(&A, cholmod_factor_, &cc_);
  cc_.print = old_print_level;

  // TODO(sameeragarwal): This switch statement is not consistent. It
  // treats all kinds of CHOLMOD failures as warnings. Some of these
  // like out of memory are definitely not warnings. The problem is
  // that the return value Cholesky is two valued, but the state of
  // the linear solver is really three valued. SUCCESS,
  // NON_FATAL_FAILURE (e.g., indefinite matrix) and FATAL_FAILURE
  // (e.g. out of memory).
  switch (cc_.status) {
    case CHOLMOD_NOT_INSTALLED:
      LOG(ERROR) << "CHOLMOD failure: Method not installed.";
      info_ = Eigen::InvalidInput;
      return;
    case CHOLMOD_OUT_OF_MEMORY:
      LOG(ERROR) << "CHOLMOD failure: Out of memory.";
      info_ = Eigen::NumericalIssue;
      return;
    case CHOLMOD_TOO_LARGE:
      LOG(ERROR) << "CHOLMOD failure: Integer overflow occured.";
      info_ = Eigen::NumericalIssue;
      return;
    case CHOLMOD_INVALID:
      LOG(ERROR) << "CHOLMOD failure: Invalid input.";
      info_ = Eigen::InvalidInput;
      return;
    case CHOLMOD_NOT_POSDEF:
      LOG(ERROR) << "CHOLMOD warning: Matrix not positive definite.";
      info_ = Eigen::NumericalIssue;
      return;
    case CHOLMOD_DSMALL:
      LOG(ERROR) << "CHOLMOD warning: D for LDL' or diag(L) or "
                    "LL' has tiny absolute value.";
      info_ = Eigen::NumericalIssue;
      return;
    case CHOLMOD_OK:
      // If everything is done successfully, set the appropriate flags to
      // success and exit.
      if (cholmod_status != 0) {
        info_ = Eigen::Success;
        is_factorization_ok_ = true;
        return;
      }
      LOG(ERROR) << "CHOLMOD failure: cholmod_factorize returned false "
                    "but cholmod_common::status is CHOLMOD_OK.";
      info_ = Eigen::NumericalIssue;
      return;
    default:
      LOG(ERROR) << "Unknown cholmod return code: " << cc_.status;
      info_ = Eigen::InvalidInput;
      return;
  }
}

void SparseCholeskyLLt::Compute(const Eigen::SparseMatrix<double>& mat) {
  AnalyzePattern(mat);
  Factorize(mat);
}

Eigen::ComputationInfo SparseCholeskyLLt::Info() { return info_; }

// Using the cholesky decomposition, solve for x that minimizes
//    lhs * x = rhs
// where lhs is the factorized matrix.
Eigen::VectorXd SparseCholeskyLLt::Solve(const Eigen::VectorXd& rhs) {
  CHECK_NOTNULL(cholmod_factor_);
  CHECK(is_analysis_ok_) << "Cannot call Solve() because symbolic analysis "
                            "of the matrix (i.e. AnalyzePattern()) failed!";
  CHECK(is_factorization_ok_)
      << "Cannot call Solve() because numeric factorization "
         "of the matrix (i.e. Factorize()) failed!";

  Eigen::VectorXd solution;
  if (cc_.status != CHOLMOD_OK) {
    LOG(ERROR) << "cholmod_solve failed. CHOLMOD status is not CHOLMOD_OK";
    return solution;
  }

  // returns a cholmod_dense*
  cholmod_dense b = ViewAsCholmod(rhs);
  cholmod_dense* x = cholmod_solve(CHOLMOD_A, cholmod_factor_, &b, &cc_);
  if (x == nullptr) {
    info_ = Eigen::NumericalIssue;
    return solution;
  }
  solution = Eigen::Map<Eigen::VectorXd>(reinterpret_cast<double*>(x->x),
                                         x->nrow, x->ncol);
  return solution;
}

}  // namespace DAGSfM

max_stars_repo_name: Yzhbuaa/DAGSfM

max_issues_repo_name: Yzhbuaa/DAGSfM

max_forks_repo_name: Yzhbuaa/DAGSfM


text:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <tuple>
#include <stdbool.h>
#include <bitset>
#include <string>
#include <boost/multiprecision/cpp_int.hpp>

namespace mp = boost::multiprecision;
using namespace std;

int main(void) {
    int n;
    cin >> n;

    int i;
    int highest = 0;
    int miss = 0;
    for(i = 0 ; i < n ; ++i) {
        int h;
        cin >> h;
        if (highest <= h) {
            highest = h;
        } else {
            miss++;
        }
    }
    cout << (n - miss) << endl;
    return 0;
}

max_stars_repo_name: kamiyaowl/atcoder

max_issues_repo_name: kamiyaowl/atcoder

max_forks_repo_name: kamiyaowl/atcoder


text:
/*=============================================================================
Copyright 2020 Syed Ali Hasan <alihasan9922@gmail.com>

Distributed under the Boost Software License, Version 1.0. (See accompanying
file License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

#define BOOST_TEST_MODULE horizon_coord_test

#include <iostream>
#include <boost/units/io.hpp>
#include <boost/units/systems/angle/degrees.hpp>
#include <boost/astronomy/coordinate/coord_sys/horizon_coord.hpp>

#include <boost/test/unit_test.hpp>

using namespace boost::units;
using namespace boost::units::si;
using namespace boost::astronomy::coordinate;

namespace bud = boost::units::degree;

BOOST_AUTO_TEST_SUITE(horizon_coord_constructors)

BOOST_AUTO_TEST_CASE(horizon_coord_default_constructor) {
    horizon_coord<
            double,
            quantity<bud::plane_angle>,
            quantity<bud::plane_angle>>
            hc;

    //Check set_altitude_azimuth
    hc.set_altitude_azimuth(45.0 * bud::degrees, 18.0 * bud::degrees);

    //Check values
    BOOST_CHECK_CLOSE(hc.get_altitude().value(), 45.0, 0.001);
    BOOST_CHECK_CLOSE(hc.get_azimuth().value(), 18.0, 0.001);

    //Quantities stored as expected?
    BOOST_TEST((std::is_same<decltype(hc.get_altitude()), quantity<bud::plane_angle>>::value));
    BOOST_TEST((std::is_same<decltype(hc.get_azimuth()), quantity<bud::plane_angle>>::value));
}

BOOST_AUTO_TEST_CASE(horizon_coord_quantities_constructor) {
    //Make Horizon Coordinate Check
    auto hc1 = make_horizon_coord
            (15.0 * bud::degrees, 39.0 * bud::degrees);

    //Check values
    BOOST_CHECK_CLOSE(hc1.get_altitude().value(), 15.0, 0.001);
    BOOST_CHECK_CLOSE(hc1.get_azimuth().value(), 39.0, 0.001);

    //Quantities stored as expected?
    BOOST_TEST((std::is_same<decltype(hc1.get_altitude()), quantity<bud::plane_angle>>::value));
    BOOST_TEST((std::is_same<decltype(hc1.get_azimuth()), quantity<bud::plane_angle>>::value));

    //Horizon Coord constructor
    horizon_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>
            hc2(1.5 * bud::degrees, 9.0 * bud::degrees);

    //Check values
    BOOST_CHECK_CLOSE(hc2.get_altitude().value(), 1.5, 0.001);
    BOOST_CHECK_CLOSE(hc2.get_azimuth().value(), 9.0, 0.001);

    //Quantities stored as expected?
    BOOST_TEST((std::is_same<decltype(hc2.get_altitude()), quantity<bud::plane_angle>>::value));
    BOOST_TEST((std::is_same<decltype(hc2.get_azimuth()), quantity<bud::plane_angle>>::value));
}

BOOST_AUTO_TEST_SUITE_END()


text:
/*
 *  Distributed under the MIT License (See accompanying file /LICENSE )
 */
#include <doctest/doctest.h>  // for ResultBuilder

#include <array>                             // for operator==
#include <boost/multiprecision/cpp_int.hpp>  // for cpp_int
#include <ostream>                           // for operator<<
#include <tuple>                             // for tuple
#include <type_traits>                       // for move

#include "projgeom/ck_plane.hpp"              // for check_sine...
#include "projgeom/common_concepts.h"         // for Value_type
#include "projgeom/euclid_plane.hpp"          // for uc_point, Ar
#include "projgeom/euclid_plane_measure.hpp"  // for quadrance
#include "projgeom/fractions.hpp"             // for operator*
#include "projgeom/pg_common.hpp"             // for sq, cross
#include "projgeom/pg_line.hpp"               // for meet
#include "projgeom/pg_object.hpp"             // for operator*
#include "projgeom/pg_point.hpp"              // for pg_point
#include "projgeom/proj_plane.hpp"            // for coincident
#include "projgeom/proj_plane_measure.hpp"    // for R
// #include <iostream>

using namespace fun;

static const auto Zero = doctest::Approx(0).epsilon(0.01);

/**
 * @brief
 *
 * @param[in] a
 * @return true
 * @return false
 */
template <typename T> inline auto ApproxZero(const T& a) -> bool {
    return a[0] == Zero && a[1] == Zero && a[2] == Zero;
}

/**
 * @brief
 *
 * @tparam T
 * @param[in] triangle
 */
template <Projective_plane_prim2 P> void chk_euclid(const Triple<P>& triangle) {
    auto trilateral = tri_dual(triangle);

    const auto& [a1, a2, a3] = triangle;
    const auto& [l1, l2, l3] = trilateral;

    // using P = decltype(a1);
    using L = decltype(l1);
    using K = Value_type<P>;
    static_assert(Projective_plane_prim2<L>);
    static_assert(ring<K>);

    // auto zero = std::array<K, 3> {0, 0, 0};

    auto [t1, t2, t3] = tri_altitude(triangle);

    auto t4 = harm_conj(t1, t2, t3);
    auto o = orthocenter(triangle);
    auto tau = reflect(l1);
    auto Q = tri_quadrance(triangle);
    auto S = tri_spread(trilateral);

    auto [m12, m23, m13] = tri_midpoint(triangle);

    auto mt1 = a1 * m23;
    auto mt2 = a2 * m13;
    auto mt3 = a3 * m12;

    const auto& [q1, q2, q3] = Q;
    const auto& [s1, s2, s3] = S;

    auto tqf = sq(q1 + q2 + q3) - 2 * (q1 * q1 + q2 * q2 + q3 * q3);
    auto tsf = sq(s1 + s2 + s3) - 2 * (s1 * s1 + s2 * s2 + s3 * s3) - 4 * s1 * s2 * s3;
    auto c3 = sq(q1 + q2 - q3) / (4 * q1 * q2);

    auto a3p = plucker(3, a1, 4, a2);
    auto q1p = quadrance(a2, a3p);
    auto q2p = quadrance(a1, a3p);
    auto q3p = quadrance(a1, a2);
    auto tqf2 = Ar(q1p, q2p, q3p);  // get 0

    if constexpr (Integral<K>) {
        CHECK(!is_parallel(l1, l2));
        CHECK(!is_parallel(l2, l3));
        CHECK(is_perpendicular(t1, l1));
        CHECK(spread(t1, l1) == K(1));
        CHECK(coincident(t1 * t2, t3));
        CHECK(coincident(t1 * t2, t3, t4));
        CHECK(R(t1, t2, t3, t4) == K(-1));
        CHECK(o == t2 * t3);
        CHECK(tau(tau(a1)) == a1);
        CHECK(spread(l1, l1) == K(0));
        CHECK(quadrance(a1, a1) == K(0));
        CHECK(check_sine_law(Q, S));
        CHECK(check_sine_law(S, Q));
        CHECK(coincident(mt1 * mt2, mt3));
        // CHECK(cross_s(l1, l2) == c3);
        CHECK((c3 + s3) == K(1));
        CHECK(tqf == Ar(q1, q2, q3));
        CHECK(tsf == K(0));
        CHECK(tqf2 == K(0));
        // auto o2 = orthocenter(
        //               std::tuple {std::move(o), std::move(a2),
        //               std::move(a3)});
        // CHECK(a1 == o2);
    } else {
        CHECK(cross2(l1, l2) != Zero);
        CHECK(cross2(l2, l3) != Zero);
        CHECK(dot1(t1, l1) == Zero);
        CHECK(spread(t1, l1) - 1 == Zero);
        CHECK(t1.dot(t2 * t3) == Zero);
        CHECK(R(t1, t2, t3, t4) + 1 == Zero);
        CHECK(ApproxZero(cross(meet(t2, t3), o)));
        CHECK(ApproxZero(cross(tau(tau(a1)), a1)));
        CHECK(mt1.dot(mt2 * mt3) == Zero);
        CHECK(spread(l1, l1) == Zero);
        CHECK(quadrance(a1, a1) == Zero);
        CHECK(angle(l1, l1) == Zero);
        CHECK(distance(a1, a1) == Zero);
        // CHECK(cross_s(l1, l2) == doctest::Approx(c3).epsilon(0.01));
        CHECK((c3 + s3) - 1 == Zero);
        CHECK(tqf - Ar(q1, q2, q3) == Zero);
        CHECK(tsf == Zero);
        CHECK(tqf2 == Zero);
        // CHECK(ApproxEqual(a1, orthocenter(std::tuple{std::move(o), // not
        // quite accurate
        //                     std::move(a2), std::move(a3)})));
    }
}

template <typename T> void chk_cyclic(const T& quadangle) {
    auto& [u1, u2, u3, u4] = quadangle;

    auto q12 = quadrance(u1, u2);
    auto q23 = quadrance(u2, u3);
    auto q34 = quadrance(u3, u4);
    auto q14 = quadrance(u1, u4);
    auto q24 = quadrance(u2, u4);
    auto q13 = quadrance(u1, u3);

    using P = decltype(u1);
    using K = Value_type<P>;

    if constexpr (Integral<K>) {
        auto okay = Ptolemy(std::tuple{std::move(q12), std::move(q23), std::move(q34),
                                       std::move(q14), std::move(q24), std::move(q13)});
        CHECK(okay);
    } else {
        auto t = Ar(q12 * q34, q23 * q14, q13 * q24);
        CHECK(t == Zero);
    }
}

TEST_CASE("Euclid plane (cpp_int)") {
    using boost::multiprecision::cpp_int;

    auto a1 = pg_point<cpp_int>{1, 3, 1};
    auto a2 = pg_point<cpp_int>{4, 2, 1};
    auto a3 = pg_point<cpp_int>{4, -3, 1};

    auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};
    chk_euclid(triangle);
}

TEST_CASE("Euclid plane (floating point)") {
    auto a1 = pg_point{1., 3., 1.};
    auto a2 = pg_point{4., 2., 1.};
    auto a3 = pg_point{4., -3., 1.};

    auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};
    chk_euclid(triangle);
}

TEST_CASE("Euclid Cyclic Points (cpp_int)") {
    using boost::multiprecision::cpp_int;
    using P = pg_point<cpp_int>;

    auto u1 = uc_point<P>(1, 0);
    auto u2 = uc_point<P>(3, 4);
    auto u3 = uc_point<P>(-1, 2);
    auto u4 = uc_point<P>(0, 1);

    auto quadangle = std::tuple{std::move(u1), std::move(u2), std::move(u3), std::move(u4)};
    chk_cyclic(quadangle);
}

TEST_CASE("Euclid Cyclic Points (double)") {
    using P = pg_point<double>;

    auto u1 = uc_point<P>(1, 0);
    auto u2 = uc_point<P>(3, 4);
    auto u3 = uc_point<P>(-1, 2);
    auto u4 = uc_point<P>(0, 1);

    auto quadangle = std::tuple{std::move(u1), std::move(u2), std::move(u3), std::move(u4)};
    chk_cyclic(quadangle);
}


text: #include <boost/icl/type_traits/size_type_of.hpp>


text:
#include <cassert>
#include <iostream>
#include <boost/timer.hpp>

template <typename T>
class vector
{
    void check_size(int that_size) const { assert(my_size == that_size); }
    void check_index(int i) const { assert(i >= 0 && i < my_size); }
  public:
    explicit vector(int size)
      : my_size(size), data( new T[my_size] )
    {}

    vector()
      : my_size(0), data(0)
    {}

    vector( const vector& that )
      : my_size(that.my_size), data( new T[my_size] )
    {
	for (int i= 0; i < my_size; ++i)
	    data[i]= that.data[i];
    }

    ~vector() { if (data) delete [] data ; }

    vector& operator=( const vector& that )
    {
	check_size(that.my_size);
	for (int i= 0; i < my_size; ++i)
	    data[i]= that.data[i];
    }

    int size() const { return my_size ; }

    const T& operator[]( int i ) const
    {
	check_index(i);
	return data[i];
    }

    T& operator[]( int i )
    {
	check_index(i);
	return data[i] ;
    }

  private:
    int   my_size ;
    T*    data ;
};

template <typename T>
std::ostream& operator<<(std::ostream& os, const vector<T>& v)
{
  os << '[';
  for (int i= 0; i < v.size(); ++i) os << v[i] << ',';
  os << ']';
  return os ;
}

template <unsigned Offset, unsigned Max>
struct my_axpy_ftor
{
    template <typename U, typename V, typename W>
    void operator()(U& u, const V& v, const W& w, unsigned i)
    {
	u[i+Offset]= 3.0f * v[i+Offset] + w[i+Offset];
	my_axpy_ftor<Offset+1, Max>()(u, v, w, i);
    }
};

template <unsigned Max>
struct my_axpy_ftor<Max, Max>
{
    template <typename U, typename V, typename W>
    void operator()(U& u, const V& v, const W& w, unsigned i) {}
};

template <unsigned BSize, typename U, typename V, typename W>
void my_axpy(U& u, const V& v, const W& w)
{
    assert(u.size() == v.size() && v.size() == w.size());
    unsigned s= u.size(), sb= s / BSize * BSize;

    for (unsigned i= 0; i < sb; i+= BSize)
	my_axpy_ftor<0, BSize>()(u, v, w, i);

    for (unsigned i= sb; i < s; i++)
	u[i]= 3.0f * v[i] + w[i];
}

int main(int argc, char** argv)
{
    /* const */ unsigned s= 1000;
    // if (argc > 1) s= atoi(argv[1]);
    vector<float> u(s), v(s), w(s);

    for (unsigned i= 0; i < s; i++) {
	v[i]= float(i);
	w[i]= float(2*i + 15);
    }

    for (unsigned j= 0; j < 3; j++)
	for (unsigned i= 0; i < s; i++)
	    u[i]= 3.0f * v[i] + w[i];

    const unsigned rep= 2000000; // 1000000;

    boost::timer native;
    // asm ( "# start here native" );
    for (unsigned j= 0; j < rep; j++)
	for (unsigned i= 0; i < s; i++)
	    u[i]= 3.0f * v[i] + w[i];
    // asm ( "# end here native" );
    std::cout << "Compute time native loop is " << 1000000.0 * native.elapsed() / double(rep) << " mmicros.\n";
    std::cout << "u[0] is " << u[0] << '\n';

    boost::timer unrolled;
    // asm ( "# start here unrolled" );
    for (unsigned j= 0; j < rep; j++) {
	unsigned sb= s / 4 * 4;
	for (unsigned i= 0; i < sb; i+= 4) {
	    u[i]=   3.0f * v[i]   + w[i];
	    u[i+1]= 3.0f * v[i+1] + w[i+1];
	    u[i+2]= 3.0f * v[i+2] + w[i+2];
	    u[i+3]= 3.0f * v[i+3] + w[i+3];
	}
	for (unsigned i= sb; i < s; i++)
	    u[i]= 3.0f * v[i] + w[i];
    }
    // asm ( "# end here unrolled" );
    std::cout << "Compute time unrolled loop is " << 1000000.0 * unrolled.elapsed() / double(rep) << " mmicros.\n";
    std::cout << "u[0] is " << u[0] << '\n';

    boost::timer unrolled2;
    for (unsigned j= 0; j < rep; j++)
	my_axpy<2>(u, v, w);
    std::cout << "Compute time unrolled<2> loop is " << 1000000.0 * unrolled2.elapsed() / double(rep) << " mmicros.\n";
    std::cout << "u[0] is " << u[0] << '\n';

    boost::timer unrolled4;
    for (unsigned j= 0; j < rep; j++)
	my_axpy<4>(u, v, w);
    std::cout << "Compute time unrolled<4> loop is " << 1000000.0 * unrolled4.elapsed() / double(rep) << " mmicros.\n";
    std::cout << "u[0] is " << u[0] << '\n';

    boost::timer unrolled6;
    for (unsigned j= 0; j < rep; j++)
	my_axpy<6>(u, v, w);
    std::cout << "Compute time unrolled<6> loop is " << 1000000.0 * unrolled6.elapsed() / double(rep) << " mmicros.\n";
    std::cout << "u[0] is " << u[0] << '\n';

    boost::timer unrolled8;
    for (unsigned j= 0; j < rep; j++)
	my_axpy<8>(u, v, w);
    std::cout << "Compute time unrolled<8> loop is " << 1000000.0 * unrolled8.elapsed() / double(rep) << " mmicros.\n";
    std::cout << "u[0] is " << u[0] << '\n';

    return 0;
}

max_stars_repo_name: tzaffi/cpp

max_issues_repo_name: tzaffi/cpp

max_forks_repo_name: tzaffi/cpp


text:
#include "ParseDotGraph.hpp"

#include <boost/fusion/tuple.hpp>
#include <boost/spirit/home/support/iterators/istream_iterator.hpp>
#include <boost/spirit/home/x3.hpp>

#include <iterator>

namespace dot {

namespace x3 = boost::spirit::x3;
namespace fusion = boost::fusion;

using x3::alnum;
using x3::alpha;
using x3::char_;
using x3::lexeme;
using x3::lit;
using x3::rule;

const auto quoted_string = lexeme['"' >> +(char_ - '"') >> '"'];
const auto word_string = alpha >> *(alnum | char_("_"));
const auto id = (word_string | quoted_string);

const rule<class edge, fusion::tuple<std::string, std::string>> edge_stmt =
    "edge";
const auto edge_stmt_def = id >> lit("->") >> id;

const auto attr_list = lit("[") >> id >> lit("=") >> id >> lit("]");
const auto node_stmt = id >> attr_list;

const auto graph_header = lit("digraph") >> id;

BOOST_SPIRIT_DEFINE(edge_stmt); // NOLINT

template <typename Iterator>
auto parse(Iterator first, Iterator last, const OnEdgeFunction &onEdge)
    -> bool {
  const auto on_edge = [&](auto &ctx) {
    const auto &attribute = x3::_attr(ctx);
    const auto &srcId = fusion::get<0>(attribute);
    const auto &destId = fusion::get<1>(attribute);
    onEdge(srcId, destId);
  };

  const auto graph =
      graph_header >> lit("{") >> *(node_stmt | edge_stmt[on_edge]) >> lit("}");
  bool r = x3::phrase_parse(first, last, graph, x3::ascii::space);

  if (first != last) {
    return false;
  }
  return r;
}
} // namespace dot

void parseDotGraph(std::istream &in, const OnEdgeFunction &onEdge) {
  in.unsetf(std::ios::skipws);
  if (!dot::parse(boost::spirit::istream_iterator{in},
                  boost::spirit::istream_iterator{}, onEdge)) {
    throw std::runtime_error("parse error");
  }
}

max_stars_repo_name: oesse/find-critical-path

max_issues_repo_name: oesse/find-critical-path

max_forks_repo_name: oesse/find-critical-path


text:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>

#include <boost/shared_ptr.hpp>

#include <iostream>
#include <pcl/point_representation.h>

PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>);

#include "make_opaque_vectors.hpp" // must be first for PYBIND11_MAKE_OPAQUE to work
#include "eigen_bind.hpp"
#include "generated_modules/__main_loader.hpp"
#include "point_cloud_buffers.hpp"
#include "point_cloud_from_array.hpp"
#include "vector_classes.hpp"
#include "point_types.hpp"

namespace py = pybind11;
using namespace pybind11::literals;

using namespace pcl;

template <typename T>
void definePointCloudBuffers(py::object &m, const char *suffix)
{
    using PointCloud = pcl::PointCloud<T>;
    using Type = py::class_<PointCloud, boost::shared_ptr<PointCloud>>;
    auto pc = static_cast<Type>(m.attr(suffix));
    pc.def(py::init([](py::array_t<float> &points) { return fromArray<T>(points); }), "array"_a);
    pc.def_static("from_array", &fromArray<T>, "array"_a);
    defineBuffers<T>(pc);
}

template <typename T>
void definePointCloudBuffersRGB(py::object &m, const char *suffix)
{
    using PointCloud = pcl::PointCloud<T>;
    using Type = py::class_<PointCloud, boost::shared_ptr<PointCloud>>;
    auto pc = static_cast<Type>(m.attr(suffix));
    pc.def(py::init([](py::array_t<float> &points, py::array_t<uint8_t> &rgb) { return fromArrayRGB<T>(points, rgb); }), "array"_a, "rgb"_a);
    pc.def_static("from_array", &fromArrayRGB<T>, "array"_a, "rgb"_a);
    defineBuffers<T>(pc);
}

PYBIND11_MODULE(pcl, m)
{
    m.doc() = "PCL python bindings";

    definePointTypes(m);

    py::module m_vector = m.def_submodule("vectors", "Submodule for vectors");
    defineEigenClasses(m_vector);
    defineVectorClasses(m_vector);

    defineClasses(m);

    py::object pc = m.attr("PointCloud");
    definePointCloudBuffers<PointXYZ>(pc, "PointXYZ");
    definePointCloudBuffers<PointXYZI>(pc, "PointXYZI");
    definePointCloudBuffers<PointXYZL>(pc, "PointXYZL");
    definePointCloudBuffers<Label>(pc, "Label");
    definePointCloudBuffersRGB<PointXYZRGBA>(pc, "PointXYZRGBA");
    definePointCloudBuffersRGB<PointXYZRGB>(pc, "PointXYZRGB");
    definePointCloudBuffersRGB<PointXYZRGBL>(pc, "PointXYZRGBL");
    definePointCloudBuffers<PointXYZHSV>(pc, "PointXYZHSV");
    definePointCloudBuffers<PointXY>(pc, "PointXY");
    definePointCloudBuffers<InterestPoint>(pc, "InterestPoint");
    definePointCloudBuffers<Axis>(pc, "Axis");
    definePointCloudBuffers<Normal>(pc, "Normal");
    definePointCloudBuffers<PointNormal>(pc, "PointNormal");
    definePointCloudBuffersRGB<PointXYZRGBNormal>(pc, "PointXYZRGBNormal");
    definePointCloudBuffers<PointXYZINormal>(pc, "PointXYZINormal");
    definePointCloudBuffers<PointXYZLNormal>(pc, "PointXYZLNormal");
    definePointCloudBuffers<PointWithRange>(pc, "PointWithRange");
    definePointCloudBuffers<PointWithViewpoint>(pc, "PointWithViewpoint");
    definePointCloudBuffers<MomentInvariants>(pc, "MomentInvariants");
    definePointCloudBuffers<PrincipalRadiiRSD>(pc, "PrincipalRadiiRSD");
    definePointCloudBuffers<PrincipalRadiiRSD>(pc, "PrincipalRadiiRSD");
    definePointCloudBuffers<Boundary>(pc, "Boundary");
    definePointCloudBuffers<PrincipalCurvatures>(pc, "PrincipalCurvatures");
    definePointCloudBuffers<PFHSignature125>(pc, "PFHSignature125");
    definePointCloudBuffers<PFHRGBSignature250>(pc, "PFHRGBSignature250");
    definePointCloudBuffers<PPFSignature>(pc, "PPFSignature");
    definePointCloudBuffers<CPPFSignature>(pc, "CPPFSignature");
    definePointCloudBuffers<PPFRGBSignature>(pc, "PPFRGBSignature");
    definePointCloudBuffers<NormalBasedSignature12>(pc, "NormalBasedSignature12");
    definePointCloudBuffers<FPFHSignature33>(pc, "FPFHSignature33");
    definePointCloudBuffers<VFHSignature308>(pc, "VFHSignature308");
    definePointCloudBuffers<GASDSignature512>(pc, "GASDSignature512");
    definePointCloudBuffers<GASDSignature984>(pc, "GASDSignature984");
    definePointCloudBuffers<GASDSignature7992>(pc, "GASDSignature7992");
    definePointCloudBuffers<GRSDSignature21>(pc, "GRSDSignature21");
    definePointCloudBuffers<ESFSignature640>(pc, "ESFSignature640");
    definePointCloudBuffers<BRISKSignature512>(pc, "BRISKSignature512");
    definePointCloudBuffers<Narf36>(pc, "Narf36");
    definePointCloudBuffers<IntensityGradient>(pc, "IntensityGradient");
    definePointCloudBuffers<PointWithScale>(pc, "PointWithScale");
    definePointCloudBuffersRGB<PointSurfel>(pc, "PointSurfel");
    definePointCloudBuffers<ShapeContext1980>(pc, "ShapeContext1980");
    definePointCloudBuffers<UniqueShapeContext1960>(pc, "UniqueShapeContext1960");
    definePointCloudBuffers<SHOT352>(pc, "SHOT352");
    definePointCloudBuffers<SHOT1344>(pc, "SHOT1344");
    definePointCloudBuffers<PointUV>(pc, "PointUV");
    definePointCloudBuffers<ReferenceFrame>(pc, "ReferenceFrame");
    definePointCloudBuffers<PointDEM>(pc, "PointDEM");
}

max_stars_repo_name: sweptlaser/pclpy

max_issues_repo_name: sweptlaser/pclpy

max_forks_repo_name: sweptlaser/pclpy