text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright 2019 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include <ripple/net/DatabaseDownloader.h>
#include <test/jtx.h>
#include <test/jtx/TrustedPublisherServer.h>
#include <test/unit_test/FileDirGuard.h>
#include <boost/filesystem/operations.hpp>
#include <boost/predef.h>
#include <mutex>
#include <condition_variable>

namespace ripple {
namespace test {

class SSLHTTPDownloader_test : public beast::unit_test::suite
{
    TrustedPublisherServer createServer(
        jtx::Env& env,
        bool ssl = true)
    {
        std::vector<TrustedPublisherServer::Validator> list;
        list.push_back (TrustedPublisherServer::randomValidator());
        return TrustedPublisherServer {
            env.app().getIOService(),
            list,
            env.timeKeeper().now() + std::chrono::seconds{3600},
            ssl};
    }

    struct DownloadCompleter
    {
        std::mutex m;
        std::condition_variable cv;
        bool called = false;
        boost::filesystem::path dest;

        void operator ()(boost::filesystem::path dst)
        {
            std::unique_lock<std::mutex> lk(m);
            called = true;
            dest = std::move(dst);
            cv.notify_one();
        };

        bool waitComplete()
        {
            std::unique_lock<std::mutex> lk(m);
            using namespace std::chrono_literals;
#if BOOST_OS_WINDOWS
            auto constexpr timeout = 4s;
#else
            auto constexpr timeout = 2s;
#endif
            auto stat = cv.wait_for(lk, timeout, [this]{return called;});
            called = false;
            return stat;
        };
    };
    DownloadCompleter cb;

    struct Downloader
    {
        test::StreamSink sink_;
        beast::Journal journal_;
        // The SSLHTTPDownloader must be created as shared_ptr
        // because it uses shared_from_this
        std::shared_ptr<DatabaseDownloader> ptr_;

        Downloader(jtx::Env& env)
        : journal_ {sink_}
        , ptr_ {std::make_shared<DatabaseDownloader>(
              env.app().getIOService(), journal_, env.app().config())}
        {}

        DatabaseDownloader* operator->()
        {
            return ptr_.get();
        }
    };

    void
    testDownload(bool verify)
    {
        testcase <<
            std::string("Basic download - SSL ") +
            (verify ? "Verify" : "No Verify");

        using namespace jtx;

        ripple::test::detail::FileDirGuard cert {
            *this, "_cert", "ca.pem", TrustedPublisherServer::ca_cert()};

        Env env {*this, envconfig([&cert, &verify](std::unique_ptr<Config> cfg)
            {
                if ((cfg->SSL_VERIFY = verify)) //yes, this is assignment
                    cfg->SSL_VERIFY_FILE = cert.file().string();
                return cfg;
            })};

        Downloader downloader {env};

        // create a TrustedPublisherServer as a simple HTTP
        // server to request from. Use the /textfile endpoint
        // to get a simple text file sent as response.
        auto server = createServer(env);

        ripple::test::detail::FileDirGuard const data {
            *this, "downloads", "data", "", false, false};
        // initiate the download and wait for the callback
        // to be invoked
        auto stat = downloader->download(
            server.local_endpoint().address().to_string(),
            std::to_string(server.local_endpoint().port()),
            "/textfile",
            11,
            data.file(),
            std::function<void(boost::filesystem::path)> {std::ref(cb)});
        if (!BEAST_EXPECT(stat))
        {
            log << "Failed. LOGS:\n" + downloader.sink_.messages().str();
            return;
        }
        if (!BEAST_EXPECT(cb.waitComplete()))
        {
            log << "Failed. LOGS:\n" + downloader.sink_.messages().str();
            return;
        }
        BEAST_EXPECT(cb.dest == data.file());
        if (!BEAST_EXPECT(boost::filesystem::exists(data.file())))
            return;
        BEAST_EXPECT(boost::filesystem::file_size(data.file()) > 0);
    }

    void
    testFailures()
    {
        testcase("Error conditions");

        using namespace jtx;

        Env env {*this};

        {
            // bad hostname
            boost::system::error_code ec;
            boost::asio::ip::tcp::resolver resolver {env.app().getIOService()};
            auto const results = resolver.resolve("badhostname", "443", ec);
            // we require an error in resolving this name in order
            // for this test to pass. Some networks might have DNS hijacking
            // that prevent NXDOMAIN, in which case the failure is not
            // possible, so we skip the test.
            if (ec)
            {
                Downloader dl {env};
                ripple::test::detail::FileDirGuard const datafile {
                    *this, "downloads", "data", "", false, false};
                BEAST_EXPECT(dl->download(
                    "badhostname",
                    "443",
                    "",
                    11,
                    datafile.file(),
                    std::function<void(boost::filesystem::path)> {std::ref(cb)}));
                BEAST_EXPECT(cb.waitComplete());
                BEAST_EXPECT(!boost::filesystem::exists(datafile.file()));
                BEAST_EXPECTS(
                    dl.sink_.messages().str().find("async_resolve")
                        != std::string::npos,
                    dl.sink_.messages().str());
            }
        }
        {
            // can't connect
            Downloader dl {env};
            ripple::test::detail::FileDirGuard const datafile {
                *this, "downloads", "data", "", false, false};
            auto server = createServer(env);
            auto host = server.local_endpoint().address().to_string();
            auto port = std::to_string(server.local_endpoint().port());
            server.stop();
            BEAST_EXPECT(dl->download(
                host,
                port,
                "",
                11,
                datafile.file(),
                std::function<void(boost::filesystem::path)> {std::ref(cb)}));
            BEAST_EXPECT(cb.waitComplete());
            BEAST_EXPECT(!boost::filesystem::exists(datafile.file()));
            BEAST_EXPECTS(
                dl.sink_.messages().str().find("async_connect")
                    != std::string::npos,
                dl.sink_.messages().str());
        }
        {
            // not ssl (failed handlshake)
            Downloader dl {env};
            ripple::test::detail::FileDirGuard const datafile {
                *this, "downloads", "data", "", false, false};
            auto server = createServer(env, false);
            BEAST_EXPECT(dl->download(
                server.local_endpoint().address().to_string(),
                std::to_string(server.local_endpoint().port()),
                "",
                11,
                datafile.file(),
                std::function<void(boost::filesystem::path)> {std::ref(cb)}));
            BEAST_EXPECT(cb.waitComplete());
            BEAST_EXPECT(!boost::filesystem::exists(datafile.file()));
            BEAST_EXPECTS(
                dl.sink_.messages().str().find("async_handshake")
                    != std::string::npos,
                dl.sink_.messages().str());
        }
        {
            // huge file (content length)
            Downloader dl {env};
            ripple::test::detail::FileDirGuard const datafile {
                *this, "downloads", "data", "", false, false};
            auto server = createServer(env);
            BEAST_EXPECT(dl->download(
                server.local_endpoint().address().to_string(),
                std::to_string(server.local_endpoint().port()),
                "/textfile/huge",
                11,
                datafile.file(),
                std::function<void(boost::filesystem::path)> {std::ref(cb)}));
            BEAST_EXPECT(cb.waitComplete());
            BEAST_EXPECT(!boost::filesystem::exists(datafile.file()));
            BEAST_EXPECTS(
                dl.sink_.messages().str().find("Insufficient disk space")
                    != std::string::npos,
                dl.sink_.messages().str());
        }
    }

public:
    void
    run() override
    {
        testDownload(true);
        testDownload(false);
        testFailures();
    }

};

BEAST_DEFINE_TESTSUITE(SSLHTTPDownloader, net, ripple);
}  // namespace test
}  // namespace ripple

ext: cpp

max_stars_repo_name: carlhua/rippled

max_issues_repo_name: carlhua/rippled

max_forks_repo_name: carlhua/rippled


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

#include <commander/algorithm.hpp>

#include <boost/test/unit_test.hpp>

#include <string_view>

