text:
/**
 * BCL to FASTQ file converter
 * Copyright (c) 2007-2017 Illumina, Inc.
 *
 * This software is covered by the accompanying EULA
 * and certain third party copyright/licenses, and any user of this
 * source file is bound by the terms therein.
 *
 * \file XmlParser.cpp
 *
 * \brief Basic XML parser.
 *
 * \author Roman Petrovski
 * \author Marek Balint
 */

#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

#include <boost/filesystem/fstream.hpp>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include "io/Xml.hh"
#include "common/Exceptions.hh"

#include "common/Logger.hh"

namespace bcl2fastq {
namespace io {

using namespace boost::property_tree;
static const std::string indexed("<indexed>");

/**
 * @brief Rearranges property tree according to a few basic schema customization rules.
 *
 * The original property tree would produce an xml
 * where each Read, Lane and Tile element has a number of child elements named after
 * the number of the read, lane of tile respectively. For example:
 *
 *  Tree:
 *  Summary.Read.1.Lane.4.Tile.5.value.Yield = 123
 *                                    .YieldQ30 = 12
 *                            .6.value.Yield = 123
 *                                    .YieldQ30 = 12
 *
 *  Xml:
 *  <Summary>
 *    <Read>
 *      <1>
 *        <Lane>
 *          <4>
 *            <Tile>
 *              <5>
 *              ...
 * This is inconvenient and against the rest of the iSAAC metadata xml schemas.
 * Before the tree is written out into the xml, all index nodes are collapsed into
 * xml attribute nodes so that the resulting xml looks like:
 *
 *  Tree:
 *  Summary.<indexed>Read.<number>1.<indexed>Lane.<number>4.<indexed>Tile.<number>5.value.Yield = 123
 *                                                                                .YieldQ30 = 12
 *                                                                      .<number>6.value.Yield = 123
 *                                                                                .YieldQ30 = 12
 *
 *  Xml:
 *  <Summary>
 *    <Read index="1">
 *      <Lane number="4">
 *        <Tile number="5">
 *          <Yield>123</Yield>
 *          <YieldQ30>12</YieldQ30>
 *        </Tile>
 *        <Tile number="6">
 *          <Yield>123</Yield>
 *          <YieldQ30>12</YieldQ30>
 *          ...
 */
void unindex(const ptree::value_type &nameElementKv, ptree &resultTree)
{
    if (indexed == nameElementKv.first.substr(0, indexed.length()))
    {
        BOOST_FOREACH(const ptree::value_type &indexElementKv, nameElementKv.second)
        {
            BOOST_ASSERT('<' == indexElementKv.first[0]);
            size_t attrNameEndPos = indexElementKv.first.find('>', 1);
            BOOST_ASSERT(std::string::npos != attrNameEndPos);
            ptree &insertedChildTree = resultTree.add_child(nameElementKv.first.substr(indexed.length()), ptree());

            std::for_each(indexElementKv.second.begin(), indexElementKv.second.end(),
                          boost::bind(unindex, _1, boost::ref(insertedChildTree)));

            if (insertedChildTree.empty())
            {
                // if child has no child elements, use its value as content
                insertedChildTree.put_value(indexElementKv.second.get_value<std::string>());
            }

            insertedChildTree.add("<xmlattr>." + indexElementKv.first.substr(1, attrNameEndPos -1),
                                  indexElementKv.first.substr(attrNameEndPos+1));
        }
    }
    else
    {
        ptree &insertedChildTree = resultTree.add_child(nameElementKv.first, ptree());
        std::for_each(nameElementKv.second.begin(), nameElementKv.second.end(),
                      boost::bind(unindex, _1, boost::ref(insertedChildTree)));
        if (insertedChildTree.empty())
        {
            //unindexing did not find any indexed nodes. just add it as is
            insertedChildTree.put_value(nameElementKv.second.get_value<std::string>());
        }
        else
        {
            //unindexing inserted the modified tree.
        }
    }
}

bool longestPathFirst(const std::string &left, const std::string &right)
{
    return std::count(left.begin(), left.end(), '.') > std::count(right.begin(), right.end(), '.');
}

void index(std::vector<std::string > indexNodes, ptree &tree)
{
    // indexing of longer paths should happen first for the shorter paths to stay valid until they get indexed
    std::sort(indexNodes.begin(), indexNodes.end(), longestPathFirst);

    BOOST_FOREACH(const std::string &idxAttrPath, indexNodes)
    {
        size_t attrNameDotPos(idxAttrPath.rfind('.'));
        BOOST_ASSERT(std::string::npos != attrNameDotPos && "Could not parse index attribute name");
        const std::string indexedNodeKey(idxAttrPath.substr(0, attrNameDotPos));
        const std::string indexAttributeName(idxAttrPath.substr(attrNameDotPos+1));

        size_t indexedNodeNameDotPos(indexedNodeKey.rfind('.'));
        BOOST_ASSERT(std::string::npos != indexedNodeNameDotPos && "Could not parse indexed node name");
        const std::string indexedNodeParentKey(indexedNodeKey.substr(0, indexedNodeNameDotPos));
        const std::string indexedNodeName(indexedNodeKey.substr(indexedNodeNameDotPos+1));

        ptree &indexedNodeParent(tree.get_child(indexedNodeParentKey));
        BOOST_FOREACH(ptree::value_type &potentiallyIndexedNode, indexedNodeParent)
        {
            if (indexedNodeName == potentiallyIndexedNode.first)
            {
                std::string indexedNodeKey("<indexed>" + indexedNodeName + ".<" + indexAttributeName + ">"
                                           + potentiallyIndexedNode.second.get<std::string>("<xmlattr>." + indexAttributeName));
                BOOST_ASSERT(potentiallyIndexedNode.second.get_child("<xmlattr>").erase(indexAttributeName));
                indexedNodeParent.add_child(indexedNodeKey, potentiallyIndexedNode.second);
            }
        }
        indexedNodeParent.erase(indexedNodeName);
    }
}

std::ostream &serializeAsXml(std::ostream &os, const boost::property_tree::ptree &tree)
{
    boost::property_tree::ptree treeWithIndexAttributes;
    if (!tree.empty())
    {
        unindex(*tree.begin(), treeWithIndexAttributes);
#ifndef WIN32
        boost::property_tree::write_xml(os, treeWithIndexAttributes, boost::property_tree::xml_writer_make_settings(' ', 2));
#else
        boost::property_tree::write_xml(os, treeWithIndexAttributes, boost::property_tree::xml_writer_make_settings<std::string>(' ', 2));
#endif
    }
    else
    {
#ifndef WIN32
        boost::property_tree::write_xml(os, tree, boost::property_tree::xml_writer_make_settings(' ', 2));
#else
        boost::property_tree::write_xml(os, tree, boost::property_tree::xml_writer_make_settings<std::string>(' ', 2));
#endif
    }
    return os;
}

std::istream &parseAsXml(std::istream &is, boost::property_tree::ptree &tree)
{
    boost::property_tree::read_xml<boost::property_tree::ptree>(is, tree);
    return is;
}

boost::property_tree::ptree parseXmlFile(const boost::filesystem::path& xmlFile)
{
    boost::filesystem::ifstream xmlStream(xmlFile);
    xmlStream.unsetf(std::ios::skipws);
    int errnum = errno;
    if (!xmlStream)
    {
        BOOST_THROW_EXCEPTION(common::IoError(errnum, (boost::format("Unable to open '%s' file for reading") % xmlFile.string()).str()));
    }

    typedef std::vector<char> XmlBuffer;
    XmlBuffer xmlBuffer;
    errnum = 0;
    std::copy(
        std::istream_iterator<XmlBuffer::value_type>(xmlStream),
        std::istream_iterator<XmlBuffer::value_type>(),
        std::back_inserter(xmlBuffer)
    );

    return parseXmlData(xmlBuffer.begin(), xmlBuffer.end());
}

} // namespace io
} // namespace bcl2fastq


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

namespace TStoreTests
{
    using namespace std;
    using namespace Common;
    using namespace ktl;
    using namespace Data::Utilities;

    class ReadOnlySortedListTest
    {
    public:
        Common::CommonConfig config; // load the config object as its needed for the tracing to work

        ReadOnlySortedListTest()
        {
            NTSTATUS status;
            status = KtlSystem::Initialize(FALSE, &ktlSystem_);
            CODING_ERROR_ASSERT(NT_SUCCESS(status));
            ktlSystem_->SetStrictAllocationChecks(TRUE);
        }

        ~ReadOnlySortedListTest()
        {
            ktlSystem_->Shutdown();
        }

        KAllocator& GetAllocator()
        {
            return ktlSystem_->NonPagedAllocator();
        }

        void ValidateEnumerator(IEnumerator<KeyValuePair<int, int>> & enumerator)
        {
            bool hasItem = enumerator.MoveNext();
            if (!hasItem)
            {
                return;
            }
            int previous = enumerator.Current().Key;
            while (enumerator.MoveNext())
            {
                int current = enumerator.Current().Key;
                CODING_ERROR_ASSERT(previous <= current);
                previous = current;
            }
        }

        void ValidateEnumerator(IEnumerator<int> & enumerator)
        {
            bool hasItem = enumerator.MoveNext();
            if (!hasItem)
            {
                return;
            }
            int previous = enumerator.Current();
            while (enumerator.MoveNext())
            {
                int current = enumerator.Current();
                CODING_ERROR_ASSERT(previous <= current);
                previous = current;
            }
        }

    private:
        KtlSystem* ktlSystem_;

#pragma region test functions
    public:
        ktl::Awaitable<void> CreateEmpty_ShouldSucceed_Test()
        {
            ConcurrentDictionary<int, int>::SPtr dictionarySPtr = nullptr;
            ConcurrentDictionary<int, int>::Create(GetAllocator(), dictionarySPtr);

            IntComparer::SPtr intComparerSPtr;
            auto status = IntComparer::Create(GetAllocator(), intComparerSPtr);
            Diagnostics::Validate(status);
            IComparer<int>::SPtr comparerSPtr = intComparerSPtr.DownCast<IComparer<int>>();

            ReadOnlySortedList<int, int>::SPtr listSPtr = nullptr;
            status = ReadOnlySortedList<int, int>::Create(*dictionarySPtr, *comparerSPtr, true, false, GetAllocator(), listSPtr);
            Diagnostics::Validate(status);

            ASSERT_IFNOT(listSPtr->Count == 0, "Expected count to be 0");

            auto enumerator = listSPtr->GetEnumerator();
            CODING_ERROR_ASSERT(enumerator->MoveNext() == false);
            co_return;
        }