BOOST_AUTO_TEST_CASE( string_literal_to_view )
{
    namespace com = commander;
    using sv = std::string_view;

    {
        {
            auto view = com::string_literal_to_view<sv>("");
            BOOST_CHECK(view.size() == 0); BOOST_CHECK(view == "");
        }

        {
            auto view = com::string_literal_to_view<sv>(" ");
            BOOST_CHECK(view.size() == 1); BOOST_CHECK(view == " ");
        }

        {
            auto view = com::string_literal_to_view<sv>("  ");
            BOOST_CHECK(view.size() == 2); BOOST_CHECK(view == "  ");
        }

        {
            auto view = com::string_literal_to_view<sv>("\0");
            BOOST_CHECK(view.size() == 1); BOOST_CHECK(view[0] == '\0');
        }

        {
            auto view = com::string_literal_to_view<sv>("\0\0");
            BOOST_CHECK(view.size() == 2); BOOST_CHECK(view[0] == '\0' && view[1] == '\0');
        }
    }

    {
        {
            char literal[1] = {'\0'};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 0); BOOST_CHECK(view == "");
        }

        {
            char literal[2] = {' ', '\0'};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 1); BOOST_CHECK(view == " ");
        }

        {
            char literal[3] = {' ', ' ', '\0'};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 2); BOOST_CHECK(view == "  ");
        }

        {
            char literal[2] = {'\0', '\0'};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 1); BOOST_CHECK(view[0] == '\0');
        }

        {
            char literal[3] = {'\0', '\0', '\0'};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 2); BOOST_CHECK(view[0] == '\0' && view[1] == '\0');
        }
    }

    {
        {
            char literal[1] = {' '};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 1); BOOST_CHECK(view == " ");
        }

        {
            char literal[2] = {' ', ' '};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 2); BOOST_CHECK(view == "  ");
        }

        {
            char literal[3] = {' ', ' ', ' '};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 3); BOOST_CHECK(view == "   ");
        }

        {
            char literal[2] = {'\0', ' '};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 2); BOOST_CHECK(view[0] == '\0' && view[1] == ' ');
        }

        {
            char literal[3] = {'\0', '\0', ' '};
            auto view = com::string_literal_to_view<sv>(literal);
            BOOST_CHECK(view.size() == 3); BOOST_CHECK(view[0] == '\0' && view[1] == '\0' && view[2] == ' ');
        }
    }
}

max_stars_repo_name: daishe/commander

max_issues_repo_name: daishe/commander

max_forks_repo_name: daishe/commander


text:
/*!
@file
Defines `boost::hana::Enumerable`.

@copyright Louis Dionne 2015
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_HANA_ENUMERABLE_HPP
#define BOOST_HANA_ENUMERABLE_HPP

#include <boost/hana/fwd/enumerable.hpp>

#include <boost/hana/bool.hpp>
#include <boost/hana/constant.hpp>
#include <boost/hana/core/convert.hpp>
#include <boost/hana/core/datatype.hpp>
#include <boost/hana/core/default.hpp>
#include <boost/hana/core/models.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/detail/std/is_arithmetic.hpp>
#include <boost/hana/detail/std/is_same.hpp>

namespace boost { namespace hana {
    //////////////////////////////////////////////////////////////////////////
    // succ
    //////////////////////////////////////////////////////////////////////////
    template <typename E, typename>
    struct succ_impl : succ_impl<E, when<true>> { };

    template <typename E, bool condition>
    struct succ_impl<E, when<condition>> : default_ {
        static void apply(...) { }
    };

    //////////////////////////////////////////////////////////////////////////
    // pred
    //////////////////////////////////////////////////////////////////////////
    template <typename E, typename>
    struct pred_impl : pred_impl<E, when<true>> { };

    template <typename E, bool condition>
    struct pred_impl<E, when<condition>> : default_ {
        static void apply(...) { }
    };

    //////////////////////////////////////////////////////////////////////////
    // models
    //////////////////////////////////////////////////////////////////////////
    template <typename E>
    struct models_impl<Enumerable, E>
        : _integral_constant<bool,
            !is_default<succ_impl<E>>{} &&
            !is_default<pred_impl<E>>{}
        >
    { };

    //////////////////////////////////////////////////////////////////////////
    // Model for non-boolean arithmetic data types
    //////////////////////////////////////////////////////////////////////////
    template <typename E>
    struct succ_impl<E, when<
        detail::std::is_arithmetic<E>{} && !detail::std::is_same<E, bool>{}
    >> {
        template <typename X>
        static constexpr auto apply(X /* by value */ x)
        { return ++x; }
    };

    template <typename E>
    struct pred_impl<E, when<
        detail::std::is_arithmetic<E>{} && !detail::std::is_same<E, bool>{}
    >> {
        template <typename X>
        static constexpr auto apply(X /* by value */ x)
        { return --x; }
    };

    //////////////////////////////////////////////////////////////////////////
    // Model for Constants over an Enumerable data type
    //////////////////////////////////////////////////////////////////////////
    template <typename C>
    struct succ_impl<C, when<
        _models<Constant, C>{} && _models<Enumerable, typename C::value_type>{}
    >> {
        using T = typename C::value_type;
        template <typename X>
        struct _constant {
            static constexpr decltype(auto) get()
            { return boost::hana::succ(boost::hana::value<X>()); }
            struct hana { using datatype = detail::CanonicalConstant<T>; };
        };
        template <typename X>
        static constexpr decltype(auto) apply(X const&)
        { return to<C>(_constant<X>{}); }
    };

    template <typename C>
    struct pred_impl<C, when<
        _models<Constant, C>{} && _models<Enumerable, typename C::value_type>{}
    >> {
        using T = typename C::value_type;
        template <typename X>
        struct _constant {
            static constexpr decltype(auto) get()
            { return boost::hana::pred(boost::hana::value<X>()); }
            struct hana { using datatype = detail::CanonicalConstant<T>; };
        };
        template <typename X>
        static constexpr decltype(auto) apply(X const&)
        { return to<C>(_constant<X>{}); }
    };
}} // end namespace boost::hana

#endif // !BOOST_HANA_ENUMERABLE_HPP

ext: hpp

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
#include "dledger/record.hpp"
#include "dledger/ledger.hpp"
#include <iostream>
#include <ndn-cxx/security/signature-sha256-with-rsa.hpp>
#include <ndn-cxx/util/scheduler.hpp>
#include <boost/asio/io_service.hpp>

#include <ndn-cxx/util/io.hpp>
#include <ndn-cxx/security/verification-helpers.hpp>

using namespace dledger;

std::list<std::string> startingPeerPath({
    "./test-certs/test-a.cert",
    "./test-certs/test-b.cert",
    "./test-certs/test-c.cert",
    "./test-certs/test-d.cert"
});

std::string peerList[] = {
        "/dledger/test-e",
};

std::string anchorName = "/dledger";

std::string addCertificateRecord(security::KeyChain& keychain, shared_ptr<Ledger> ledger) {
    CertificateRecord record(std::to_string(std::rand()));
    const auto& pib = keychain.getPib();

    for (const std::string& peer : peerList) {
        const auto& identity = pib.getIdentity(peer);
        const auto& key = identity.getDefaultKey();
        security::Certificate newCert;

        Name certName = key.getName();
        certName.append("test-anchor").append(std::to_string(std::rand()));
        newCert.setName(certName);
        newCert.setContent(key.getDefaultCertificate().getContent());
        SignatureInfo signatureInfo;
        signatureInfo.setValidityPeriod(security::ValidityPeriod(time::system_clock::now(), time::system_clock::now() + time::days(3)));
        security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
                                          anchorName, signatureInfo);
        newCert.setFreshnessPeriod(time::days(1));
        keychain.sign(newCert, signingInfo);

        record.addCertificateItem(newCert);
    }
    ReturnCode result = ledger->createRecord(record);
    if (!result.success()) {
        std::cout << "- Adding record error : " << result.what() << std::endl;
    }
    return result.what();
}

std::string addRevokeRecord(security::KeyChain& keychain, shared_ptr<Ledger> ledger, std::string certRecordName) {
    RevocationRecord record(std::to_string(std::rand()));
    auto fetchResult = ledger->getRecord(certRecordName);
    assert(fetchResult.has_value());
    auto certRecord = CertificateRecord(*fetchResult);
    record.addCertificateNameItem(certRecord.getCertificates().begin()->getFullName());

    ReturnCode result = ledger->createRecord(record);
    if (!result.success()) {
        std::cout << "- Adding record error : " << result.what() << std::endl;
    }

    return result.what();
}