        ktl::Awaitable<void> Enumerate_AddInReverseOrder_ShouldBeSorted_Test()
        {
            ConcurrentDictionary<int, int>::SPtr dictionarySPtr = nullptr;
            ConcurrentDictionary<int, int>::Create(GetAllocator(), dictionarySPtr);

            ULONG32 numItems = 6;
            for (int i = numItems; i > 0; i--)
            {
                dictionarySPtr->Add(i, i);
            }

            IntComparer::SPtr intComparerSPtr;
            auto status = IntComparer::Create(GetAllocator(), intComparerSPtr);
            Diagnostics::Validate(status);
            IComparer<int>::SPtr comparerSPtr = intComparerSPtr.DownCast<IComparer<int>>();

            ReadOnlySortedList<int, int>::SPtr listSPtr = nullptr;
            status = ReadOnlySortedList<int, int>::Create(*dictionarySPtr, *comparerSPtr, true, false, GetAllocator(), listSPtr);
            Diagnostics::Validate(status);

            ASSERT_IFNOT(listSPtr->Count == numItems, "Expected count to be {0}, got {1}", numItems, listSPtr->Count);

            auto enumerator = listSPtr->GetEnumerator();
            ValidateEnumerator(*enumerator);
            co_return;
        }

        ktl::Awaitable<void> EnumerateKeys_AddInReverseOrder_ShouldBeSorted_Test()
        {
            ConcurrentDictionary<int, int>::SPtr dictionarySPtr = nullptr;
            ConcurrentDictionary<int, int>::Create(GetAllocator(), dictionarySPtr);

            ULONG32 numItems = 6;
            for (int i = numItems; i > 0; i--)
            {
                dictionarySPtr->Add(i, i);
            }

            IntComparer::SPtr intComparerSPtr;
            auto status = IntComparer::Create(GetAllocator(), intComparerSPtr);
            Diagnostics::Validate(status);
            IComparer<int>::SPtr comparerSPtr = intComparerSPtr.DownCast<IComparer<int>>();

            ReadOnlySortedList<int, int>::SPtr listSPtr = nullptr;
            status = ReadOnlySortedList<int, int>::Create(*dictionarySPtr, *comparerSPtr, true, false, GetAllocator(), listSPtr);
            Diagnostics::Validate(status);

            ASSERT_IFNOT(listSPtr->Count == numItems, "Expected count to be {0}, got {1}", numItems, listSPtr->Count);

            auto enumerator = listSPtr->GetKeys();
            ValidateEnumerator(*enumerator);
            co_return;
        }

        ktl::Awaitable<void> EnumerateKeys_SortedInput_ShouldBeSorted_Test()
        {
            ConcurrentDictionary<int, int>::SPtr dictionarySPtr = nullptr;
            ConcurrentDictionary<int, int>::Create(GetAllocator(), dictionarySPtr);

            ULONG32 numItems = 6;
            for (ULONG32 i = 0; i < numItems; i++)
            {
                dictionarySPtr->Add(i, i);
            }

            IntComparer::SPtr intComparerSPtr;
            auto status = IntComparer::Create(GetAllocator(), intComparerSPtr);
            Diagnostics::Validate(status);
            IComparer<int>::SPtr comparerSPtr = intComparerSPtr.DownCast<IComparer<int>>();

            ReadOnlySortedList<int, int>::SPtr listSPtr = nullptr;
            status = ReadOnlySortedList<int, int>::Create(*dictionarySPtr, *comparerSPtr, true, true, GetAllocator(), listSPtr);
            Diagnostics::Validate(status);

            ASSERT_IFNOT(listSPtr->Count == numItems, "Expected count to be {0}, got {1}", numItems, listSPtr->Count);

            auto enumerator = listSPtr->GetKeys();
            ValidateEnumerator(*enumerator);
            co_return;
        }

        ktl::Awaitable<void> EnumerateKeys_MoveTo_ShouldBeSorted_Test()
        {
            ConcurrentDictionary<int, int>::SPtr dictionarySPtr = nullptr;
            ConcurrentDictionary<int, int>::Create(GetAllocator(), dictionarySPtr);

            for (int i = 2; i <= 18; i += 2)
            {
                dictionarySPtr->Add(i, i);
            }

            IntComparer::SPtr intComparerSPtr;
            auto status = IntComparer::Create(GetAllocator(), intComparerSPtr);
            Diagnostics::Validate(status);
            IComparer<int>::SPtr comparerSPtr = intComparerSPtr.DownCast<IComparer<int>>();

            ReadOnlySortedList<int, int>::SPtr listSPtr = nullptr;
            status = ReadOnlySortedList<int, int>::Create(*dictionarySPtr, *comparerSPtr, true, false, GetAllocator(), listSPtr);
            Diagnostics::Validate(status);

            for (int startKey = 1; startKey <= 19; startKey++)
            {
                auto enumerator = listSPtr->GetKeys();
                bool moved = enumerator->MoveTo(startKey);

                int firstKey = (startKey % 2 == 0) ? startKey : startKey + 1;

                if (firstKey > 18)
                {
                    CODING_ERROR_ASSERT(moved == false);
                    bool hasNext = enumerator->MoveNext();
                    CODING_ERROR_ASSERT(hasNext == false);
                    continue;
                }

                CODING_ERROR_ASSERT(moved);

                for (int key = firstKey; key <= 18; key += 2)
                {
                    bool hasNext = enumerator->MoveNext();

                    CODING_ERROR_ASSERT(hasNext);

                    int item = enumerator->Current();
                    CODING_ERROR_ASSERT(item == key);
                }

                bool hasNext = enumerator->MoveNext();
                CODING_ERROR_ASSERT(hasNext == false);
            }
            co_return;
        }

        ktl::Awaitable<void> ContainsKeys_AddInReverseOrder_ShouldSucceed_Test()
        {
            ConcurrentDictionary<int, int>::SPtr dictionarySPtr = nullptr;
            ConcurrentDictionary<int, int>::Create(GetAllocator(), dictionarySPtr);

            int numItems = 6;
            for (int i = numItems; i > 0; i--)
            {
                dictionarySPtr->Add(i, i);
            }

            IntComparer::SPtr intComparerSPtr;
            auto status = IntComparer::Create(GetAllocator(), intComparerSPtr);
            Diagnostics::Validate(status);
            IComparer<int>::SPtr comparerSPtr = intComparerSPtr.DownCast<IComparer<int>>();

            ReadOnlySortedList<int, int>::SPtr listSPtr = nullptr;
            status = ReadOnlySortedList<int, int>::Create(*dictionarySPtr, *comparerSPtr, true, false, GetAllocator(), listSPtr);
            Diagnostics::Validate(status);

            CODING_ERROR_ASSERT(listSPtr->ContainsKey(0) == false);
            for (int i = 1; i <= numItems; i++)
            {
                CODING_ERROR_ASSERT(listSPtr->ContainsKey(i) == true);
            }
            CODING_ERROR_ASSERT(listSPtr->ContainsKey(numItems+1) == false);
            co_return;
        }

        ktl::Awaitable<void> TryGetValue_AddInReverseOrder_ShouldSucceed_Test()
        {
            ConcurrentDictionary<int, int>::SPtr dictionarySPtr = nullptr;
            ConcurrentDictionary<int, int>::Create(GetAllocator(), dictionarySPtr);

            int numItems = 6;
            for (int i = numItems; i > 0; i--)
            {
                dictionarySPtr->Add(i, i);
            }

            IntComparer::SPtr intComparerSPtr;
            auto status = IntComparer::Create(GetAllocator(), intComparerSPtr);
            Diagnostics::Validate(status);
            IComparer<int>::SPtr comparerSPtr = intComparerSPtr.DownCast<IComparer<int>>();

            ReadOnlySortedList<int, int>::SPtr listSPtr = nullptr;
            status = ReadOnlySortedList<int, int>::Create(*dictionarySPtr, *comparerSPtr, true, false, GetAllocator(), listSPtr);
            Diagnostics::Validate(status);

            int result;

            CODING_ERROR_ASSERT(listSPtr->TryGetValue(0, result) == false);
            for (int i = 1; i <= numItems; i++)
            {
                CODING_ERROR_ASSERT(listSPtr->TryGetValue(i, result) == true);
                CODING_ERROR_ASSERT(result == i);
            }
            CODING_ERROR_ASSERT(listSPtr->TryGetValue(numItems+1, result) == false);
            co_return;
        }
    #pragma endregion
    };

    BOOST_FIXTURE_TEST_SUITE(ReadOnlySortedListTestSuite, ReadOnlySortedListTest)

    BOOST_AUTO_TEST_CASE(CreateEmpty_ShouldSucceed)
    {
        SyncAwait(CreateEmpty_ShouldSucceed_Test());
    }

    BOOST_AUTO_TEST_CASE(Enumerate_AddInReverseOrder_ShouldBeSorted)
    {
        SyncAwait(Enumerate_AddInReverseOrder_ShouldBeSorted_Test());
    }

    BOOST_AUTO_TEST_CASE(EnumerateKeys_AddInReverseOrder_ShouldBeSorted)
    {
        SyncAwait(EnumerateKeys_AddInReverseOrder_ShouldBeSorted_Test());
    }

    BOOST_AUTO_TEST_CASE(EnumerateKeys_SortedInput_ShouldBeSorted)
    {
        SyncAwait(EnumerateKeys_SortedInput_ShouldBeSorted_Test());
    }

    BOOST_AUTO_TEST_CASE(EnumerateKeys_MoveTo_ShouldBeSorted)
    {
        SyncAwait(EnumerateKeys_MoveTo_ShouldBeSorted_Test());
    }

    BOOST_AUTO_TEST_CASE(ContainsKeys_AddInReverseOrder_ShouldSucceed)
    {
        SyncAwait(ContainsKeys_AddInReverseOrder_ShouldSucceed_Test());
    }

    BOOST_AUTO_TEST_CASE(TryGetValue_AddInReverseOrder_ShouldSucceed)
    {
        SyncAwait(TryGetValue_AddInReverseOrder_ShouldSucceed_Test());
    }

    BOOST_AUTO_TEST_SUITE_END()
}

ext: cpp


text:
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the
 * License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

/*! \file udm_event_sig.hpp
 \brief
 \author  Tien-Thinh NGUYEN (EURECOM)
 \company
 \date 2022
 \email: contact@openairinterface.org
 */

#ifndef FILE_UDM_EVENT_SIG_HPP_SEEN
#define FILE_UDM_EVENT_SIG_HPP_SEEN

#include <boost/signals2.hpp>
#include <string>

namespace bs2 = boost::signals2;

namespace oai::udm::app {

// Signal for Loss of Connectivity
// SUPI, Connectivity status, HTTP version
typedef bs2::signal_type<
    void(std::string, uint8_t, uint8_t),
    bs2::keywords::mutex_type<bs2::dummy_mutex>>::type
    loss_of_connectivity_sig_t;

// Signal for UE Reachability for Data
// SUPI, Reachability status, HTTP version
typedef bs2::signal_type<
    void(std::string, uint8_t, uint8_t),
    bs2::keywords::mutex_type<bs2::dummy_mutex>>::type
    ue_reachability_for_data_sig_t;

// UE_REACHABILITY_FOR_SMS
// LOCATION_REPORTING
// CHANGE_OF_SUPI_PEI_ASSOCIATION
// ROAMING_STATUS
// COMMUNICATION_FAILURE
// AVAILABILITY_AFTER_DNN_FAILURE
// CN_TYPE_CHANGE

}  // namespace oai::udm::app
#endif

ext: hpp


text:
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

#include "std_msgs/String.h"
#include <sstream>
#include <termios.h>

#include <ros/ros.h>

#include <sensor_msgs/Joy.h>

#include "rosserial_server/serial_session.h"

using namespace ros;

int getch()
{
	static struct termios oldt, newt;
	tcgetattr( STDIN_FILENO, &oldt);           // save old settings
	newt = oldt;
	newt.c_lflag &= ~(ICANON);                 // disable buffering
	tcsetattr( STDIN_FILENO, TCSANOW, &newt);  // apply new settings

	int c = getchar();  // read character (non-blocking)

	tcsetattr( STDIN_FILENO, TCSANOW, &oldt);  // restore old settings
	return c;
}

int main(int argc, char* argv[])
{
	ros::init(argc, argv, "rosserial_server_serial_node");
	std::string port;
	ros::param::param<std::string>("~port", port, "/dev/ttyACM1");
	int baud;
	ros::param::param<int>("~baud", baud, 57600);

	boost::asio::io_service io_service;
	new rosserial_server::SerialSession(io_service, port, baud);
	boost::thread(boost::bind(&boost::asio::io_service::run, &io_service));

	NodeHandle n;
	Publisher chatter_pub = n.advertise<std_msgs::String>("Direction", 1000);

	Rate loop_rate(10);

	int count = 0;
	while (ros::ok())
	{

		// %Tag(FILL_MESSAGE)%
		std_msgs::String msg;

		std::stringstream ss,ss1;
		//ss << "hello world " << count;

		char c = getch();   // call your non-blocking input function
		ss << "keyboard command is " << c << "\n";
		ss1 << c << "";

		msg.data = ss1.str();
		// %EndTag(FILL_MESSAGE)%

		// %Tag(ROSCONSOLE)%
		//ROS_INFO("%s", msg.data.c_str());
		// %EndTag(ROSCONSOLE)%

		/**
		 * The publish() function is how you send messages. The parameter
		 * is the message object. The type of this object must agree with the type
		 * given as a template parameter to the advertise<>() call, as was done
		 * in the constructor above.
		 */
		// %Tag(PUBLISH)%
		chatter_pub.publish(msg);
		// %EndTag(PUBLISH)%

		// %Tag(SPINONCE)%
		spinOnce();
		// %EndTag(SPINONCE)%

		chatter_pub.publish(msg);
		spinOnce();

		// %Tag(RATE_SLEEP)%
		//loop_rate.sleep();
		// %EndTag(RATE_SLEEP)%
		++count;
	}

	return 0;
}
// %EndTag(FULLTEXT)%

max_stars_repo_name: khairulislam/phys

max_issues_repo_name: khairulislam/phys

max_forks_repo_name: khairulislam/phys


text:
// Copyright 2019 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

#ifndef METALL_UTILITY_DETAIL_NAMED_PROXY_HPP
#define METALL_UTILITY_DETAIL_NAMED_PROXY_HPP

#include <boost/interprocess/detail/named_proxy.hpp>

/// \namespace metall::mtlldetail
/// \brief Namespace for implementation details
namespace metall::mtlldetail {

/// \brief Proxy class that implements named allocation syntax.
/// \tparam segment_manager segment manager to construct the object
/// \tparam T type of object to build
/// \tparam is_iterator passing parameters are normal object or iterators?
template <typename segment_manager, typename T, bool is_iterator>
using named_proxy = boost::interprocess::ipcdetail::named_proxy<segment_manager, T, is_iterator>;

} // namespace metall::mtlldetail

#endif //METALL_UTILITY_DETAIL_NAMED_PROXY_HPP

max_stars_repo_name: dice-group/metall

max_issues_repo_name: dice-group/metall

max_forks_repo_name: dice-group/metall


text: #include <boost/hana/fwd/string.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// \file
/// Tests for the SURGSIM_LOG_*() macros and the related classes.

#include <gtest/gtest.h>
#include "SurgSim/Framework/Log.h"

#include <boost/filesystem.hpp>

#include <fstream>
#include <string>
#include <iomanip>

using SurgSim::Framework::Logger;
using SurgSim::Framework::FileOutput;

::testing::AssertionResult isContained(const std::string& expected, const std::string& argument)
{
	if (std::string::npos != argument.find(expected))
	{
		return ::testing::AssertionSuccess();
	}
	else
	{
		return ::testing::AssertionFailure() << expected << " not contained in " << argument;
	}
}

class MockOutput : public SurgSim::Framework::LogOutput
{
public:
	MockOutput()
	{
	}

	~MockOutput()
	{
	}

	bool writeMessage(const std::string& message)
	{
		logMessage = message;
		return true;
	}
	void reset()
	{
		logMessage = "";
	}

	std::string logMessage;
};

TEST(LoggerTest, MessageTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);

	logger->writeMessage("TestMessage");
	EXPECT_EQ("TestMessage", output->logMessage);
}

TEST(LoggerTest, LogMacroTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_WARNING);

	output->reset();
	SURGSIM_LOG(logger, CRITICAL) << "Test Text";
	EXPECT_TRUE(isContained("Test Text",output->logMessage));

	output->reset();
	SURGSIM_LOG(logger, DEBUG) << "Missing Text";
	EXPECT_EQ("", output->logMessage);

	output->reset();
	SURGSIM_LOG(logger, WARNING) << "Exactly At Threshold";
	EXPECT_TRUE(isContained("Exactly At Threshold", output->logMessage));
}

TEST(LoggerTest, SharedPtrTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_WARNING);

	output->reset();
	SURGSIM_LOG(logger, CRITICAL) << "Test Text";
	EXPECT_TRUE(isContained("Test Text", output->logMessage));

	output->reset();
	SURGSIM_LOG(logger, DEBUG) << "Missing Text";
	EXPECT_EQ("", output->logMessage);

	output->reset();
	SURGSIM_LOG(logger, WARNING) << "Exactly At Threshold";
	EXPECT_TRUE(isContained("Exactly At Threshold", output->logMessage));
}

TEST(LoggerTest, LevelSpecificMacroTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();

	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_WARNING);

	output->reset();
	SURGSIM_LOG_CRITICAL(logger) << "Test Text";
	EXPECT_TRUE(isContained("Test Text", output->logMessage));

	output->reset();
	SURGSIM_LOG_DEBUG(logger) << "Missing Text";
	EXPECT_EQ("", output->logMessage);

	output->reset();
	SURGSIM_LOG_WARNING(logger) << "Exactly At Threshold";
	EXPECT_TRUE(isContained("Exactly At Threshold", output->logMessage));
}

TEST(LoggerTest, IfMacroTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_WARNING);

	output->reset();
	SURGSIM_LOG_IF(true, logger, CRITICAL) << "Test Text";
	EXPECT_TRUE(isContained("Test Text", output->logMessage));
	output->reset();
	SURGSIM_LOG_IF(false, logger, CRITICAL) << "Test Text";
	EXPECT_EQ("", output->logMessage);

	output->reset();
	SURGSIM_LOG_IF(true, logger, DEBUG) << "Missing Text";
	EXPECT_EQ("", output->logMessage);
	output->reset();
	SURGSIM_LOG_IF(false, logger, DEBUG) << "Missing Text";
	EXPECT_EQ("", output->logMessage);

	output->reset();
	SURGSIM_LOG_IF(true, logger, WARNING) << "Exactly At Threshold";
	EXPECT_TRUE(isContained("Exactly At Threshold", output->logMessage));
	output->reset();
	SURGSIM_LOG_IF(false, logger, WARNING) << "Exactly At Threshold";
	EXPECT_EQ("", output->logMessage);
}

TEST(LoggerTest, OnceMacroTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_WARNING);

	for (int i = 0;  i < 3; ++i)
	{
		output->reset();
		SURGSIM_LOG_ONCE(logger, CRITICAL) << "Test Text";
		if (i == 0)
		{
			EXPECT_TRUE(isContained("Test Text", output->logMessage));
		}
		else
		{
			EXPECT_EQ("", output->logMessage);
		}

		output->reset();
		SURGSIM_LOG_ONCE(logger, DEBUG) << "Missing Text";
		EXPECT_EQ("", output->logMessage);

		output->reset();
		SURGSIM_LOG_ONCE(logger, CRITICAL) << "More Text";
		if (i == 0)
		{
			EXPECT_TRUE(isContained("More Text", output->logMessage));
		}
		else
		{
			EXPECT_EQ("", output->logMessage);
		}
	}
}

TEST(LoggerTest, OnceIfMacroTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_WARNING);

	for (int i = 0;  i < 3; ++i)
	{
		output->reset();
		SURGSIM_LOG_ONCE_IF(i >= 0, logger, CRITICAL) << "Test Text";
		if (i == 0)
		{
			EXPECT_TRUE(isContained("Test Text", output->logMessage));
		}
		else
		{
			EXPECT_EQ("", output->logMessage);
		}

		output->reset();
		SURGSIM_LOG_ONCE_IF(i >= 1, logger, DEBUG) << "Missing Text";
		EXPECT_EQ("", output->logMessage);

		output->reset();
		SURGSIM_LOG_ONCE_IF(i >= 2, logger, CRITICAL) << "More Text";
		if (i == 2)
		{
			EXPECT_TRUE(isContained("More Text", output->logMessage));
		}
		else
		{
			EXPECT_EQ("", output->logMessage);
		}
	}
}