int
main(int argc, char** argv)
{
    boost::asio::io_service ioService;
    Face face(ioService);
    security::KeyChain keychain;
    std::shared_ptr<Config> config = nullptr;
    try {
        config = Config::CustomizedConfig("/ndn/broadcast/dledger", anchorName,
                                          std::string("./dledger-anchor.cert"), std::string("/tmp/dledger-db/test-anchor"),
                                          startingPeerPath);
        mkdir("/tmp/dledger-db/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    }
    catch(const std::exception& e) {
        std::cout << e.what() << std::endl;
        return 1;
    }

    shared_ptr<Ledger> ledger = std::move(Ledger::initLedger(*config, keychain, face));

    auto recordName = addCertificateRecord(keychain, ledger);
    Scheduler scheduler(ioService);
    scheduler.schedule(time::seconds(60),
            [ledger, &keychain, recordName]{addRevokeRecord(keychain, ledger, recordName);});

    face.processEvents();
    return 0;
}

max_stars_repo_name: UCLA-IRL/dledger

max_issues_repo_name: UCLA-IRL/dledger

max_forks_repo_name: UCLA-IRL/dledger


text:
//   Copyright 2015 Patrick Putnam
//
//   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.
#ifndef CLOTHO_TRAIT_SPACE_GENERATOR_HPP_
#define CLOTHO_TRAIT_SPACE_GENERATOR_HPP_

#include <boost/property_tree/ptree.hpp>
#include "clotho/data_spaces/generators/weight_parameter.hpp"
#include "clotho/data_spaces/generators/neutral_generator.hpp"

namespace clotho {
namespace genetics {

template < class RNG, class TraitSpaceType >
class TraitSpaceGenerator {
public:
    typedef TraitSpaceGenerator< RNG, TraitSpaceType > self_type;

    typedef RNG                                     random_engine_type;
    typedef TraitSpaceType                          trait_space_type;
    typedef typename trait_space_type::weight_type  weight_type;

    typedef weight_parameter< weight_type >         parameter_type;
    typedef neutral_generator2                      neutrality_generator_type;
    typedef typename neutrality_generator_type::parameter_type      neutral_param_type;

    TraitSpaceGenerator( random_engine_type * rng, boost::property_tree::ptree & config ) :
        m_rng( rng )
        , m_weights( config )
        , m_neutral( config )
    {}

    TraitSpaceGenerator( random_engine_type * rng, const parameter_type & param, const neutral_param_type & nparam ) :
        m_rng( rng )
        , m_weights( param )
        , m_neutral( nparam)
    {}

    TraitSpaceGenerator( const self_type & other ) :
        m_rng( other.m_rng )
        , m_weights( other.m_weights )
        , m_neutral( other.m_neutral )
    {}

    template < class FreeSpaceType >
    void operator()( trait_space_type & traits, FreeSpaceType & fs, unsigned int N ) {
        generate( traits, fs, N );
    }

    template < class FreeSpaceType >
    void generate( trait_space_type & traits, FreeSpaceType & fs, unsigned int N ) {
        assert( N <= fs.free_size() );

        typename FreeSpaceType::base_type::iterator it = fs.free_begin();

        while( N-- ) {
            typename FreeSpaceType::size_type offset = *it++;
            operator()( traits, offset );
        }
    }

    void operator()( trait_space_type & traits, unsigned int offset ) {
        unsigned int i = 0;
        while( i < traits.trait_count() ) {
            weight_type w = 0;
            if( !m_neutral( *m_rng ) )
                w = m_weights.m_dist( *m_rng );
            traits.setWeight( w, offset, i );
            ++i;
        }
    }

    virtual ~TraitSpaceGenerator() {}

protected:
    random_engine_type  * m_rng;
    parameter_type      m_weights;
    neutrality_generator_type m_neutral;
};

template < class TraitSpaceType >
class TraitSpaceGenerator2 {
public:

    typedef TraitSpaceGenerator2< TraitSpaceType >  self_type;
    typedef TraitSpaceType                          trait_space_type;
    typedef typename trait_space_type::weight_type  weight_type;

    typedef weight_parameter< weight_type >         parameter_type;
    typedef neutral_generator2                      neutrality_generator_type;
    typedef typename neutrality_generator_type::parameter_type      neutral_param_type;

    TraitSpaceGenerator2( boost::property_tree::ptree & config ) :
        m_weights( config )
        , m_neutral( config )
    {}

    TraitSpaceGenerator2( const parameter_type & param, const neutral_param_type & neut_rate ) :
        m_weights( param )
        , m_neutral( neut_rate )
    {}

    TraitSpaceGenerator2( const self_type & other ) :
        m_weights( other.m_weights )
        , m_neutral( other.m_neutral )
    {}

    template < class Engine >
    void operator()( Engine & eng, trait_space_type & traits, unsigned int offset ) {
        unsigned int i = 0;
        while( i < traits.trait_count() ) {

            weight_type w = 0;
            if( !m_neutral( eng ) )
                w = m_weights.m_dist( eng );
            traits.setWeight( w, offset, i );
            ++i;
        }
    }

    virtual ~TraitSpaceGenerator2() {}
protected:

    parameter_type m_weights;
    neutrality_generator_type m_neutral;
};

}   // namespace genetics
}   // namespace clotho

#endif  // CLOTHO_TRAIT_SPACE_GENERATOR_HPP_

max_stars_repo_name: putnampp/clotho

max_issues_repo_name: putnampp/clotho

max_forks_repo_name: putnampp/clotho


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Sylko Olzscher
 *
 */

#include <smf/sml/obis_io.h>
#include <iomanip>
#include <sstream>
#include <cyng/util/split.h>
#include <cyng/parser/buffer_parser.h>

#include <boost/io/ios_state.hpp>

namespace node
{
	namespace sml
	{
		std::ostream& operator<<(std::ostream& os, obis const& v)
		{
			//	store and reset stream state
			boost::io::ios_flags_saver  ifs(os);

			os
				<< std::dec
				<< v.get_medium()
				<< '-'
				<< v.get_channel()
				<< ':'
				<< v.get_indicator()
				<< '.'
				<< v.get_mode()
				<< '.'
				<< v.get_quantities()
				<< '*'
				<< v.get_storage()
				;
			return os;
		}

		std::string to_string(obis const& v)
		{
			std::ostringstream ss;
			ss << v;
			return ss.str();
		}

		std::ostream& to_hex(std::ostream& os, obis const& v)
		{
			//	store and reset stream state
			boost::io::ios_flags_saver  ifs(os);

			os
				<< std::hex
				<< std::setfill('0')
				;

			os
				<< std::setw(2)
				<< v.get_medium()
				<< ' '
				<< std::setw(2)
				<< v.get_channel()
				<< ' '
				<< std::setw(2)
				<< v.get_indicator()
				<< ' '
				<< std::setw(2)
				<< v.get_mode()
				<< ' '
				<< std::setw(2)
				<< v.get_quantities()
				<< ' '
				<< std::setw(2)
				<< v.get_storage()
				;
			return os;
		}

		std::string to_hex(obis const& v)
		{
			std::ostringstream ss;
			to_hex(ss, v);
			return ss.str();
		}

		std::string to_hex(obis_path const& p)
		{
			std::ostringstream ss;
			bool init = false;
			for (auto o : p)
			{
				if (init)
				{
					ss << " => ";
				}
				else
				{
					init = true;
				}
				to_hex(ss, o);
			}
			return ss.str();
		}

		obis to_obis(std::string const& str)
		{
			//
			//	heuristic approach
			//
			const auto size = str.size();
			auto num_dots = std::count(str.begin(), str.end(), '.');
			auto num_dashes = std::count(str.begin(), str.end(), '-');
			auto num_colons = std::count(str.begin(), str.end(), ':');
			auto num_spaces = std::count(str.begin(), str.end(), ' ');
			if (size > 8 && num_dots == 2 && num_dashes == 1 && num_colons == 1 && num_spaces == 0) {
				//
				//	decimal representation
				//	example: 1-1:1.8.1
				//
				const auto res = cyng::split(str, ".-:");
				if (res.size() == 6) {
					try {
						return obis(std::stoi(res.at(0))
							, std::stoi(res.at(1))
							, std::stoi(res.at(2))
							, std::stoi(res.at(3))
							, std::stoi(res.at(4))
							, std::stoi(res.at(5)));
					}
					catch (std::exception const&) {

					}
				}
			}
			else if (size == 12 && num_dots == 0 && num_dashes == 0 && num_colons == 0 && num_spaces == 0) {
				//
				//	hex representation
				//	example: 0100010800ff
				//
				const auto buffer = cyng::parse_hex_string(str);
				if (buffer.second && buffer.first.size() == 6) {
					return obis(buffer.first.at(0)
						, buffer.first.at(1)
						, buffer.first.at(2)
						, buffer.first.at(3)
						, buffer.first.at(4)
						, buffer.first.at(5));
				}
			}
			else if (size == 17 && num_dots == 0 && num_dashes == 0 && num_colons == 0 && num_spaces == 5) {
				//
				//	hex representation
				//	example: 01 00 01 08 00 ff
				//
				const auto res = cyng::split(str, " ");
				if (res.size() == 6) {
					const auto buffer = cyng::parse_log_string(str);
					if (buffer.second && buffer.first.size() == 6) {
						return obis(buffer.first.at(0)
							, buffer.first.at(1)
							, buffer.first.at(2)
							, buffer.first.at(3)
							, buffer.first.at(4)
							, buffer.first.at(5));
					}
				}
			}

			return obis();
		}

	}
}

max_stars_repo_name: solosTec/node

max_issues_repo_name: solosTec/node

max_forks_repo_name: solosTec/node


text:
#include <blitz/array.h>
#include <iostream>

BZ_USING_NAMESPACE(blitz)

BZ_DECLARE_STENCIL2(footprint,A,B)
    B = stenciltoapply(stencilargs);
BZ_END_STENCIL

template<class T_stencil>
void dumpStencil(const T_stencil& stencil)
{
    const int maxN = 5;

    Array<double,2> A(Range(-maxN,maxN),Range(-maxN,maxN)),
     B(Range(-maxN,maxN), Range(-maxN, maxN));

    A = 0.0;
    A(0,0) = 1;

    B = 0.0;

    applyStencil(stencil, A, B);

    B.reverseSelf(firstDim);
    B.reverseSelf(secondDim);

    using namespace blitz::tensor;

    int minrow = first(sum(B != 0.0, j));
    int maxrow = last(sum(B != 0.0, j));
    int mincol = first(sum(B(j,i) != 0.0, j));
    int maxcol = last(sum(B(j,i) != 0.0, j));

    // Code to dump HTML
		cout << "@html" << endl;
    cout << "
" << endl
         << "
	";

    for (int j=mincol; j <= maxcol; ++j)
        cout << "" << j << "	";

    cout << "
";

    for (int i=minrow; i <= maxrow; ++i)
    {
        cout << "
";

        if (minrow != maxrow)
            cout << "" << i << "	";
        else
            cout << "	";

        for (int j=mincol; j <= maxcol; ++j)
        {
            if (B(i,j) != 0.0)
            {
                if ((i == 0) && (j == 0))
                    cout << "";
                else
                    cout << "";
                cout << "" << B(i,j) << "	";
            }
            else
                cout << "	";
        }

        cout << "
" << endl;
    }
    cout << "
" << endl;
    cout << "@end html" << endl;

    // Code to dump TeX
		cout << "@tex" << endl;
		cout << "\\def\\tablevrule{\\vrule height 10pt depth 3pt}" << endl;
		cout << "\\vskip0.5\\baselineskip\\hskip\\itemindent" << endl;
		cout << "\\vbox{\\halign{\\hfill#\\quad&\\tablevrule#\\quad" << endl;
    for (int j=mincol; j <= maxcol; ++j)
        cout << "&\\hfill#\\quad";
    cout << "\\cr" << endl;
    cout << "&& ";
    for (int j=mincol; j < maxcol; ++j)
        cout << j << " & " ;
    cout << maxcol << " \\cr" << endl << "\\noalign{\\hrule}" << endl;
    for (int i=minrow; i <= maxrow; ++i)
    {
        if (minrow != maxrow)
            cout << i << " && ";
        else
            cout << " && ";
        for (int j=mincol; j <= maxcol; ++j)
        {
            if (B(i,j) != 0.0)
            {
                if ((i == 0) && (j == 0))
                    cout << "{\\bf " << B(i,j) << "} ";
                else
                    cout << " " << B(i,j) << " ";
            }
            if (j != maxcol)
                cout << " & ";
        }
        if (i != maxrow)
            cout << "\\cr" << endl;
    }
    cout <<  "\\cr}}" << endl;
    cout << "@end tex" << endl;

    // Code to dump !TeX && !HTML
		cout << "@ifnottex" << endl;
		cout << "@ifnothtml" << endl;
    cout << "@multitable {12345}";
    for (int j=mincol; j <= maxcol; ++j)
        cout << " {12345}";
    cout << endl << "@item @tab ";
    for (int j=mincol; j < maxcol; ++j)
        cout << j << " @tab " ;
    cout << maxcol << endl << "@item ";
    for (int i=minrow; i <= maxrow; ++i)
    {
        if (minrow != maxrow)
            cout << i << " @tab ";
        else
            cout << "@tab ";
        for (int j=mincol; j <= maxcol; ++j)
        {
            if (B(i,j) != 0.0)
            {
                if ((i == 0) && (j == 0))
                    cout << "@strong{" << B(i,j) << "} ";
                else
                    cout << " " << B(i,j) << " ";
            }
            if (j != maxcol)
                cout << "@tab ";
        }
        if (i != maxrow)
            cout << endl << "@item ";
    }
    cout << endl << "@end multitable" << endl;
		cout << "@end ifnothtml" << endl;
		cout << "@end ifnottex" << endl;

#if 0
    // Code to dump LaTeX
		cout << "latexcommand(" << endl;
    cout << "\\begin{tabular}{r|";
    for (int j=mincol; j <= maxcol; ++j)
        cout << "r";
    cout << "}" << endl;
    cout << " & ";
    for (int j=mincol; j < maxcol; ++j)
        cout << j << " & " ;
    cout << maxcol << " \\\\ \\hline" << endl;
    for (int i=minrow; i <= maxrow; ++i)
    {
        if (minrow != maxrow)
            cout << i << " & ";
        else
            cout << " & ";
        for (int j=mincol; j <= maxcol; ++j)
        {
            if (B(i,j) != 0.0)
            {
                if ((i == 0) && (j == 0))
                    cout << "{\\bf " << B(i,j) << "} ";
                else
                    cout << " " << B(i,j) << " ";
            }
            if (j != maxcol)
                cout << " & ";
        }
        if (i != maxrow)
            cout << " \\\\  " << endl;
    }
    cout << endl << "\\end{tabular}" << endl;
    cout << ")" << endl;
#endif
}

int main()
{
    dumpStencil(footprint());
}

max_stars_repo_name: fraguela/depspawn

max_issues_repo_name: MSV-Project/IBAMR

max_forks_repo_name: MSV-Project/IBAMR


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

#ifndef SOCIAL_ACTIVITIES_DISPLAY_H
#define SOCIAL_ACTIVITIES_DISPLAY_H
#ifndef Q_MOC_RUN
#include <map>
#include <vector>
#include <boost/circular_buffer.hpp>
#include <spencer_social_relation_msgs/SocialActivities.h>
#endif
#include "person_display_common.h"
#include "tracked_persons_cache.h"

namespace spencer_tracking_rviz_plugin
{
    typedef std::string activity_type;

    /// The display which can be added in RViz to display social activities.
    class SocialActivitiesDisplay: public PersonDisplayCommon<spencer_social_relation_msgs::SocialActivities>
    {
    Q_OBJECT
    public:
        // To determine, for persons involved in multiple social activities, their most likely one.
        struct ActivityWithConfidence {
            activity_type type;
            float confidence;
        };

        // Constructor.  pluginlib::ClassLoader creates instances by calling
        // the default constructor, so make sure you have one.
        SocialActivitiesDisplay() {};
        virtual ~SocialActivitiesDisplay();

        // Overrides of protected virtual functions from Display.  As much
        // as possible, when Displays are not enabled, they should not be
        // subscribed to incoming data and should not show anything in the
        // 3D view.  These functions are where these connections are made
        // and broken.

        // Called after the constructors have run
        virtual void onInitialize();

        // Called periodically by the visualization manager
        virtual void update(float wall_dt, float ros_dt);

    protected:
        // A helper to clear this display back to the initial state.
        virtual void reset();

        // Must be implemented by derived classes because MOC doesn't work in templates
        virtual rviz::DisplayContext* getContext() {
            return context_;
        }

    private:
        struct SocialActivityVisual {
            vector<boost::shared_ptr<rviz::Shape> > socialActivityAssignmentCircles;
            vector<boost::shared_ptr<rviz::BillboardLine> > connectionLines;
            vector< boost::shared_ptr<TextNode> > typeTexts;
            vector<track_id> trackIds;
            activity_type activityType;
            float confidence;
            geometry_msgs::Point socialActivityCenter;
            size_t personCount;
            size_t declutteringOffset; // for decluttering of labels etc. in case of multiple activities per track, e.g. 1 = shift label by 1 row
        };

        // Functions to handle an incoming ROS message.
        void processMessage(const spencer_social_relation_msgs::SocialActivities::ConstPtr& msg);

        // Helper functions
        void updateSocialActivityVisualStyles(boost::shared_ptr<SocialActivityVisual>& groupVisual);
        bool isActivityTypeHidden(activity_type activityType);
        Ogre::ColourValue getActivityColor(activity_type activityType, float confidence);

        // Scene nodes
        boost::shared_ptr<Ogre::SceneNode> m_socialActivitiesSceneNode;

        // User-editable property variables.
        rviz::StringProperty* m_excluded_activity_types_property;
        rviz::StringProperty* m_included_activity_types_property;

        rviz::BoolProperty* m_render_intraactivity_connections_property;
        rviz::BoolProperty* m_render_activity_types_property;
        rviz::BoolProperty* m_activity_type_per_track_property;
        rviz::BoolProperty* m_render_confidences_property;
        rviz::BoolProperty* m_render_circles_property;
        rviz::BoolProperty* m_hide_with_no_activity_property;

        rviz::FloatProperty* m_occlusion_alpha_property;
        rviz::FloatProperty* m_min_confidence_property;
        rviz::FloatProperty* m_circle_radius_property;
        rviz::FloatProperty* m_circle_alpha_property;
        rviz::FloatProperty* m_line_width_property;
        rviz::FloatProperty* m_activity_type_offset; // z offset of the group ID text

        rviz::Property* m_activity_colors;
        rviz::ColorProperty* m_activity_color_none;
        rviz::ColorProperty* m_activity_color_unknown;
        rviz::ColorProperty* m_activity_color_shopping;
        rviz::ColorProperty* m_activity_color_standing;
        rviz::ColorProperty* m_activity_color_individual_moving;
        rviz::ColorProperty* m_activity_color_waiting_in_queue;
        rviz::ColorProperty* m_activity_color_looking_at_information_screen;
        rviz::ColorProperty* m_activity_color_looking_at_kiosk;
        rviz::ColorProperty* m_activity_color_group_assembling;
        rviz::ColorProperty* m_activity_color_group_moving;
        rviz::ColorProperty* m_activity_color_flow;
        rviz::ColorProperty* m_activity_color_antiflow;
        rviz::ColorProperty* m_activity_color_waiting_for_others;
        rviz::ColorProperty* m_activity_color_looking_for_help;

        // State variables
        struct PersonVisualContainer {
            boost::shared_ptr<PersonVisual> personVisual;
            boost::shared_ptr<Ogre::SceneNode> sceneNode;
            track_id trackId;
        };

        vector<boost::shared_ptr<SocialActivityVisual> > m_socialActivityVisuals;
        map<track_id, PersonVisualContainer > m_personVisualMap; // to keep person visuals alive across multiple frames, for walking animation

        map<track_id, ActivityWithConfidence> m_highestConfidenceActivityPerTrack; // only highest-confidence activity per person
        map<track_id, vector<ActivityWithConfidence> > m_allActivitiesPerTrack; // all activities that a track is involved in

        set<activity_type> m_excludedActivityTypes, m_includedActivityTypes;

        Ogre::Matrix4 m_frameTransform;
        TrackedPersonsCache m_trackedPersonsCache;

    private Q_SLOTS:
        void personVisualTypeChanged();
        virtual void stylesChanged();
    };

} // end namespace spencer_tracking_rviz_plugin

#endif // SOCIAL_ACTIVITIES_DISPLAY_H


text:
//  (C) Copyright Matt Borland 2021.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <cstdint>
#include <cinttypes>
#include <boost/math/ccmath/div.hpp>
#include <boost/math/tools/is_constant_evaluated.hpp>
#include <boost/multiprecision/cpp_int.hpp>

template <typename Z>
constexpr void test()
{
    constexpr auto test_val1 = boost::math::ccmath::div(Z(1), Z(1));
    static_assert(test_val1.quot == Z(1));
    static_assert(test_val1.rem == Z(0));

    constexpr auto test_val2 = boost::math::ccmath::div(Z(1'000'000), Z(3));
    static_assert(test_val2.quot == Z(333'333));
    static_assert(test_val2.rem == Z(1));
}

#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)
int main()
{
    test<int>();
    test<long>();
    test<long long>();
    test<std::intmax_t>();

    test<std::int32_t>();
    test<std::int64_t>();
    test<std::uint32_t>();

    test<boost::multiprecision::int128_t>();
    test<boost::multiprecision::int256_t>();
    test<boost::multiprecision::int512_t>();

    return 0;
}
#else
int main()
{
    return 0;
}
#endif

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math

max_forks_repo_name: oleg-alexandrov/math


text:
// Copyright (c) 2013, Noe Casas (noe.casas@gmail.com).
// Distributed under New BSD License.
// (see accompanying file COPYING)

#ifndef ENCODING_CODEC_HEADER_SEEN__
#define ENCODING_CODEC_HEADER_SEEN__

#include <boost/dynamic_bitset.hpp>

namespace encoding
{
  /** Type to be used as bit storage */
  typedef boost::dynamic_bitset<> Bitset;

  /****************************************************************************
   * Interface of an encoding/decoding strategy.
   *
   ***************************************************************************/
  template<typename Type>
  struct Codec
  {
    /** Number of bits of the encoded data */
    const std::size_t sizeInBits;

    /**************************************************************************
     * Constructor.
     * \param bits Number of bits of the encoded data,
     *************************************************************************/
    Codec (std::size_t bits) : sizeInBits(bits) { }

    /**************************************************************************
     * Encodes the supplied piece of data.
     * \param value Value to be encoded.
     * \return The encoded bits.
     *************************************************************************/
    virtual Bitset encode(Type value) const = 0;

    /**************************************************************************
     * Decodes a piece of data from the supplied bits.
     * \param bits Encoded data to be decoded.
     * \return The decoded piece of data.
     *************************************************************************/
    virtual Type decode(const Bitset& bits) const = 0;

    /**************************************************************************
     * Destructor.
     *************************************************************************/
    virtual ~Codec() noexcept (true) { }
  };
}

#endif

max_stars_repo_name: noe/encoding

max_issues_repo_name: noe/encoding

max_forks_repo_name: noe/encoding


text:
#include <NTL/vec_lzz_p.h>

NTL_START_IMPL

// NOTE: the signature for this is in lzz_p.h
void conv(vec_zz_p& x, const vec_ZZ& a)
{
   long i, n;

   n = a.length();
   x.SetLength(n);

   VectorConv(n, x.elts(), a.elts());
}

// NOTE: the signature for this is in lzz_p.h
void conv(vec_zz_p& x, const Vec<long>& a)
{
   long i, n;

   n = a.length();
   x.SetLength(n);

   VectorConv(n, x.elts(), a.elts());
}

void InnerProduct(zz_p& x, const vec_zz_p& a, const vec_zz_p& b)
{
   long n = min(a.length(), b.length());
   long i;

   long accum, t;
   long p = zz_p::modulus();
   mulmod_t pinv = zz_p::ModulusInverse();

   const zz_p *ap = a.elts();
   const zz_p *bp = b.elts();

   accum = 0;
   for (i = 0; i < n; i++) {
      t = MulMod(rep(ap[i]), rep(bp[i]), p, pinv);
      accum = AddMod(accum, t, p);
   }

   x.LoopHole() = accum;
}

void InnerProduct(zz_p& x, const vec_zz_p& a, const vec_zz_p& b,
                  long offset)
{
   if (offset < 0) LogicError("InnerProduct: negative offset");
   if (NTL_OVERFLOW(offset, 1, 0)) ResourceError("InnerProduct: offset too big");

   long n = min(a.length(), b.length()+offset);
   long i;

   long accum, t;
   long p = zz_p::modulus();
   mulmod_t pinv = zz_p::ModulusInverse();

   const zz_p *ap = a.elts();
   const zz_p *bp = b.elts();

   accum = 0;
   for (i = offset; i < n; i++) {
      t = MulMod(rep(ap[i]), rep(bp[i-offset]), p, pinv);
      accum = AddMod(accum, t, p);
   }

   x.LoopHole() = accum;
}

long CRT(vec_ZZ& gg, ZZ& a, const vec_zz_p& G)
{
   long n = gg.length();
   if (G.length() != n) LogicError("CRT: vector length mismatch");

   long p = zz_p::modulus();

   ZZ new_a;
   mul(new_a, a, p);

   long a_inv;
   a_inv = rem(a, p);
   a_inv = InvMod(a_inv, p);

   long p1;
   p1 = p >> 1;

   ZZ a1;
   RightShift(a1, a, 1);

   long p_odd = (p & 1);

   long modified = 0;

   long h;

   ZZ g;
   long i;
   for (i = 0; i < n; i++) {
      if (!CRTInRange(gg[i], a)) {
         modified = 1;
         rem(g, gg[i], a);
         if (g > a1) sub(g, g, a);
      }
      else
         g = gg[i];

      h = rem(g, p);
      h = SubMod(rep(G[i]), h, p);
      h = MulMod(h, a_inv, p);
      if (h > p1)
         h = h - p;

      if (h != 0) {
         modified = 1;

         if (!p_odd && g > 0 && (h == p1))
            MulSubFrom(g, a, h);
         else
            MulAddTo(g, a, h);
      }

      gg[i] = g;
   }

   a = new_a;

   return modified;
}

void mul(vec_zz_p& x, const vec_zz_p& a, zz_p b)
{
   long n = a.length();
   x.SetLength(n);

   long i;

   if (n <= 1) {

      for (i = 0; i < n; i++)
         mul(x[i], a[i], b);

   }
   else {

      long p = zz_p::modulus();
      mulmod_t pinv = zz_p::ModulusInverse();
      long bb = rep(b);
      mulmod_precon_t bpinv = PrepMulModPrecon(bb, p, pinv);

      const zz_p *ap = a.elts();
      zz_p *xp = x.elts();

      for (i = 0; i < n; i++)
         xp[i].LoopHole() = MulModPrecon(rep(ap[i]), bb, p, bpinv);

   }
}

void mul(vec_zz_p& x, const vec_zz_p& a, long b_in)
{
   zz_p b;
   b = b_in;
   mul(x, a, b);
}

void add(vec_zz_p& x, const vec_zz_p& a, const vec_zz_p& b)
{
   long n = a.length();
   if (b.length() != n) LogicError("vector add: dimension mismatch");

   long p = zz_p::modulus();

   x.SetLength(n);

   const zz_p *ap = a.elts();
   const zz_p *bp = b.elts();
   zz_p *xp = x.elts();

   long i;
   for (i = 0; i < n; i++)
      xp[i].LoopHole() = AddMod(rep(ap[i]), rep(bp[i]), p);
}

void sub(vec_zz_p& x, const vec_zz_p& a, const vec_zz_p& b)
{
   long n = a.length();
   if (b.length() != n) LogicError("vector sub: dimension mismatch");

   long p = zz_p::modulus();

   x.SetLength(n);

   const zz_p *ap = a.elts();
   const zz_p *bp = b.elts();
   zz_p *xp = x.elts();

   long i;
   for (i = 0; i < n; i++)
      xp[i].LoopHole() = SubMod(rep(ap[i]), rep(bp[i]), p);
}

void clear(vec_zz_p& x)
{
   long n = x.length();

   zz_p *xp = x.elts();

   long i;
   for (i = 0; i < n; i++)
      clear(xp[i]);
}

void negate(vec_zz_p& x, const vec_zz_p& a)
{
   long n = a.length();
   long p = zz_p::modulus();

   x.SetLength(n);

   const zz_p *ap = a.elts();
   zz_p *xp = x.elts();

   long i;
   for (i = 0; i < n; i++)
      xp[i].LoopHole() = NegateMod(rep(ap[i]), p);
}

long IsZero(const vec_zz_p& a)
{
   long n = a.length();

   const zz_p *ap = a.elts();

   long i;
   for (i = 0; i < n; i++)
      if (!IsZero(ap[i]))
         return 0;

   return 1;
}

vec_zz_p operator+(const vec_zz_p& a, const vec_zz_p& b)
{
   vec_zz_p res;
   add(res, a, b);
   NTL_OPT_RETURN(vec_zz_p, res);
}

vec_zz_p operator-(const vec_zz_p& a, const vec_zz_p& b)
{
   vec_zz_p res;
   sub(res, a, b);
   NTL_OPT_RETURN(vec_zz_p, res);
}

vec_zz_p operator-(const vec_zz_p& a)
{
   vec_zz_p res;
   negate(res, a);
   NTL_OPT_RETURN(vec_zz_p, res);
}

zz_p operator*(const vec_zz_p& a, const vec_zz_p& b)
{
   zz_p res;
   InnerProduct(res, a, b);
   return res;
}

void VectorCopy(vec_zz_p& x, const vec_zz_p& a, long n)
{
   if (n < 0) LogicError("VectorCopy: negative length");
   if (NTL_OVERFLOW(n, 1, 0)) ResourceError("overflow in VectorCopy");

   long m = min(n, a.length());

   x.SetLength(n);

   const zz_p *ap = a.elts();
   zz_p *xp = x.elts();

   long i;

   for (i = 0; i < m; i++)
      xp[i] = ap[i];

   for (i = m; i < n; i++)
      clear(xp[i]);
}

void random(vec_zz_p& x, long n)
{
   x.SetLength(n);
   VectorRandom(n, x.elts());
}

NTL_END_IMPL


text:
/*=============================================================================
  Copyright (c) 2016 Jilles Steeve Dibangoye
  ==============================================================================*/
#pragma once

#include <sdm/macros.hpp>
#include <sdm/parser/ast.hpp>
#include <sdm/world/mpomdp.hpp>
#include <sdm/world/posg.hpp>
#include <sdm/world/networked_distributed_pomdp.hpp>
#include <sdm/world/bayesian_game_interface.hpp>
#include <boost/spirit/home/x3.hpp>

namespace sdm
{
  namespace x3 = boost::spirit::x3;

  /**
   * @brief Namespace grouping all functions for parsing files.
   */
  namespace parser
  {
    struct dpomdp_class;
    struct posg_class;

    typedef x3::rule<dpomdp_class, ast::dpomdp_t> dpomdp_type;
    typedef x3::rule<posg_class, ast::posg_t> posg_type;

    BOOST_SPIRIT_DECLARE(dpomdp_type)
    BOOST_SPIRIT_DECLARE(posg_type)

    SDMS_DECLARE_PARSER(sdm::MDP, parseMDP)
    SDMS_DECLARE_PARSER(sdm::POMDP, parsePOMDP)
    SDMS_DECLARE_PARSER(sdm::MPOMDP, parseMPOMDP)
    SDMS_DECLARE_PARSER(sdm::DecPOMDP, parseDecPOMDP)
    SDMS_DECLARE_PARSER(sdm::POSG, parsePOSG)

    std::shared_ptr<sdm::MPOMDP> parse_file(std::string, Config = {});

    std::shared_ptr<sdm::BayesianGameInterface> parse_file_bayesian(std::string);
    std::shared_ptr<sdm::BayesianGameInterface> parse_file_normal_form(std::string filename);

  } // namespace parser
} // namespace sdm

max_stars_repo_name: SDMStudio/sdms

max_issues_repo_name: SDMStudio/sdms

max_forks_repo_name: SDMStudio/sdms


text:
//
// Created by Alex Beccaro on 18/01/18.
//

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "../../src/problems/51-100/65/problem65.hpp"

BOOST_AUTO_TEST_SUITE( Problem65 )

    BOOST_AUTO_TEST_CASE( Example ) {
        auto res = problems::problem65::solve(10);
        BOOST_CHECK_EQUAL(res, 17);
    }

    BOOST_AUTO_TEST_CASE( Solution ) {
        auto res = problems::problem65::solve();
        BOOST_CHECK_EQUAL(res, 272);
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: abeccaro/project-euler

max_issues_repo_name: abeccaro/project-euler

max_forks_repo_name: abeccaro/project-euler


text:
// Copyright 2021-2022 Software Quality Laboratory, NYCU.
//
// 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.

#include <s2e/Plugins/CRAX/CRAX.h>

#include <boost/algorithm/searching/knuth_morris_pratt.hpp>

#include "Memory.h"

using namespace klee;

namespace s2e::plugins::crax {

bool Memory::isSymbolic(uint64_t virtAddr, uint64_t size) const {
    return m_state->mem()->symbolic(virtAddr, size);
}

ref<Expr> Memory::readSymbolic(uint64_t virtAddr, uint64_t size) const {
    // XXX: check `size`.
    // See: klee/include/klee/Expr.h
    return m_state->mem()->read(virtAddr, size);
}

std::vector<uint8_t> Memory::readConcrete(uint64_t virtAddr,
                                          uint64_t size,
                                          bool concretize) const {
    std::vector<uint8_t> ret(size);

    if (concretize) {
        if (!m_state->mem()->read(virtAddr, ret.data(), size)) {
            log<WARN>() << "Cannot read concrete data from memory: " << hexval(virtAddr) << '\n';
            ret.clear();
        }
    } else {
        // XXX: The performance seems fast enough even though I bruteforce it byte by byte,
        // but maybe we can optimize it directly in libs2ecore at some point.
        bool ok = false;
        for (uint64_t i = 0; i < size; i++) {
            if (isSymbolic(virtAddr + i, 1)) {
                // Read the underlying concrete bytes, but don't concretize them.
                ok = m_state->mem()->read(virtAddr + i, &ret[i], VirtualAddress, false);
            } else {
                ok = m_state->mem()->read(virtAddr + i, &ret[i], 1);
            }

            if (!ok) {
                ret[i] = 0;
            }
        }
    }

    return ret;
}

bool Memory::writeSymbolic(uint64_t virtAddr, const ref<Expr> &value) {
    bool success = m_state->mem()->write(virtAddr, value);
    if (!success) {
        log<WARN>() << "Cannot write symbolic data to memory: " << hexval(virtAddr) << '\n';
    }
    return success;
}

bool Memory::writeConcrete(uint64_t virtAddr, const std::vector<uint8_t> &bytes) {
    bool success = m_state->mem()->write(virtAddr, bytes.data(), bytes.size());
    if (!success) {
        log<WARN>() << "Cannot write concrete data to memory: " << hexval(virtAddr) << '\n';
    }
    return success;
}

bool Memory::isMapped(uint64_t virtAddr) const {
    return m_state->mem()->getHostAddress(virtAddr) != -1;
}

std::vector<uint64_t> Memory::search(const std::vector<uint8_t> &needle) const {
    const auto &_vmmap = vmmap();
    std::vector<uint64_t> ret;

    // Iterate over all the mapped memory regions.
    foreach2 (it, _vmmap.begin(), _vmmap.end()) {
        // XXX: Some regions might be unaccessible even though it's mapped,
        // which I believe this is a bug in S2E. Just in case this happens,
        // we'll use `Memory::isMapped()` to scan through every address
        // within this region until an accessible address is found.
        uint64_t start = it.start();
        uint64_t end = it.stop();

        while (!isMapped(start) && start < end) {
            ++start;
        }

        // If the entire region is not accessible, then
        // we don't have to do anything with this region.
        if (start >= end) {
            continue;
        }

        // Read the region concretely into `haystack`,
        // and use kmp algorithm to search all the occurences of `needle`.
        std::vector<uint8_t> haystack = readConcrete(start, end - start, /*concretize=*/false);

        auto its = boost::algorithm::knuth_morris_pratt_search(haystack.begin(),
                                                               haystack.end(),
                                                               needle.begin(),
                                                               needle.end());

        if (its.first == haystack.end() && its.second == haystack.end()) {
            continue;
        }

        ret.push_back((its.first - haystack.begin()) + start);
    }

    return ret;
}

std::map<uint64_t, uint64_t> Memory::getSymbolicMemory() const {
    // first:  The base address of a consecutive symbolic data.
    // second: The size of the symbolic data.
    std::map<uint64_t, uint64_t> ret;

    bool isPreviousByteConstant = true;
    uint64_t base = 0;
    uint64_t size = 0;
    const auto &__vmmap = vmmap();

    foreach2 (it, __vmmap.begin(), __vmmap.end()) {
        for (uint64_t addr = it.start(); addr <= it.stop(); addr++) {
            if (isSymbolic(addr, 1)) {
                // Start of a symbolic memory region.
                if (isPreviousByteConstant) {
                    base = addr;
                    size = 1;
                } else {
                    size++;
                }
                isPreviousByteConstant = false;
            } else {
                // End of a symbolic memory region.
                if (!isPreviousByteConstant) {
                    ret.insert(std::make_pair(base, size));
                }
                isPreviousByteConstant = true;
                continue;
            }
        }
    }

    return ret;
}

const VirtualMemoryMap &Memory::vmmap() const {
    m_vmmap.rebuild(m_state);
    return m_vmmap;
}

void Memory::showMapInfo() const {
    m_vmmap.rebuild(m_state);
    m_vmmap.dump(m_state);
}

Memory &mem(S2EExecutionState *state) {
    return g_crax->mem(state);
}

}  // namespace s2e::plugins::crax

max_stars_repo_name: aesophor/CRAXplusplus

max_issues_repo_name: aesophor/CRAXplusplus

max_forks_repo_name: aesophor/CRAXplusplus


text:
//
// Copyright (c) 2002--2010
// Toon Knapen, Karl Meerbergen, Kresimir Fresl,
// Thomas Klimpel and Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// THIS FILE IS AUTOMATICALLY GENERATED
// PLEASE DO NOT EDIT!
//

#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_TPTRI_HPP
#define BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_TPTRI_HPP

#include <boost/assert.hpp>
#include <boost/numeric/bindings/begin.hpp>
#include <boost/numeric/bindings/diag_tag.hpp>
#include <boost/numeric/bindings/is_mutable.hpp>
#include <boost/numeric/bindings/remove_imaginary.hpp>
#include <boost/numeric/bindings/size.hpp>
#include <boost/numeric/bindings/stride.hpp>
#include <boost/numeric/bindings/uplo_tag.hpp>
#include <boost/numeric/bindings/value_type.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_const.hpp>

//
// The LAPACK-backend for tptri is the netlib-compatible backend.
//
#include <boost/numeric/bindings/lapack/detail/lapack.h>
#include <boost/numeric/bindings/lapack/detail/lapack_option.hpp>

namespace boost {
namespace numeric {
namespace bindings {
namespace lapack {

//
// The detail namespace contains value-type-overloaded functions that
// dispatch to the appropriate back-end LAPACK-routine.
//
namespace detail {

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * float value-type.
//
template< typename UpLo, typename Diag >
inline std::ptrdiff_t tptri( const UpLo, const Diag, const fortran_int_t n,
        float* ap ) {
    fortran_int_t info(0);
    LAPACK_STPTRI( &lapack_option< UpLo >::value, &lapack_option<
            Diag >::value, &n, ap, &info );
    return info;
}

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * double value-type.
//
template< typename UpLo, typename Diag >
inline std::ptrdiff_t tptri( const UpLo, const Diag, const fortran_int_t n,
        double* ap ) {
    fortran_int_t info(0);
    LAPACK_DTPTRI( &lapack_option< UpLo >::value, &lapack_option<
            Diag >::value, &n, ap, &info );
    return info;
}

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * complex<float> value-type.
//
template< typename UpLo, typename Diag >
inline std::ptrdiff_t tptri( const UpLo, const Diag, const fortran_int_t n,
        std::complex<float>* ap ) {
    fortran_int_t info(0);
    LAPACK_CTPTRI( &lapack_option< UpLo >::value, &lapack_option<
            Diag >::value, &n, ap, &info );
    return info;
}

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * complex<double> value-type.
//
template< typename UpLo, typename Diag >
inline std::ptrdiff_t tptri( const UpLo, const Diag, const fortran_int_t n,
        std::complex<double>* ap ) {
    fortran_int_t info(0);
    LAPACK_ZTPTRI( &lapack_option< UpLo >::value, &lapack_option<
            Diag >::value, &n, ap, &info );
    return info;
}

} // namespace detail

//
// Value-type based template class. Use this class if you need a type
// for dispatching to tptri.
//
template< typename Value >
struct tptri_impl {

    typedef Value value_type;
    typedef typename remove_imaginary< Value >::type real_type;

    //
    // Static member function, that
    // * Deduces the required arguments for dispatching to LAPACK, and
    // * Asserts that most arguments make sense.
    //
    template< typename MatrixAP >
    static std::ptrdiff_t invoke( MatrixAP& ap ) {
        namespace bindings = ::boost::numeric::bindings;
        typedef typename result_of::uplo_tag< MatrixAP >::type uplo;
        typedef typename result_of::diag_tag< MatrixAP >::type diag;
        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixAP >::value) );
        BOOST_ASSERT( bindings::size_column(ap) >= 0 );
        return detail::tptri( uplo(), diag(), bindings::size_column(ap),
                bindings::begin_value(ap) );
    }

};

//
// Functions for direct use. These functions are overloaded for temporaries,
// so that wrapped types can still be passed and used for write-access. In
// addition, if applicable, they are overloaded for user-defined workspaces.
// Calls to these functions are passed to the tptri_impl classes. In the
// documentation, most overloads are collapsed to avoid a large number of
// prototypes which are very similar.
//

//
// Overloaded function for tptri. Its overload differs for
//
template< typename MatrixAP >
inline std::ptrdiff_t tptri( MatrixAP& ap ) {
    return tptri_impl< typename bindings::value_type<
            MatrixAP >::type >::invoke( ap );
}

} // namespace lapack
} // namespace bindings
} // namespace numeric
} // namespace boost

#endif

max_stars_repo_name: ljktest/siconos

max_issues_repo_name: ljktest/siconos

max_forks_repo_name: ljktest/siconos


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

#include <boost/test/unit_test.hpp>
#include "armnnOnnxParser/IOnnxParser.hpp"
#include  "ParserPrototxtFixture.hpp"

BOOST_AUTO_TEST_SUITE(OnnxParser)

struct SimpleConv2DFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
    SimpleConv2DFixture()
    {
        m_Prototext = R"(
                   ir_version: 3
                   producer_name:  "CNTK"
                   producer_version:  "2.5.1"
                   domain:  "ai.cntk"
                   model_version: 1
                   graph {
                     name:  "CNTKGraph"
                     input {
                        name: "Input"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 3
                              }
                              dim {
                                dim_value: 3
                              }
                            }
                          }
                        }
                      }
                      input {
                        name: "Weight"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 3
                              }
                              dim {
                                dim_value: 3
                              }
                            }
                          }
                        }
                      }
                      initializer {
                          dims: 1
                          dims: 1
                          dims: 3
                          dims: 3
                          data_type: 1
                          float_data: 2
                          float_data: 1
                          float_data: 0
                          float_data: 6
                          float_data: 2
                          float_data: 1
                          float_data: 4
                          float_data: 1
                          float_data: 2
                          name: "Weight"
                        }
                      node {
                         input: "Input"
                         input: "Weight"
                         output: "Output"
                         name: "Convolution"
                         op_type: "Conv"
                         attribute {
                           name: "kernel_shape"
                           ints: 3
                           ints: 3
                           type: INTS
                         }
                         attribute {
                           name: "strides"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         attribute {
                           name: "auto_pad"
                           s: "VALID"
                           type: STRING
                         }
                         attribute {
                           name: "group"
                           i: 1
                           type: INT
                         }
                         attribute {
                           name: "dilations"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         doc_string: ""
                         domain: ""
                       }
                      output {
                          name: "Output"
                          type {
                             tensor_type {
                               elem_type: 1
                               shape {
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 1
                                   }
                               }
                            }
                        }
                        }
                    }
                   opset_import {
                      version: 7
                    })";
        Setup();
    }
};