TEST(LoggerTest, EndOfLineTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_WARNING);

	output->reset();
	SURGSIM_LOG_CRITICAL(logger) << "foo" << std::endl << "bar";
	EXPECT_TRUE(isContained("foo\nbar", output->logMessage));
}

TEST(LoggerTest, LogLevelTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output = std::make_shared<MockOutput>();
	logger->setOutput(output);
	logger->setThreshold(SurgSim::Framework::LOG_LEVEL_DEBUG);

	output->reset();
	SURGSIM_LOG_DEBUG(logger) << "a message";
	EXPECT_TRUE(isContained("DEBUG", output->logMessage));

	output->reset();
	SURGSIM_LOG_INFO(logger) << "a message";
	EXPECT_TRUE(isContained("INFO", output->logMessage));

	output->reset();
	SURGSIM_LOG_WARNING(logger) << "a message";
	EXPECT_TRUE(isContained("WARNING", output->logMessage));

	output->reset();
	SURGSIM_LOG_SEVERE(logger) << "a message";
	EXPECT_TRUE(isContained("SEVERE", output->logMessage));

	output->reset();
	SURGSIM_LOG_CRITICAL(logger) << "a message";
	EXPECT_TRUE(isContained("CRITICAL", output->logMessage));
}

TEST(LoggerTest, ManipulatorTest)
{
	auto logger = Logger::getLogger("TestLogger");
	auto output	= std::make_shared<MockOutput>();
	logger->setOutput(output);

	output->reset();
	SURGSIM_LOG_WARNING(logger) << "aAa" << std::endl << "bBb";
	EXPECT_TRUE(isContained("aAa\nbBb", output->logMessage) || isContained("aAa\r\n\bBb", output->logMessage)) <<
		"message: '" << output->logMessage << "'";

	output->reset();
	SURGSIM_LOG_WARNING(logger) << "[" << std::hex << std::setw(5) << std::setfill('0') << 0x1234 << "]";
	EXPECT_TRUE(isContained("[01234]", output->logMessage)) <<
		"message: '" << output->logMessage << "'";

	output->reset();
	// The next message should not show any evidence of previous manipulators.
	SURGSIM_LOG_WARNING(logger) << "[" << 987 << "]";
	EXPECT_TRUE(isContained("[987]", output->logMessage)) <<
		"message: '" << output->logMessage << "'";
}

class FileOutputTest : public ::testing::Test
{
public:
	void SetUp()
	{
		output = std::make_shared<FileOutput>("test.log");
	}

	void TearDown()
	{
		output = nullptr;
		boost::filesystem::remove("test.log");
	}

	static std::shared_ptr<FileOutput> output;
};

std::shared_ptr<FileOutput> FileOutputTest::output;

TEST_F(FileOutputTest, BasicTest)
{
	EXPECT_TRUE(boost::filesystem::exists("test.log"));
}

TEST_F(FileOutputTest, CreationFailure)
{
	ASSERT_ANY_THROW(FileOutput("asdfasdf/test.log"));
}

TEST_F(FileOutputTest, Write)
{
	output->writeMessage("TestMessage");
	output = nullptr;

	std::ifstream stream("test.log");
	EXPECT_FALSE(stream.fail());

	std::string message;
	stream >> message;

	EXPECT_EQ("TestMessage",message);
}

max_stars_repo_name: dbungert/opensurgsim

max_issues_repo_name: dbungert/opensurgsim

max_forks_repo_name: dbungert/opensurgsim


text:
/******************************************************************************\
* LuaWrappers.hpp                                                              *
* Making C++ stuff accessible from Lua.                                        *
*                                                                              *
*                                                                              *
* Copyright (C) 2005-2011 by Leandro Motta Barros.                             *
*                                                                              *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to     *
* deal in the Software without restriction, including without limitation the   *
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or  *
* sell copies of the Software, and to permit persons to whom the Software is   *
* furnished to do so, subject to the following conditions:                     *
*                                                                              *
* The above copyright notice and this permission notice shall be included in   *
* all copies or substantial portions of the Software.                          *
*                                                                              *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,     *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER       *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS *
* IN THE SOFTWARE.                                                             *
\******************************************************************************/

#ifndef _DILUCULUM_LUA_WRAPPERS_HPP_
#define _DILUCULUM_LUA_WRAPPERS_HPP_

#include <algorithm>
#include <string>
#include <boost/bind.hpp>
#include <Diluculum/CppObject.hpp>
#include <Diluculum/LuaExceptions.hpp>
#include <Diluculum/LuaState.hpp>
#include <Diluculum/LuaUtils.hpp>

namespace Diluculum
{
   namespace Impl
   {
      /** Calls \c lua_error() with a proper error message. The error message is
       *  composed of things that may help to find out what's the error, like
       *  the function name.
       *  @param ls The <tt>lua_State*</tt> on which the function will operate.
       *  @param what A message to be included in the error message created by
       *         this function.
       *  @note This is not intended to be called by Diluculum users.
       */
      void ReportErrorFromCFunction (lua_State* ls, const::std::string& what);

      /** Helper class, used by the \c DILUCULUM_CLASS_METHOD() macro, as a
       *  means register a method in the table that represents a class being
       *  exported to Lua. Everything is done in the constructor. This is just
       *  a way to get some code executed in a macro call that happens at the
       *  global scope, outside of a function definition.
       */
      class ClassTableFiller
      {
         public:
            /** Adds the function \c func to the table \c classTable, with a key
             *  \c name.
             *  @param classTable The table representing the class being
             *         exported to Lua.
             *  @param name The name by which the method will be known in the
             *         Lua side.
             *  @param func The C function wrapping the method.
             */
            ClassTableFiller (Diluculum::LuaValueMap& classTable,
                              const std::string& name,
                              lua_CFunction func)
            {
               classTable[name] = func;
            }
      };
   }
}

/** Returns the name of the wrapper function that is created by
 *  \c DILUCULUM_WRAP_FUNCTION() for a given function name.
 *  @param FUNC The function whose wrapper name is desired.
 */
#define DILUCULUM_WRAPPER_FUNCTION(FUNC)        \
   Diluculum__ ## FUNC ## __Wrapper_Function

/** Creates a \c lua_CFunction that wraps a function with the signature like the
 *  following one:
 *
<tt>Diluculum::LuaValueList Func (const Diluculum::LuaValueList& params)</tt>
 *
Notice that, thanks to the use of <tt>Diluculum::LuaValueList</tt>s, the
 *  wrapped function can effectively take and return an arbitrary number of
 *  values.
 *  @note The name of the created wrapper function is a decorated version of the
 *        \c FUNC parameter. The decoration scheme can be quite complicated and
 *        is subject to change in future releases of Diluculum, so don't try to
 *        use it directly. Use the \c DILUCULUM_WRAPPER_FUNCTION() macro to
 *        obtain it instead.
 *  @note The proper way to report errors from the function being wrapped is by
 *        <tt>throw</tt>ing a \c Diluculum::LuaError. The created wrapper
 *        function will handle these exceptions and "translate" them to a call
 *        to \c lua_error().
 *  @see DILUCULUM_WRAPPER_FUNCTION() To find out the name of the created
 *       wrapper function.
 *  @param FUNC The function to be wrapped.
 */
#define DILUCULUM_WRAP_FUNCTION(FUNC)                                         \
int DILUCULUM_WRAPPER_FUNCTION(FUNC) (lua_State* ls)                          \
{                                                                             \
   using std::for_each;                                                       \
   using boost::bind;                                                         \
   using Diluculum::PushLuaValue;                                             \
   using Diluculum::Impl::ReportErrorFromCFunction;                           \
                                                                              \
   try                                                                        \
   {                                                                          \
      /* Read parameters and empty the stack */                               \
      const int numParams = lua_gettop (ls);                                  \
      Diluculum::LuaValueList params;                                         \
      for (int i = 1; i <= numParams; ++i)                                    \
         params.push_back (Diluculum::ToLuaValue (ls, i));                    \
      lua_pop (ls, numParams);                                                \
                                                                              \
      /* Call the wrapped function */                                         \
      Diluculum::LuaValueList ret = FUNC (params);                            \
                                                                              \
      /* Push the return values and return */                                 \
      for_each (ret.begin(), ret.end(), bind (PushLuaValue, ls, _1));         \
                                                                              \
      return ret.size();                                                      \
   }                                                                          \
   catch (Diluculum::LuaError& e)                                             \
   {                                                                          \
      ReportErrorFromCFunction (ls, e.what());                                \
      return 0;                                                               \
   }                                                                          \
   catch(...)                                                                 \
   {                                                                          \
      ReportErrorFromCFunction (ls, "Unknown exception caught by wrapper.");  \
      return 0;                                                               \
   }                                                                          \
}

/** Returns the name of the table that represent the class \c CLASS.
 *  @note This is used internally. Users can ignore this macro.
 */
#define DILUCULUM_CLASS_TABLE(CLASS) \
Diluculum__Class_Table__ ## CLASS

/** Starts a block of class wrapping macro calls. This must be followed by calls
 *  to \c DILUCULUM_CLASS_METHOD() for each method to be exported to Lua and a
 *  final call to \c DILUCULUM_END_CLASS().
 *  @param CLASS The class being exported.
 */
#define DILUCULUM_BEGIN_CLASS(CLASS)                                          \
namespace                                                                     \
{                                                                             \
   /* the table representing the class */                                     \
   Diluculum::LuaValueMap DILUCULUM_CLASS_TABLE(CLASS);                       \
}                                                                             \
                                                                              \
/* The Constructor */                                                         \
int Diluculum__ ## CLASS ## __Constructor_Wrapper_Function (lua_State* ls)    \
{                                                                             \
   using Diluculum::PushLuaValue;                                             \
   using Diluculum::Impl::CppObject;                                          \
   using Diluculum::Impl::ReportErrorFromCFunction;                           \
                                                                              \
   try                                                                        \
   {                                                                          \
      /* Read parameters and empty the stack */                               \
      const int numParams = lua_gettop (ls);                                  \
      Diluculum::LuaValueList params;                                         \
      for (int i = 1; i <= numParams; ++i)                                    \
         params.push_back (Diluculum::ToLuaValue (ls, i));                    \
      lua_pop (ls, numParams);                                                \
                                                                              \
      /* Construct the object, wrap it in a userdata, and return */           \
      void* ud = lua_newuserdata (ls, sizeof(CppObject));                     \
      CppObject* cppObj = reinterpret_cast<CppObject*>(ud);                   \
      cppObj->ptr = new CLASS (params);                                       \
      cppObj->deleteMe = true;                                                \
                                                                              \
      lua_getglobal (ls, "__Diluculum__Class_Metatables");                    \
      lua_getfield (ls, -1, #CLASS);                                          \
      lua_setmetatable (ls, -3);                                              \
      lua_pop (ls, 1); /* pop the table of metatables */                      \
                                                                              \
      return 1;                                                               \
   }                                                                          \
   catch (Diluculum::LuaError& e)                                             \
   {                                                                          \
      ReportErrorFromCFunction (ls, e.what());                                \
      return 0;                                                               \
   }                                                                          \
   catch(...)                                                                 \
   {                                                                          \
      ReportErrorFromCFunction (ls, "Unknown exception caught by wrapper.");  \
      return 0;                                                               \
   }                                                                          \
}                                                                             \
                                                                              \
/* Destructor */                                                              \
int Diluculum__ ## CLASS ## __Destructor_Wrapper_Function (lua_State* ls)     \
{                                                                             \
   using Diluculum::Impl::CppObject;                                          \
                                                                              \
   CppObject* cppObj =                                                        \
      reinterpret_cast<CppObject*>(lua_touserdata (ls, -1));                  \
                                                                              \
   if (cppObj->deleteMe)                                                      \
   {                                                                          \
      cppObj->deleteMe = false; /* don't delete again when gc'ed! */          \
      CLASS* pObj = reinterpret_cast<CLASS*>(cppObj->ptr);                    \
      delete pObj;                                                            \
   }                                                                          \
                                                                              \
   return 0;                                                                  \
}

/** Returns the name of the function used to wrap a method \c METHOD of the
 *  class \c CLASS.
 *  @note This is used internally. Users can ignore this macro.
 */
#define DILUCULUM_METHOD_WRAPPER(CLASS, METHOD)                      \
   Diluculum__ ## CLASS ## __ ## METHOD ## __Method_Wrapper_Function

/** Exports a given class' method. This macro must be called between calls to
 *  \c DILUCULUM_BEGIN_CLASS() and \c DILUCULUM_END_CLASS().
 *  @param CLASS The class whose method is being exported.
 *  @param METHOD The method being exported.
 */
#define DILUCULUM_CLASS_METHOD(CLASS, METHOD)                                 \
int DILUCULUM_METHOD_WRAPPER(CLASS, METHOD) (lua_State* ls)                   \
{                                                                             \
   using std::for_each;                                                       \
   using boost::bind;                                                         \
   using Diluculum::PushLuaValue;                                             \
   using Diluculum::Impl::CppObject;                                          \
   using Diluculum::Impl::ReportErrorFromCFunction;                           \
                                                                              \
   try                                                                        \
   {                                                                          \
      /* Read parameters and empty the stack */                               \
      const int numParams = lua_gettop (ls);                                  \
      Diluculum::LuaValue ud = Diluculum::ToLuaValue (ls, 1);                 \
      Diluculum::LuaValueList params;                                         \
      for (int i = 2; i <= numParams; ++i)                                    \
         params.push_back (Diluculum::ToLuaValue (ls, i));                    \
      lua_pop (ls, numParams);                                                \
                                                                              \
      /* Get the object pointer and call the method */                        \
      CppObject* cppObj =                                                     \
         reinterpret_cast<CppObject*>(ud.asUserData().getData());             \
      CLASS* pObj = reinterpret_cast<CLASS*>(cppObj->ptr);                    \
                                                                              \
      Diluculum::LuaValueList ret = pObj->METHOD (params);                    \
                                                                              \
      /* Push the return values and return */                                 \
      for_each (ret.begin(), ret.end(), bind (PushLuaValue, ls, _1));         \
                                                                              \
      return static_cast<int>( ret.size() );                                                      \
   }                                                                          \
   catch (Diluculum::LuaError& e)                                             \
   {                                                                          \
      ReportErrorFromCFunction (ls, e.what());                                \
      return 0;                                                               \
   }                                                                          \
   catch(...)                                                                 \
   {                                                                          \
      ReportErrorFromCFunction (ls, "Unknown exception caught by wrapper.");  \
      return 0;                                                               \
   }                                                                          \
}                                                                             \
                                                                              \
namespace                                                                     \
{                                                                             \
   Diluculum::Impl::ClassTableFiller                                          \
      Diluculum__ ## CLASS ## _ ## METHOD ## __ ## Filler(                    \
         DILUCULUM_CLASS_TABLE(CLASS),                                        \
         #METHOD,                                                             \
         DILUCULUM_METHOD_WRAPPER(CLASS, METHOD));                            \
}

/** Ends a block of class wrapping macro calls (which was opened by a call to
 *  \c DILUCULUM_BEGIN_CLASS()).
 *  @param CLASS The class being exported.
 */
#define DILUCULUM_END_CLASS(CLASS)                                            \
                                                                              \