struct Conv2DWithBiasesFixture :  public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
    Conv2DWithBiasesFixture() {
        m_Prototext = R"(
                   ir_version: 3
                   producer_name:  "CNTK"
                   producer_version:  "2.5.1"
                   domain:  "ai.cntk"
                   model_version: 1
                   graph {
                     name:  "CNTKGraph"
                     input {
                        name: "Input"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 2
                              }
                              dim {
                                dim_value: 2
                              }
                            }
                          }
                        }
                      }
                      input {
                        name: "Weight"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 2
                              }
                              dim {
                                dim_value: 2
                              }
                            }
                          }
                        }
                      }
                      initializer {
                          dims: 1
                          dims: 1
                          dims: 2
                          dims: 2
                          data_type: 1
                          float_data: 2
                          float_data: 1
                          float_data: 0
                          float_data: 6
                          name: "Weight"
                        }
                        input {
                          name: "Bias"
                          type {
                            tensor_type {
                              elem_type: 1
                              shape {
                                dim {
                                  dim_value: 4
                                }
                              }
                            }
                          }
                        }
                        initializer {
                            dims: 4
                            data_type: 1
                            float_data: 10
                            float_data: 0
                            float_data: 0
                            float_data: 0
                            name: "Bias"
                          }
                      node {
                         input: "Input"
                         input: "Weight"
                         input: "Bias"
                         output: "Output"
                         name: "Convolution"
                         op_type: "Conv"
                         attribute {
                           name: "kernel_shape"
                           ints: 2
                           ints: 2
                           type: INTS
                         }
                         attribute {
                           name: "strides"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         attribute {
                           name: "auto_pad"
                           s: "SAME_UPPER"
                           type: STRING
                         }
                         attribute {
                           name: "group"
                           i: 1
                           type: INT
                         }
                         attribute {
                           name: "dilations"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         doc_string: ""
                         domain: ""
                       }
                      output {
                          name: "Output"
                          type {
                             tensor_type {
                               elem_type: 1
                               shape {
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 2
                                   }
                                   dim {
                                       dim_value: 2
                                   }
                               }
                            }
                        }
                        }
                    }
                   opset_import {
                      version: 7
                    })";
        Setup();
    }
};