/* The function used to register the class in a 'LuaState' */                 \
void Diluculum_Register_Class__ ## CLASS (Diluculum::LuaVariable className)   \
{                                                                             \
   Diluculum::LuaState ls (className.getState());                             \
                                                                              \
   if (ls["__Diluculum__Class_Metatables"].value().type() == LUA_TNIL)        \
     ls["__Diluculum__Class_Metatables"] = Diluculum::EmptyLuaValueMap;       \
                                                                              \
   static bool isInited = false;                                              \
   if (!isInited)                                                             \
   {                                                                          \
      isInited = true;                                                        \
                                                                              \
      DILUCULUM_CLASS_TABLE(CLASS)["classname"] = #CLASS;                     \
                                                                              \
      DILUCULUM_CLASS_TABLE(CLASS)["new"] =                                   \
         Diluculum__ ## CLASS ## __Constructor_Wrapper_Function;              \
                                                                              \
      DILUCULUM_CLASS_TABLE(CLASS)["delete"] =                                \
         Diluculum__ ## CLASS ## __Destructor_Wrapper_Function;               \
                                                                              \
      DILUCULUM_CLASS_TABLE(CLASS)["__gc"] =                                  \
         Diluculum__ ## CLASS ## __Destructor_Wrapper_Function;               \
                                                                              \
      DILUCULUM_CLASS_TABLE(CLASS)["__index"] = DILUCULUM_CLASS_TABLE(CLASS); \
   }                                                                          \
                                                                              \
   className = DILUCULUM_CLASS_TABLE(CLASS);                                  \
                                                                              \
   ls["__Diluculum__Class_Metatables"][#CLASS] =                              \
      DILUCULUM_CLASS_TABLE(CLASS);                                           \
} /* end of Diluculum_Register_Class__CLASS */

/** Registers a class in a given \c Diluculum::LuaState. The class must have
 *  been previously exported by calls to \c DILUCULUM_BEGIN_CLASS(),
 *  \c DILUCULUM_END_CLASS() and probably \c DILUCULUM_CLASS_METHOD().
 *  @param LUA_VARIABLE The \c Diluculum::LuaVariable that will store the class
 *         after this call.
 *  @param CLASS The class being registered.
 */
#define DILUCULUM_REGISTER_CLASS(LUA_VARIABLE, CLASS)  \
   Diluculum_Register_Class__ ## CLASS (LUA_VARIABLE);

/** Registers an object instantiated in C++ into a Lua state. This way, this
 *  object's methods can be called from Lua. The registered C++ object will
 *  \e not be destroyed when the corresponding Lua object is garbage-collected.
 *  Destroying it is responsibility of the programmer on the C++ side.
 *  @param LUA_VARIABLE The \c Diluculum::LuaVariable where the object will be
 *         stored. Notice that a \c Diluculum::LuaVariable contains a reference
 *         to a <tt>lua_State*</tt>, so the Lua state in which the object will
 *         be stored is passed here, too, albeit indirectly.
 *  @param CLASS The class of the object being registered. This class must have
 *         been previously registered in the target Lua state with a call to the
 *         \c DILUCULUM_REGISTER_CLASS() macro.
 *  @param OBJECT The object to be registered to the Lua state.
 */
#define DILUCULUM_REGISTER_OBJECT(LUA_VARIABLE, CLASS, OBJECT)                \
{                                                                             \
   /* leave the table where 'OBJECT' is to be stored at the stack top */      \
   LUA_VARIABLE.pushLastTable();                                              \
                                                                              \
   /* push the field where the object will be stored */                       \
   Diluculum::PushLuaValue (LUA_VARIABLE.getState(),                          \
                            LUA_VARIABLE.getKeys().back());                   \
                                                                              \
   /* create the userdata, set its metatable */                               \
   void* ud = lua_newuserdata (LUA_VARIABLE.getState(),                       \
                               sizeof(Diluculum::Impl::CppObject));           \
                                                                              \
   Diluculum::Impl::CppObject* cppObj =                                       \
      reinterpret_cast<Diluculum::Impl::CppObject*>(ud);                      \
                                                                              \
   cppObj->ptr = &OBJECT;                                                     \
   cppObj->deleteMe = false;                                                  \
                                                                              \
   lua_getglobal (LUA_VARIABLE.getState(), "__Diluculum__Class_Metatables");  \
   lua_getfield (LUA_VARIABLE.getState(), -1, #CLASS);                        \
   lua_setmetatable (LUA_VARIABLE.getState(), -3);                            \
                                                                              \
   lua_pop (LUA_VARIABLE.getState(), 1); /* pop the table of metatables */    \
                                                                              \
   /* store the userdata */                                                   \
   lua_settable (LUA_VARIABLE.getState(), -3);                                \
}

/** Starts a block declaring a dynamically loadable module, that is, a module
 *  that is expected to be compiled as a shared library. The block must be
 *  closed by a call to \c DILUCULUM_END_MODULE() and contain some calls to
 *  macros like \c DILUCULUM_MODULE_ADD_CLASS() and
 *  \c DILUCULUM_MODULE_ADD_FUNCTION() in its body.
 *
For those who know the way things happen in Lua, this block will provide
 *  a \c luaopen_MyModule() function, which initializes the module when loaded.
 *  @param MODNAME The module name. This is how the module will be called in
 *         Lua. Also, the dynamic library to which the model will be compiled
 *         should be named like this (plus an extension like <tt>.so</tt> or
 *         <tt>.dll</tt>). Well, actually the rules for naming the module file
 *         are more complex than this. Check the
 *         Lua manual for the dirty
 *         details.
 */
#define DILUCULUM_BEGIN_MODULE(MODNAME)                  \
extern "C" int luaopen_ ## MODNAME (lua_State *luaState) \
{                                                        \
   using Diluculum::LuaState;                            \
   using Diluculum::LuaVariable;                         \
   using Diluculum::EmptyLuaValueMap;                    \
   LuaState ls (luaState);                               \
                                                         \
   ls[#MODNAME] = EmptyLuaValueMap;                      \
   LuaVariable theModule = ls[#MODNAME];

/** Adds a class to the module. Must be called between calls to
 *  \c DILUCULUM_BEGIN_MODULE() and \c DILUCULUM_END_MODULE().
 *  @param CLASS The name of the class being added, as it is known in the
 *         C++ side.
 *  @param LUACLASS The name by which the class will be known in the Lua side.
 */
#define DILUCULUM_MODULE_ADD_CLASS(CLASS, LUACLASS)      \
   DILUCULUM_REGISTER_CLASS(theModule[LUACLASS], CLASS);

/** Adds a function to the module. Must be called between calls to
 *  \c DILUCULUM_BEGIN_MODULE() and \c DILUCULUM_END_MODULE().
 *  @param CFUNC The name of the function being added, as it is known in the
 *         C++ side.
 *  @param LUAFUNC The name by which the function will be known in the Lua side.
 */
#define DILUCULUM_MODULE_ADD_FUNCTION(CFUNC, LUAFUNC) \
   theModule[LUAFUNC] = CFUNC;

/** Closes a block (started by \c DILUCULUM_BEGIN_MODULE()) that defines a
 *  dynamically loadable Lua module.
 *  @bug In principle, this function should return one parameter: the table
 *       containing the module (this is more or less a convention). The current
 *       implementation not only ignores the convention: it also seems to return
 *       something invalid (function looks to be returning 1 without anything on
 *       the stack).
 */
#define DILUCULUM_END_MODULE() \
   return 1;                   \
}

#endif // _DILUCULUM_LUA_WRAPPERS_HPP_

max_stars_repo_name: TankOs/flexworld-diluculum

max_issues_repo_name: TankOs/flexworld-diluculum

max_forks_repo_name: TankOs/flexworld-diluculum


text:
#ifndef GUNERO_MERKLE_TREE_GADGET_H_
#define GUNERO_MERKLE_TREE_GADGET_H_

#include <deque>
#include <boost/optional.hpp>
#include <boost/static_assert.hpp>
#include <libff/common/utils.hpp>
#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>
#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>
#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>
#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>
#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>
#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>
#include <libff/algebra/fields/field_utils.hpp>
#include <libff/algebra/scalar_multiplication/multiexp.hpp>
#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>
#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>
#include <libff/algebra/curves/edwards/edwards_pp.hpp>
#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>
#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>
#include <libff/common/utils.hpp>

#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>
#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>

#include "uint256.h"
#include "serialize.h"
#include "gunero_merkle_tree.hpp"

using namespace libsnark;

namespace gunero {

template<typename FieldT, typename HashT, size_t tree_depth>
class gunero_merkle_tree_gadget : gadget<FieldT> {
private:
    pb_variable_array<FieldT> positions;
    std::shared_ptr<gunero_merkle_authentication_path_variable<FieldT, HashT>> authvars;
    std::shared_ptr<gunero_merkle_tree_check_read_gadget<FieldT, HashT>> auth;

public:
    gunero_merkle_tree_gadget(
        protoboard<FieldT>& pb,
        digest_variable<FieldT>& leaf,
        digest_variable<FieldT>& root,
        const pb_variable<FieldT>& enforce,
        const std::string &annotation_prefix
    ) : gadget<FieldT>(pb, annotation_prefix) {
        positions.allocate(pb, tree_depth);
        authvars.reset(new gunero_merkle_authentication_path_variable<FieldT, HashT>(
            pb, tree_depth, "auth"
        ));
        auth.reset(new gunero_merkle_tree_check_read_gadget<FieldT, HashT>(
            pb,
            tree_depth,
            positions,
            leaf,
            root,
            *authvars,
            enforce,
            "path"
        ));
    }

    void generate_r1cs_constraints() {
        for (size_t i = 0; i < tree_depth; i++) {
            // TODO: This might not be necessary, and doesn't
            // appear to be done in libsnark's tests, but there
            // is no documentation, so let's do it anyway to
            // be safe.
            generate_boolean_r1cs_constraint<FieldT>(
                this->pb,
                positions[i],
                "boolean_positions"
            );
        }

        authvars->generate_r1cs_constraints();
        auth->generate_r1cs_constraints();
    }

    void generate_r1cs_witness(const std::vector<gunero_merkle_authentication_node>& M_account, const libff::bit_vector& A_account)
    {
        // size_t path_index_account = convertVectorToInt(path.index_account);
        // uint256 path_A_account = bool_vector_to_uint256(A_account);
        // size_t path_index_account = convertVectorToInt(A_account);

        // positions.fill_with_bits_of_ulong(this->pb, path_index_account);
        libff::bit_vector A_account_LSB(tree_depth);
        for(size_t i = 0; i < tree_depth; i++)
        {
            A_account_LSB.at(i) = A_account.at(tree_depth - 1 - i);
        }
        positions.fill_with_bits(this->pb, A_account_LSB);

        // authvars->generate_r1cs_witness(path_index_account, path.authentication_path);
        // auth->generate_r1cs_witness();

        // positions.fill_with_bits(this->pb, A_account);

        authvars->generate_r1cs_witness(A_account, M_account);
        auth->generate_r1cs_witness();
    }
};

} // end namespace `gunero`

#endif /* GUNERO_MERKLE_TREE_GADGET_H_ */

max_stars_repo_name: GunClear/Silencer

max_issues_repo_name: GunClear/Silencer

max_forks_repo_name: GunClear/Silencer


text:
//  Copyright (c) 2013-2014 Thomas Heller
//  Copyright (c) 2007-2012 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef HPX_PARCELSET_POLICIES_IBVERBS_SENDER_HPP
#define HPX_PARCELSET_POLICIES_IBVERBS_SENDER_HPP

#include <hpx/runtime/parcelset/locality.hpp>
#include <hpx/runtime/parcelset/parcelport_connection.hpp>
#include <hpx/runtime/parcelset/policies/ibverbs/context.hpp>
#include <hpx/runtime/parcelset/policies/ibverbs/messages.hpp>
#include <hpx/runtime/parcelset/policies/ibverbs/allocator.hpp>
#include <hpx/performance_counters/parcels/data_point.hpp>
#include <hpx/performance_counters/parcels/gatherer.hpp>
#include <hpx/util/high_resolution_timer.hpp>

#include <boost/asio/placeholders.hpp>

namespace hpx { namespace parcelset { namespace policies { namespace ibverbs
{
    class connection_handler;
    void add_sender(connection_handler & handler,
        boost::shared_ptr<sender> const& sender_connection);

    ibverbs_mr register_buffer(connection_handler & handler,
        ibv_pd * pd, char * buffer, std::size_t size, int access);

    class sender
      : public parcelset::parcelport_connection<
            sender
          , std::vector<char, allocator<message::payload_size> >
        >//data_buffer>
    {
        typedef bool(sender::*next_function_type)();
    public:
        typedef
            HPX_STD_FUNCTION<void(boost::system::error_code const &, std::size_t)>
            handler_function_type;
        typedef
            HPX_STD_FUNCTION<
                void(
                    boost::system::error_code const &
                  , parcelset::locality const&
                  , boost::shared_ptr<sender>
                )
            >
            postprocess_function_type;

        sender(connection_handler & handler, util::memory_chunk_pool & pool, parcelset::locality const& there,
            performance_counters::parcels::gatherer& parcels_sent)
          : context_(), parcelport_(handler), there_(there), parcels_sent_(parcels_sent), memory_pool_(pool)
        {
        }

        ~sender()
        {
            // gracefully and portably shutdown the socket
            boost::system::error_code ec;
            context_.shutdown(ec); // shut down data connection
            context_.close(ec);    // close the socket to give it back to the OS
        }

        /// Get the window associated with the parcelport_connection.
        client_context& context() { return context_; }

        void verify(parcelset::locality const & parcel_locality_id)
        {
            HPX_ASSERT(parcel_locality_id == there_);
        }

        parcelset::locality const& destination() const
        {
            return there_;
        }

        boost::shared_ptr<parcel_buffer_type> get_buffer(parcel const & p, std::size_t arg_size)
        {
            if(!buffer_)
            {
                boost::system::error_code ec;
                buffer_
                    = boost::shared_ptr<parcel_buffer_type>(
                        new parcel_buffer_type(
                            allocator<message::payload_size>(memory_pool_)
                        )
                    );
                buffer_->data_.reserve(arg_size);
            }
            return buffer_;
        }

        /// Asynchronously write a data structure to the socket.
        template <typename Handler, typename ParcelPostprocess>
        void async_write(Handler handler, ParcelPostprocess parcel_postprocess)
        {
            /// Increment sends and begin timer.
            buffer_->data_point_.time_ = timer_.elapsed_nanoseconds();
            HPX_ASSERT(buffer_->num_chunks_.first == 0u);

            handler_ = handler;
            postprocess_ = parcel_postprocess;

            send_size();
            add_sender(parcelport_, shared_from_this());
        }

        bool done()
        {
            next_function_type f = 0;
            {
                hpx::lcos::local::spinlock::scoped_lock l(mtx_);
                f = next_;
            }
            if(f != 0)
            {
                if(((*this).*f)())
                {
                    error_code ec;
                    handler_(ec, buffer_->data_.size());
                    buffer_->data_point_.time_ = timer_.elapsed_nanoseconds()
                        - buffer_->data_point_.time_;
                    parcels_sent_.add_data(buffer_->data_point_);
                    postprocess_function_type pp;
                    std::swap(pp, postprocess_);
                    pp(ec, there_, shared_from_this());
                    mr_.reset();
                    return true;
                }
            }
            return false;
        }

    private:
        bool send_size()
        {
            boost::system::error_code & ec = boost::system::throws;
            std::size_t size = buffer_->data_.size();
            HPX_ASSERT(buffer_->num_chunks_.first == 0u);
            if(size <= message::payload_size)
            {
                context_.connection().send_small_msg(&buffer_->data_[0], size, ec);
                return next(&sender::sent_small_msg);
            }
            else
            {
                context_.send_size(buffer_->data_.size(), ec);
                mr_ = register_buffer(
                    parcelport_
                  , context_.pd_
                  , &buffer_->data_[0]
                  , buffer_->data_.size()
                  , IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);

                adapted_mr_ = *mr_.mr_;
                adapted_mr_.addr = &buffer_->data_[0];
                adapted_mr_.length = buffer_->data_.size();

                return next(&sender::sent_size);
            }
        }

        bool sent_small_msg()
        {
            boost::system::error_code & ec = boost::system::throws;
            if(context_.check_wc<false>(MSG_SIZE, ec))
            {
                context_.post_receive(ec);
                return next(&sender::read_ack);
            }
            return false;
        }

        bool sent_size()
        {
            boost::system::error_code & ec = boost::system::throws;
            if(context_.check_wc<false>(MSG_SIZE, ec))
            {
                context_.post_receive(ec);
                return next(&sender::read_mr);
            }
            return false;
        }

        bool read_mr()
        {
            if(context_.check_wc<false>(MSG_MR, boost::system::throws))
            {
                return send_data();
            }
            return false;
        }

        bool send_data()
        {
            context_.connection().write_remote(
                &buffer_->data_[0]
              , &adapted_mr_
              , buffer_->data_.size()
              , boost::system::throws
            );
            return next(&sender::sent_data);
        }

        bool sent_data()
        {
            boost::system::error_code & ec = boost::system::throws;
            if(context_.check_wc<false>(MSG_DATA, ec))
            {
                context_.post_receive(ec);
                return next(&sender::read_ack);
            }
            return false;
        }

        bool read_ack()
        {
            boost::system::error_code & ec = boost::system::throws;
            if(context_.check_wc<false>(MSG_DONE, ec))
            {
                next(0);
                return true;
            }
            return false;
        }

        bool next(next_function_type f)
        {
            hpx::lcos::local::spinlock::scoped_lock l(mtx_);
            next_ = f;
            return false;
        }

        /// Context for the parcelport_connection.
        client_context context_;

        hpx::lcos::local::spinlock mtx_;
        next_function_type next_;

        handler_function_type handler_;
        postprocess_function_type postprocess_;

        connection_handler & parcelport_;

        /// the other (receiving) end of this connection
        parcelset::locality there_;
        /// Counters and their data containers.
        util::high_resolution_timer timer_;
        performance_counters::parcels::gatherer& parcels_sent_;

        util::memory_chunk_pool & memory_pool_;
        ibverbs_mr mr_;
        ibv_mr adapted_mr_;
    };
}}}}

#endif


text:
/*
    This file is part of solidity.

    solidity is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Alex Beregszaszi
 * @date 2017
 * Unit tests for the LLL compiler.
 */

#include <string>
#include <memory>
#include <boost/test/unit_test.hpp>
#include <liblll/Compiler.h>

using namespace std;

namespace dev
{
namespace lll
{
namespace test
{

namespace
{

bool successCompile(std::string const& _sourceCode)
{
	std::vector<std::string> errors;
	bytes bytecode = eth::compileLLL(_sourceCode, false, &errors);
	if (!errors.empty())
		return false;
	if (bytecode.empty())
		return false;
	return true;
}

}

BOOST_AUTO_TEST_SUITE(LLLCompiler)

BOOST_AUTO_TEST_CASE(smoke_test)
{
	char const* sourceCode = "1";
	BOOST_CHECK(successCompile(sourceCode));
}

BOOST_AUTO_TEST_CASE(switch_valid)
{
	char const* sourceCode = R"(
		(switch (origin))
	)";
	BOOST_CHECK(successCompile(sourceCode));
	sourceCode = R"(
		(switch
			1 (panic)
			2 (panic))
	)";
	BOOST_CHECK(successCompile(sourceCode));
	sourceCode = R"(
		(switch
			1 (panic)
			2 (panic)
			(panic))
	)";
	BOOST_CHECK(successCompile(sourceCode));
	sourceCode = R"(
		(switch
			1 (origin)
			2 (origin)
			(origin))
	)";
	BOOST_CHECK(successCompile(sourceCode));
}

BOOST_AUTO_TEST_CASE(switch_invalid_arg_count)
{
	char const* sourceCode = R"(
		(switch)
	)";
	BOOST_CHECK(!successCompile(sourceCode));
}

BOOST_AUTO_TEST_CASE(switch_inconsistent_return_count)
{
	// cannot return stack items if the default case is not present
	char const* sourceCode = R"(
		(switch
			1 (origin)
			2 (origin)
	)";
	BOOST_CHECK(!successCompile(sourceCode));
	// return count mismatch
	sourceCode = R"(
		(switch
			1 (origin)
			2 (origin)
			(panic))
	)";
	BOOST_CHECK(!successCompile(sourceCode));
	// return count mismatch
	sourceCode = R"(
		(switch
			1 (panic)
			2 (panic)
			(origin))
	)";
	BOOST_CHECK(!successCompile(sourceCode));
}

BOOST_AUTO_TEST_SUITE_END()

}
}
} // end namespaces

max_stars_repo_name: jansenbarabona/NFT-Game-Development

max_issues_repo_name: jansenbarabona/NFT-Game-Development

max_forks_repo_name: jansenbarabona/NFT-Game-Development


text:
// [===========================================================================]
// [                                M o n e t a                                ]
// [---------------------------------------------------------------------------]
// [                                                                           ]
// [                          Copyright (C) 2005-2015                          ]
// [                      Rodrigo Madera <madera@acm.org>                      ]
// [                                                                           ]
// [---------------------------------------------------------------------------]
// [         Distributed under the Boost Software License, Version 1.0         ]
// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]
// [===========================================================================]

// TODO: FIXME: This needs serious work on the repetition and/or dispatch logic!!!

#pragma once
#include <boost/mpl/transform_view.hpp>
#include <boost/mpl/size.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/size.hpp>
#include <boost/fusion/adapted.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/container/vector/convert.hpp>
#include <boost/fusion/include/as_vector.hpp>

namespace moneta { namespace traits { namespace detail {

	template <class Sequence>
	struct basic_tie_vector : boost::fusion::result_of::as_vector<
		typename boost::mpl::transform_view<
			Sequence,
			boost::add_reference<boost::mpl::_1>
		>::type
	> {};

	template <class Sequence, int Size = boost::mpl::size<Sequence>::value>
	struct tie_vector_impl;

	// TODO: Boost.PPize this.

	template <class Sequence>
	struct tie_vector_impl<Sequence, 1> : basic_tie_vector<Sequence> {
		typename basic_tie_vector<Sequence>::type operator()(Sequence& s) {
			using boost::fusion::at_c;
			return typename basic_tie_vector<Sequence>::type(at_c<0>(s));
		}
	};

	template <class Sequence>
	struct tie_vector_impl<Sequence, 2> : basic_tie_vector<Sequence> {
		typename basic_tie_vector<Sequence>::type operator()(Sequence& s) {
			using boost::fusion::at_c;
			return typename basic_tie_vector<Sequence>::type(at_c<0>(s), at_c<1>(s));
		}
	};

	template <class Sequence>
	struct tie_vector_impl<Sequence, 3> : basic_tie_vector<Sequence> {
		typename basic_tie_vector<Sequence>::type operator()(Sequence& s) {
			using boost::fusion::at_c;
			return typename basic_tie_vector<Sequence>::type(at_c<0>(s), at_c<1>(s), at_c<2>(s));
		}
	};

	template <class Sequence>
	typename tie_vector_impl<Sequence>::type
	tie_vector(Sequence& sequence) {
		return tie_vector_impl<Sequence>()(sequence);
	}

}}}

ext: hxx

max_stars_repo_name: madera/Moneta

max_issues_repo_name: madera/Moneta

max_forks_repo_name: madera/Moneta


text:
// -*- mode: C++; tab-width: 4; c-basic-offset: 4 -*-

// If the compressor requires full-image buffers (for entropy-coding
// optimization or a multi-scan JPEG file), it will create temporary
// files for anything that doesn't fit within the maximum-memory setting.
// (Note that temp files are NOT needed if you use the default parameters.)
// On some systems you may need to set up a signal handler to ensure that
// temporary files are deleted if the program is interrupted.  See libjpeg.doc.

#define BOOST_ENABLE_ASSERT_HANDLER
#include <boost/assert.hpp>

#include "jpeg_writer.h"
#include "jpeg_error.h"
#include "system_error.h"

namespace image {

    using namespace std;
    //using namespace log4cxx;
    namespace fs = boost::filesystem;

    jpeg_writer::jpeg_writer(
        const fs::path & file_path,
        const JSAMPLE * image_buffer,
        unsigned int image_width,
        unsigned int image_height,
        unsigned int num_components,
        unsigned int quality,
        bool overwrite)
        : /*logger_(Logger::getLogger(_T("genera.jpeg_writer"))),*/
          image_buffer_(image_buffer),
          image_width_(image_width),
          image_height_(image_height),
          num_components_(num_components),
          quality_(quality)
    {
        BOOST_ASSERT(quality_ <= 100);

        // Open the stdio stream.
        if (overwrite) {
            stream_ = ::fopen(file_path.string().c_str(), "wb");
            if (stream_ == 0)
                throw system_error("fopen");
        }
        else {
            stream_ = ::fopen(file_path.string().c_str(), "ab");
            if (stream_ == 0)
                throw system_error("fopen");

            long stream_position = ::ftell(stream_);
            if (stream_position == -1) {
                int rc = ::fclose(stream_);
                if (rc != 0) {
//                    LOG4CXX_WARN(logger_, _T("Unable to close JPEG file."));
                }
                throw system_error("ftell");
            }

            if (stream_position != 0) {
                // The file exists alrady and is not empty.
                int rc = ::fclose(stream_);
                if (rc != 0) {
//                    LOG4CXX_WARN(logger_, _T("Unable to close JPEG file."));
                }
                throw file_exists(file_path);
            }
        }

        // We set up the normal JPEG error routines, then override error_exit.
        compress_info_.err = jpeg_std_error(&err_.standard_error_mgr);
        err_.standard_error_mgr.error_exit = jpeg_writer::error_exit_cb;

        // We use C's setjmp/longjmp facility to return control. This means that
        // the routine which calls the JPEG library must first execute a
        // setjmp() call to establish the return point.
        if (setjmp(err_.return_context)) {
            // jpeg_create_compress has signaled an error.
            int rc = ::fclose(stream_);
            if (rc != 0) {
//                LOG4CXX_WARN(logger_, _T("Unable to close JPEG file."));
            }
            throw jpeg_error("jpeg_create_compress", compress_info_);
        }

        jpeg_create_compress(&compress_info_);
    }

    jpeg_writer::~jpeg_writer() throw ()
    {
        if (setjmp(err_.return_context) != 0) {
            // jpeg_destroy_compress has signaled an error and longjmp is
            // called.
//            LOG4CXX_WARN(logger_, _T("Unable to destroy JPEG decompressor."));
        }
        else {
            jpeg_destroy_compress(&compress_info_);
        }

        int rc = ::fclose(stream_);
        if (rc != 0) {
//            LOG4CXX_WARN(logger_, _T("Unable to close JPEG file."));
        }
    }