struct Conv2DDimReducingFixture :  public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
    Conv2DDimReducingFixture() {
        m_Prototext = R"(
                   ir_version: 3
                   producer_name:  "CNTK"
                   producer_version:  "2.5.1"
                   domain:  "ai.cntk"
                   model_version: 1
                   graph {
                     name:  "CNTKGraph"
                     input {
                        name: "Input"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 3
                              }
                              dim {
                                dim_value: 2
                              }
                              dim {
                                dim_value: 2
                              }
                            }
                          }
                        }
                      }
                      input {
                        name: "Weight"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 2
                              }
                              dim {
                                dim_value: 3
                              }
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 1
                              }
                            }
                          }
                        }
                      }
                      initializer {
                          dims: 2
                          dims: 3
                          dims: 1
                          dims: 1
                          data_type: 1
                          float_data: -1
                          float_data: 2
                          float_data: 0
                          float_data: 1
                          float_data: 0
                          float_data: 0
                          name: "Weight"
                        }
                      node {
                         input: "Input"
                         input: "Weight"
                         output: "Output"
                         name: "Convolution"
                         op_type: "Conv"
                         attribute {
                           name: "kernel_shape"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         attribute {
                           name: "strides"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         attribute {
                           name: "group"
                           i: 1
                           type: INT
                         }
                         attribute {
                           name: "dilations"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         doc_string: ""
                         domain: ""
                       }
                      output {
                          name: "Output"
                          type {
                             tensor_type {
                               elem_type: 1
                               shape {
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 2
                                   }
                                   dim {
                                       dim_value: 2
                                   }
                                   dim {
                                       dim_value: 2
                                   }
                               }
                            }
                        }
                        }
                    }
                   opset_import {
                      version: 7
                    })";
        Setup();
    }
};

struct Conv2DwithDilationFixture : public armnnUtils::ParserPrototxtFixture<armnnOnnxParser::IOnnxParser>
{
    Conv2DwithDilationFixture()
    {
        m_Prototext = R"(
                   ir_version: 3
                   producer_name:  "CNTK"
                   producer_version:  "2.5.1"
                   domain:  "ai.cntk"
                   model_version: 1
                   graph {
                     name:  "CNTKGraph"
                     input {
                        name: "Input"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 6
                              }
                              dim {
                                dim_value: 6
                              }
                            }
                          }
                        }
                      }
                      input {
                        name: "Weight"
                        type {
                          tensor_type {
                            elem_type: 1
                            shape {
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 1
                              }
                              dim {
                                dim_value: 3
                              }
                              dim {
                                dim_value: 3
                              }
                            }
                          }
                        }
                      }
                      initializer {
                          dims: 1
                          dims: 1
                          dims: 3
                          dims: 3
                          data_type: 1
                          float_data: 2
                          float_data: 1
                          float_data: 0
                          float_data: 6
                          float_data: 2
                          float_data: 1
                          float_data: 4
                          float_data: 1
                          float_data: 2
                          name: "Weight"
                        }
                      node {
                         input: "Input"
                         input: "Weight"
                         output: "Output"
                         name: "Convolution"
                         op_type: "Conv"
                         attribute {
                           name: "kernel_shape"
                           ints: 3
                           ints: 3
                           type: INTS
                         }
                         attribute {
                           name: "strides"
                           ints: 1
                           ints: 1
                           type: INTS
                         }
                         attribute {
                           name: "auto_pad"
                           s: "VALID"
                           type: STRING
                         }
                         attribute {
                           name: "group"
                           i: 1
                           type: INT
                         }
                         attribute {
                           name: "dilations"
                           ints: 2
                           ints: 2
                           type: INTS
                         }
                         doc_string: ""
                         domain: ""
                       }
                      output {
                          name: "Output"
                          type {
                             tensor_type {
                               elem_type: 1
                               shape {
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 1
                                   }
                                   dim {
                                       dim_value: 2
                                   }
                                   dim {
                                       dim_value: 2
                                   }
                               }
                            }
                        }
                        }
                    }
                   opset_import {
                      version: 7
                    })";
        Setup();
    }
};