    void jpeg_writer::write()
    {
        if (setjmp(err_.return_context))
            // The JPEG library has signaled an error.
            throw jpeg_error("jpeg_writer::write", compress_info_);

        // Use the library-supplied code to send compressed data to an stdio
        // stream.
        jpeg_stdio_dest(&compress_info_, stream_);

        compress_info_.image_width = image_width_;
        compress_info_.image_height = image_height_;
        compress_info_.input_components = num_components_;
        compress_info_.in_color_space = JCS_RGB;

        unsigned int row_stride = image_width_ * num_components_;

        jpeg_set_defaults(&compress_info_);
        jpeg_set_quality(
            &compress_info_,
            quality_,
            TRUE);  // Limit to baseline-JPEG values.

        jpeg_start_compress(
            &compress_info_,
            TRUE);  // Ensures that we will write a complete interchange-JPEG file.
                    // Pass TRUE unless you are very sure of what you're doing.

        // jpeg_write_scanlines expects an array of pointers to scanlines.
        // Here the array is only one element long
        JSAMPROW scanline_ptrs[1];
        scanline_ptrs[0] = const_cast<JSAMPLE *>(image_buffer_);

        // Here we use the library's state variable cinfo.next_scanline as the
        // loop counter, so that we don't have to keep track ourselves.
        while (compress_info_.next_scanline < compress_info_.image_height) {
            unsigned int num_written = jpeg_write_scanlines(
                &compress_info_, scanline_ptrs, 1);
            // Partial writes can only occur if you use a data destination module
            // that can demand suspension of the compressor.
            BOOST_ASSERT(num_written == 1);

            scanline_ptrs[0] += row_stride;
        }

        ::jpeg_finish_compress(&compress_info_);
    }

    /// \brief A replacement for the standard error_exit function. Returns
    /// control to the previously saved context.
    ///
    void jpeg_writer::error_exit_cb(j_common_ptr compress_info)
    {
        extended_error_mgr & err =
            *reinterpret_cast<extended_error_mgr *>
            (compress_info->err);

        longjmp(err.return_context, 1);
    }

}

ext: cc

max_stars_repo_name: senarvi/senarvi-image

max_issues_repo_name: senarvi/senarvi-image

max_forks_repo_name: senarvi/senarvi-image


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

    @copyright 2016 NumScale SAS

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

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-boolean
    This function object conditionally returns @c x+1 (respectively @c x)
    if @c c is @ref True (respectively  @ref False)

    @par Header <boost/simd/function/if_inc.hpp>

    @par Example:

      @snippet if_inc.cpp if_inc

    @par Possible output:

      @snippet if_inc.txt if_inc

  **/
  Value1 if_inc(Value0 const& c, Value1 const& x);
} }
#endif

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

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#ifndef GAME_STATE_CHARACTERMANAGER_H
#define GAME_STATE_CHARACTERMANAGER_H

#include <boost/filesystem/path.hpp>

#include "character.hpp"

namespace MWState
{
    class CharacterManager
    {
            boost::filesystem::path mPath;

            // Uses std::list, so that mCurrent stays valid when characters are deleted
            std::list<Character> mCharacters;

            Character *mCurrent;
            std::string mGame;

        private:

            CharacterManager (const CharacterManager&);
            ///< Not implemented

            CharacterManager& operator= (const CharacterManager&);
            ///< Not implemented

            std::list<Character>::iterator findCharacter(const MWState::Character* character);

        public:

            CharacterManager (const boost::filesystem::path& saves, const std::string& game);

            Character *getCurrentCharacter (bool create, const std::string& name);
            ///< \param create Create a new character, if there is no current character.
            /// \param name The character name to use in case a new character is created.

            void deleteSlot(const MWState::Character *character, const MWState::Slot *slot);

            void createCharacter(const std::string& name);
            ///< Create new character within saved game management
            /// \param name Name for the character (does not need to be unique)

            void setCurrentCharacter (const Character *character);

            void clearCurrentCharacter();

            std::list<Character>::const_iterator begin() const;

            std::list<Character>::const_iterator end() const;
    };
}

#endif

max_stars_repo_name: Bodillium/openmw

max_issues_repo_name: Bodillium/openmw

max_forks_repo_name: Bodillium/openmw


text:
// Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
// Use of this source code is governed by a apache 2.0 license that can be
// found in the LICENSE file.

#include "common/plugins/plugin_list_parser.h"

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

namespace common_installer {

PluginInfo::PluginInfo(int flag, const std::string& type,
                       const std::string& name,
                       const boost::filesystem::path& path)
    : flag_(flag),
      type_(std::move(type)),
      name_(std::move(name)),
      path_(std::move(path)) {}

int PluginInfo::flag() const { return flag_; }

const std::string& PluginInfo::type() const { return type_; }

const std::string& PluginInfo::name() const { return name_; }

const boost::filesystem::path& PluginInfo::path() const { return path_; }

// class PluginsListParser
bool PluginsListParser::ValidType(const std::string& type) {
  if (type.empty()) {
    LOG(ERROR) << "Type is empty (valid function)";
    return false;
  }
  std::regex re_valid(R"((tag|metadata|category))");
  return std::regex_search(type, re_valid);
}

bool PluginsListParser::ValidFlag(const std::string& flag) {
  if (flag.empty()) {
    LOG(ERROR) << "Flag is empty (valid function)";
    return false;
  }

  std::regex re_valid(R"(0x[01248]+)");
  return std::regex_match(flag, re_valid);
}

bool PluginsListParser::ValidName(const std::string& name) {
  if (name.empty()) {
    LOG(ERROR) << "Name is empty (valid function)";
    return false;
  }

  return true;
}

bool PluginsListParser::ValidPath(const std::string& path) {
  if (path.empty()) {
    LOG(ERROR) << "Path is empty (valid function)";
    return false;
  }

  std::smatch match;
  std::regex re_extension(R"((\.so[^/]+)?$)");

  if (!std::regex_search(path, match, re_extension)) {
    return false;
  }

  // if no matched group
  if (match.size() != 2) {
    LOG(ERROR) << "Path not included extension lib file";
    return false;
  }

  return true;
}

std::string PluginsListParser::ExtractRaw(const std::string& data,
                                          const std::regex& re_extract) {
  std::smatch match;
  std::regex_search(data, match, re_extract);

  // 2 mean matched group
  if (match.size() != 2) {
    LOG(ERROR) << "Could not find data during extracting parameter";
    return {};
  }
  return match[1];
}

std::string PluginsListParser::ExtractFlag(const std::string& flag) {
  std::regex re_extract(R"(flag\s*\=\s*\"(.*)\")");
  return ExtractRaw(flag, re_extract);
}

std::string PluginsListParser::ExtractName(const std::string& type) {
  std::regex re_extract(R"(name\s*\=\s*\"(.*)\")");
  return ExtractRaw(type, re_extract);
}

std::string PluginsListParser::ExtractType(const std::string& type) {
  std::regex re_extract(R"(type\s*\=\s*\"(.*)\")");
  return ExtractRaw(type, re_extract);
}

std::string PluginsListParser::ExtractPath(const std::string& path) {
  std::regex re_extract(R"(path\s*\=\s*\"(.*)\")");
  return ExtractRaw(path, re_extract);
}

bool PluginsListParser::Parse() {
  std::vector<std::string> lines;

  if (!ReadLinesFromFile(&lines)) {
    LOG(ERROR) << "No read lines from file";
    return false;
  }

  if (!ParsePluginsRawData(lines)) {
    LOG(ERROR) << "No parse data from lines";
    return false;
  }

  return true;
}

const PluginsListParser::PluginList& PluginsListParser::PluginInfoList() const {
  return plugin_info_list_;
}

bool PluginsListParser::ReadLinesFromFile(std::vector<std::string>* lines) {
  std::ifstream plugins_file;

  plugins_file.open(path_);

  if (!plugins_file.is_open()) {
    LOG(ERROR) << "File " << path_ << " no open";
    return false;
  }

  LOG(INFO) << "Plugin list path: " << path_;

  std::string line;
  while (plugins_file >> line) {
    lines->push_back(line);
  }

  plugins_file.close();

  if (lines->empty()) {
    LOG(ERROR) << "No data in file " << path_;
    return false;
  }

  return true;
}

bool PluginsListParser::ParsePluginsRawData(
    const std::vector<std::string>& lines) {
  plugin_info_list_.clear();

  std::vector<int> flag_container;

  for (const std::string& line : lines) {
    std::vector<std::string> parts;
    if (!SplitPluginLine(line, &parts)) {
      LOG(ERROR) << "Invalid split plugin line";
      return false;
    }

    std::string flag = ExtractFlag(parts.at(Flag));
    std::string type = ExtractType(parts.at(Type));
    std::string name = ExtractName(parts.at(Name));
    std::string path = ExtractPath(parts.at(Path));

    if (!ValidFlag(flag)) {
      LOG(ERROR) << "Invalid flag: " << flag;
      return false;
    }

    const int kConvertStringBase = 16;
    int _flag = std::strtoul(flag.c_str(), nullptr, kConvertStringBase);

    // flag should be unique
    if (std::find(flag_container.begin(), flag_container.end(), _flag) !=
        flag_container.end()) {
      LOG(ERROR) << "Flag isn't unique, flag:  " << _flag;
      return false;
    } else {
      flag_container.push_back(_flag);
    }

    if (!ValidType(type)) {
      LOG(ERROR) << "Invalid type: " << type;
      return false;
    }

    if (!ValidName(name)) {
      LOG(ERROR) << "Invalid name: " << name;
      return false;
    }

    if (!ValidPath(path)) {
      LOG(ERROR) << "Invalid path: " << path;
      return false;
    }

    boost::filesystem::path _path = boost::filesystem::path(path);

    plugin_info_list_.push_back(
        std::make_shared<PluginInfo>(_flag, type, name, _path));
  }

  return true;
}

bool PluginsListParser::SplitPluginLine(const std::string& line,
                                        std::vector<std::string>* parts) {
  static const char kPartsInLine = 4;

  std::vector<std::string> _parts;
  boost::algorithm::split(_parts, line, boost::algorithm::is_any_of(";"));

  if (_parts.size() != kPartsInLine) {
    LOG(ERROR) << "Invalid number of parts";
    return false;
  }

  parts->assign(_parts.begin(), _parts.end());

  return true;
}
}  // namespace common_installer