BOOST_FIXTURE_TEST_CASE(ValidConvTest, SimpleConv2DFixture)
{
    RunTest<4>({{"Input", {1.0, 2.0, 3.0,
                           4.0, 5.0, 6.0,
                           7.0, 8.0, 9.0}}},
              {{"Output", {1.0 * 2 + 2.0 * 1 + 3.0 * 0 +
                           4.0 * 6 + 5.0 * 2 + 6.0 * 1 +
                           7.0 * 4 + 8.0 * 1 + 9.0 * 2}}});
}

BOOST_FIXTURE_TEST_CASE(ValidConvWithBiasTest, Conv2DWithBiasesFixture)
{
    RunTest<4>({{"Input", {1.0, 2.0,
                           3.0, 4.0}}},
              {{"Output", {1.0 * 2 + 2.0 * 1 + 3.0 * 0 + 4 * 6 + 10,
                           2.0 * 2 + 0 * 1 + 4.0 * 0 + 0 * 6 + 10,
                           3.0 * 2 + 4.0 * 1 + 0 * 0 + 0 * 6 + 10,
                           4.0 * 2 + 0 * 1 + 0 * 0 + 0 * 6 + 10}}});
}

BOOST_FIXTURE_TEST_CASE(ValidConvDimReducTest, Conv2DDimReducingFixture)
{
    RunTest<4>({{"Input", {1.0, 2.0, 3.0, 4.0, -1, -2, 3, 4, 1 , 1, 1, 1 }}},
              {{"Output", {-1 * 1 + 2 * -1, -1 * 2 + 2 * -2,
                           -1 * 3 + 2 * 3,  -1 * 4 + 2 * 4,
                           1, 2, 3, 4}}});
}

BOOST_FIXTURE_TEST_CASE(ValidConvWithDilationTest, Conv2DwithDilationFixture)
{
    RunTest<4>({{"Input", {1.0, 2.0, 3.0, 4.0, 5.0, 6.0,
                           7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
                           1.0, 2.0, 3.0, 4.0, 5.0, 6.0,
                           7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
                           1.0, 2.0, 3.0, 4.0, 5.0, 6.0,
                           7.0, 8.0, 9.0, 10.0, 11.0, 12.0}}},
               {{"Output", {39.0, 58.0, 153.0, 172.0 }}});
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: tuanhe/armnn

max_issues_repo_name: tuanhe/armnn

max_forks_repo_name: tuanhe/armnn