text:
// Copyright Vladimir Prus 2002-2004.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/program_options/options_description.hpp>
using namespace boost::program_options;

#include <boost/function.hpp>
using namespace boost;

#include <utility>
#include <string>
#include <sstream>
using namespace std;

#include "minitest.hpp"

void test_type()
{
    options_description desc;
    desc.add_options()
        ("foo", value<int>(), "")
        ("bar", value<string>(), "")
        ;

    const typed_value_base* b = dynamic_cast<const typed_value_base*>
        (desc.find("foo", false).semantic().get());
    BOOST_CHECK(b);
    BOOST_CHECK(b->value_type() == typeid(int));

    const typed_value_base* b2 = dynamic_cast<const typed_value_base*>
        (desc.find("bar", false).semantic().get());
    BOOST_CHECK(b2);
    BOOST_CHECK(b2->value_type() == typeid(string));
}

void test_approximation()
{
    options_description desc;
    desc.add_options()
        ("foo", new untyped_value())
        ("fee", new untyped_value())
        ("baz", new untyped_value())
        ("all-chroots", new untyped_value())
        ("all-sessions", new untyped_value())
        ("all", new untyped_value())
        ;

    BOOST_CHECK_EQUAL(desc.find("fo", true).long_name(), "foo");

    BOOST_CHECK_EQUAL(desc.find("all", true).long_name(), "all");
    BOOST_CHECK_EQUAL(desc.find("all-ch", true).long_name(), "all-chroots");

    options_description desc2;
    desc2.add_options()
        ("help", "display this message")
        ("config", value<string>(), "config file name")
        ("config-value", value<string>(), "single config value")
        ;

    BOOST_CHECK_EQUAL(desc2.find("config", true).long_name(), "config");
    BOOST_CHECK_EQUAL(desc2.find("config-value", true).long_name(),
                      "config-value");

//    BOOST_CHECK(desc.count_approx("foo") == 1);
//    set<string> a = desc.approximations("f");
//    BOOST_CHECK(a.size() == 2);
//    BOOST_CHECK(*a.begin() == "fee");
//    BOOST_CHECK(*(++a.begin()) == "foo");
}

void test_formatting()
{
    // Long option descriptions used to crash on MSVC-8.0.
    options_description desc;
    desc.add_options()(
        "test", new untyped_value(),
        "foo foo foo foo foo foo foo foo foo foo foo foo foo foo"
        "foo foo foo foo foo foo foo foo foo foo foo foo foo foo"
        "foo foo foo foo foo foo foo foo foo foo foo foo foo foo"
        "foo foo foo foo foo foo foo foo foo foo foo foo foo foo")
      ("list", new untyped_value(),
         "a list:\n      \t"
             "item1, item2, item3, item4, item5, item6, item7, item8, item9, "
             "item10, item11, item12, item13, item14, item15, item16, item17, item18")
      ("well_formated", new untyped_value(),
                        "As you can see this is a very well formatted option description.\n"
                        "You can do this for example:\n\n"
                        "Values:\n"
                        "  Value1: \tdoes this and that, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla\n"
                        "  Value2: \tdoes something else, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla\n\n"
                        "    This paragraph has a first line indent only, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla")
      ;

    stringstream ss;
    ss << desc;
    BOOST_CHECK_EQUAL(ss.str(),
"  --test arg            foo foo foo foo foo foo foo foo foo foo foo foo foo \n"
"                        foofoo foo foo foo foo foo foo foo foo foo foo foo foo \n"
"                        foofoo foo foo foo foo foo foo foo foo foo foo foo foo \n"
"                        foofoo foo foo foo foo foo foo foo foo foo foo foo foo \n"
"                        foo\n"
"  --list arg            a list:\n"
"                              item1, item2, item3, item4, item5, item6, item7, \n"
"                              item8, item9, item10, item11, item12, item13, \n"
"                              item14, item15, item16, item17, item18\n"
"  --well_formated arg   As you can see this is a very well formatted option \n"
"                        description.\n"
"                        You can do this for example:\n"
"                        \n"
"                        Values:\n"
"                          Value1: does this and that, bla bla bla bla bla bla \n"
"                                  bla bla bla bla bla bla bla bla bla\n"
"                          Value2: does something else, bla bla bla bla bla bla \n"
"                                  bla bla bla bla bla bla bla bla bla\n"
"                        \n"
"                            This paragraph has a first line indent only, bla \n"
"                        bla bla bla bla bla bla bla bla bla bla bla bla bla bla\n"
   );
}

void test_formatting_description_length()
{
    {
        options_description desc("",
                                 options_description::m_default_line_length,
                                 options_description::m_default_line_length / 2U);
        desc.add_options()
            ("an-option-that-sets-the-max", new untyped_value(), // > 40 available for desc
            "this description sits on the same line, but wrapping should still work correctly")
            ("a-long-option-that-would-leave-very-little-space-for-description", new untyped_value(),
            "the description of the long opt, but placed on the next line\n"
            "    \talso ensure that the tabulation works correctly when a"
            " description size has been set");

        stringstream ss;
        ss << desc;
        BOOST_CHECK_EQUAL(ss.str(),
        "  --an-option-that-sets-the-max arg     this description sits on the same line,\n"
        "                                        but wrapping should still work \n"
        "                                        correctly\n"
        "  --a-long-option-that-would-leave-very-little-space-for-description arg\n"
        "                                        the description of the long opt, but \n"
        "                                        placed on the next line\n"
        "                                            also ensure that the tabulation \n"
        "                                            works correctly when a description \n"
        "                                            size has been set\n");
    }
    {
        // the default behaviour reserves 23 (+1 space) characters for the
        // option column; this shows that the min_description_length does not
        // breach that.
        options_description desc("",
                                 options_description::m_default_line_length,
                                 options_description::m_default_line_length - 10U); // leaves < 23 (default option space)
        desc.add_options()
            ("an-option-that-encroaches-description", new untyped_value(),
            "this description should always be placed on the next line, and wrapping should continue as normal");

        stringstream ss;
        ss << desc;
        BOOST_CHECK_EQUAL(ss.str(),
        "  --an-option-that-encroaches-description arg\n"
       //123456789_123456789_
        "          this description should always be placed on the next line, and \n"
        "          wrapping should continue as normal\n");
    }
}

void test_long_default_value()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,c",
         value<string>()->default_value("/usr/local/etc/myprogramXXXXXXXXX/configuration.conf"),
         "the configfile")
       ;

    stringstream ss;
    ss << desc;
    BOOST_CHECK_EQUAL(ss.str(),
"  -c [ --cfgfile ] arg (=/usr/local/etc/myprogramXXXXXXXXX/configuration.conf)\n"
"                                        the configfile\n"
   );
}

void test_word_wrapping()
{
   options_description desc("Supported options");
   desc.add_options()
      ("help",    "this is a sufficiently long text to require word-wrapping")
      ("prefix", value<string>()->default_value("/h/proj/tmp/dispatch"), "root path of the dispatch installation")
      ("opt1",    "this_is_a_sufficiently_long_text_to_require_word-wrapping_but_cannot_be_wrapped")
      ("opt2",    "this_is_a_sufficiently long_text_to_require_word-wrapping")
      ("opt3",    "this_is_a sufficiently_long_text_to_require_word-wrapping_but_will_not_be_wrapped")
      ;
    stringstream ss;
    ss << desc;
    BOOST_CHECK_EQUAL(ss.str(),
"Supported options:\n"
"  --help                               this is a sufficiently long text to \n"
"                                       require word-wrapping\n"
"  --prefix arg (=/h/proj/tmp/dispatch) root path of the dispatch installation\n"
"  --opt1                               this_is_a_sufficiently_long_text_to_requ\n"
"                                       ire_word-wrapping_but_cannot_be_wrapped\n"
"  --opt2                               this_is_a_sufficiently \n"
"                                       long_text_to_require_word-wrapping\n"
"  --opt3                               this_is_a sufficiently_long_text_to_requ\n"
"                                       ire_word-wrapping_but_will_not_be_wrappe\n"
"                                       d\n"
   );
}

void test_default_values()
{
   options_description desc("Supported options");
   desc.add_options()
      ("maxlength", value<double>()->default_value(.1, "0.1"), "Maximum edge length to keep.")
      ;
   stringstream ss;
   ss << desc;
   BOOST_CHECK_EQUAL(ss.str(),
"Supported options:\n"
"  --maxlength arg (=0.1) Maximum edge length to keep.\n"
   );
}

void test_value_name()
{
    options_description desc("Supported options");
    desc.add_options()
        ("include", value<string>()->value_name("directory"), "Search for headers in 'directory'.")
        ;

    stringstream ss;
    ss << desc;
   BOOST_CHECK_EQUAL(ss.str(),
"Supported options:\n"
"  --include directory   Search for headers in 'directory'.\n"
   );
}

int main(int, char* [])
{
    test_type();
    test_approximation();
    test_formatting();
    test_formatting_description_length();
    test_long_default_value();
    test_word_wrapping();
    test_default_values();
    test_value_name();
    return 0;
}


text:
#include "common/file_read.hpp"

#include <boost/iostreams/categories.hpp>   // input_filter_tag
#include <boost/iostreams/filter/gzip.hpp>  // decompressor
#include <boost/iostreams/operations.hpp>   // get, WOULD_BLOCK

struct fasta_to_upper_filter {
  typedef char char_type;
  typedef input_filter_tag category;
  bool newline{true}, header{false};

  template <typename Source>
  int get(Source &src) {
    int c = boost::iostreams::get(src);
    if (newline) {
      (unsigned char)c == '>' ? header = true : header = false;
      newline = false;
    }
    if ((unsigned char)c == '\n') {
      newline = true;
      header = false;
    }
    if (c == EOF || header) return c;
    return std::toupper((unsigned char)c);
  }
};

filtering_istreambuf &input_fasta(filtering_istreambuf &input_filter,
                                  std::istream &input_stream, bool gzipped) {
  input_filter.push(fasta_to_upper_filter());
  if (gzipped) {
    input_filter.push(gzip_decompressor());
  }
  input_filter.push(input_stream);
  return input_filter;
}

ext: cpp

max_stars_repo_name: bricoletc/gramtools

max_issues_repo_name: bricoletc/gramtools

max_forks_repo_name: bricoletc/gramtools


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"
#include "TestHealthClient.h"
#include "ComTestStatefulServicePartition.h"
#include "ComTestOperation.h"
#include "ComTestStateProvider.h"
#include "ComProxyTestReplicator.h"
#include "ComReplicator.h"
#include "TestChangeRole.h"
#include "testFabricAsyncCallbackHelper.h"

#include <ktl.h>
#include <KTpl.h>
#include <KComAdapter.h>

namespace ReplicationUnitTest
{
    using ::_delete;
}

namespace ReplicationUnitTest
{
    using namespace Common;
    using namespace std;
    using namespace Reliability::ReplicationComponent;

    static Common::StringLiteral const PerfTestSource("PerfTest");

    class OperationData
        : public IFabricOperationData
        , Common::ComUnknownBase
    {
        DENY_COPY_ASSIGNMENT(OperationData)
            COM_INTERFACE_LIST1(
                FabricOperationData,
                IID_IFabricOperationData,
                IFabricOperationData)
    public:

        OperationData()
            : value_()
        {
        }

        OperationData(int valueSize)
            : value_(valueSize)
        {
            for (int i = 0; i < value_; i++)
            {
                buffer_.push_back(static_cast<byte>(0));
            }
        }

        HRESULT STDMETHODCALLTYPE GetData(
            /*[out]*/ ULONG * count,
            /*[out, retval]*/ FABRIC_OPERATION_DATA_BUFFER const ** buffers)
        {
            *count = 1;

            replicaBuffer_.BufferSize = static_cast<ULONG>(value_);
            replicaBuffer_.Buffer = buffer_.data();

            *buffers = &replicaBuffer_;

            return S_OK;
        }

    private:
        int value_;
        std::vector<byte> buffer_;
        FABRIC_OPERATION_DATA_BUFFER replicaBuffer_;
    };

    class ComProxyStateReplicator final
        : public KObject<ComProxyStateReplicator>
        , public KShared<ComProxyStateReplicator>
    {
        K_FORCE_SHARED(ComProxyStateReplicator)

    public:

        static NTSTATUS Create(
            __in Common::ComPointer<IFabricStateReplicator> & v1StateReplicator,
            __in KAllocator & allocator,
            __out ComProxyStateReplicator::SPtr & comProxyStateReplicator);

        ktl::Awaitable<void> ReplicateAsync(
            LONG size);
    private:

        ComProxyStateReplicator(
            __in Common::ComPointer<IFabricStateReplicator> & v1StateReplicator);

        class AsyncReplicateContextBase :
            public Ktl::Com::FabricAsyncContextBase
        {
        };

        //
        // Replicate async operation
        //
        class AsyncReplicateContext
            : public Ktl::Com::AsyncCallOutAdapter<AsyncReplicateContextBase>
        {
            friend ComProxyStateReplicator;

            K_FORCE_SHARED(AsyncReplicateContext)

        public:

            ktl::Awaitable<void> ReplicateAsync(
                Common::ComPointer<IFabricOperationData> comOperationData);

        protected:

            HRESULT OnEnd(__in IFabricAsyncOperationContext & context);

        private:

            FABRIC_SEQUENCE_NUMBER resultSequenceNumber_;
            ComProxyStateReplicator::SPtr parent_;
            ktl::AwaitableCompletionSource<void>::SPtr task_;
        };

        Common::ComPointer<IFabricStateReplicator> comStateReplicator_;
    };

    ComProxyStateReplicator::ComProxyStateReplicator(
        __in ComPointer<IFabricStateReplicator> & v1StateReplicator)
        : KObject()
        , KShared()
        , comStateReplicator_(v1StateReplicator)
    {
    }

    ComProxyStateReplicator::~ComProxyStateReplicator()
    {
    }

    NTSTATUS ComProxyStateReplicator::Create(
        __in ComPointer<IFabricStateReplicator> & v1StateReplicator,
        __in KAllocator & allocator,
        __out ComProxyStateReplicator::SPtr & comProxyStateReplicator)
    {
        ComProxyStateReplicator * pointer = _new('ascd', allocator) ComProxyStateReplicator(v1StateReplicator);

        if (pointer == nullptr)
        {
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        comProxyStateReplicator = pointer;

        return STATUS_SUCCESS;
    }

    ktl::Awaitable<void> ComProxyStateReplicator::ReplicateAsync(
        __in LONG size)
    {
        AsyncReplicateContext::SPtr context = _new('abcd', GetThisAllocator()) AsyncReplicateContext();
        context->parent_ = this;

        ComPointer<IFabricOperationData> operationData = make_com<OperationData, IFabricOperationData>(size);

        co_await context->ReplicateAsync(
            operationData);

        co_return;
    }

    //
    // Callout adapter to invoke replicate API on v1 replicator
    //
    ComProxyStateReplicator::AsyncReplicateContext::AsyncReplicateContext()
        : resultSequenceNumber_(FABRIC_INVALID_SEQUENCE_NUMBER)
        , parent_()
        , task_()
    {
    }

    ComProxyStateReplicator::AsyncReplicateContext::~AsyncReplicateContext()
    {
    }

    ktl::Awaitable<void> ComProxyStateReplicator::AsyncReplicateContext::ReplicateAsync(
        __in Common::ComPointer<IFabricOperationData> comOperationData)
    {
        FABRIC_SEQUENCE_NUMBER logicalSequenceNumber = FABRIC_INVALID_SEQUENCE_NUMBER;

        //
        // The following implementation ensures that when the replication operations fails synchronously with
        // an error, this error is returned immediatly, instead of starting the underlying callout adapter.
        //
        // - begin fails: returns error, async context is not started
        // - begin succeeds:
        //    - completed synchronously:
        //       - end fails: returns error, async context is not started
        //       - end succeeds: returns success, async context not started
        //    - not completed synchronously:
        //       - when the Invoke is seen and the OnStart is seen, call end and complete the async context
        //
        ComPointer<IFabricAsyncOperationContext> context;

        HRESULT hr = parent_->comStateReplicator_->BeginReplicate(
            comOperationData.GetRawPointer(),
            this,
            &logicalSequenceNumber,
            context.InitializationAddress());

        if (context->CompletedSynchronously())
        {
            hr = parent_->comStateReplicator_->EndReplicate(
                context.GetRawPointer(),
                &resultSequenceNumber_); // Use the reference input variable only on beginreplicate

            co_return;
        }
        else
        {
            OnComOperationStarted(
                *context.GetRawPointer(),
                nullptr,
                nullptr);
        }

        ktl::AwaitableCompletionSource<void>::Create(GetThisAllocator(), 'abcf', task_);
        co_await task_->GetAwaitable();
        co_return;
    }

    HRESULT ComProxyStateReplicator::AsyncReplicateContext::OnEnd(__in IFabricAsyncOperationContext & context)
    {
        ASSERT_IFNOT(
            context.CompletedSynchronously() == FALSE,
            "Replicate Operation callback must only be invoked when not completed synchronously");

        HRESULT hr = parent_->comStateReplicator_->EndReplicate(
            &context,
            &resultSequenceNumber_);

        task_->Set();
        return hr;
    }

    class ComAsyncOperationCallbackHelper
        : public IFabricAsyncOperationCallback
        , private Common::ComUnknownBase
    {
        COM_INTERFACE_LIST1(ComAsyncOperationCallbackHelper, IID_IFabricAsyncOperationCallback, IFabricAsyncOperationCallback);

    public:
        ComAsyncOperationCallbackHelper(std::function<void(IFabricAsyncOperationContext *)> const & callback)
            : callback_(callback)
        {
        }

        void STDMETHODCALLTYPE Invoke(IFabricAsyncOperationContext * aoc)
        {
            callback_(aoc);
        }

        static BOOLEAN GetCompletedSynchronously(IFabricAsyncOperationContext * context)
        {
            return context->CompletedSynchronously();
        }
    private:
        std::function<void(IFabricAsyncOperationContext *)> callback_;
    };

    class ServiceEntry
    {
    public:
        ServiceEntry(__int64 key)
            : key_(key)
        {
        }

        __declspec(property(get = get_Key)) __int64 Key;
        __int64 get_Key() const
        {
            return key_;
        }

        HRESULT BeginReplicate(
            Common::ComPointer<IFabricStateReplicator> & replicator,
            Common::ComPointer<ComAsyncOperationCallbackHelper> & callback,
            Common::ComPointer<IFabricAsyncOperationContext> & context,
            FABRIC_SEQUENCE_NUMBER & newVersion,
            int newValueSize)
        {
            ComPointer<OperationData> operationData = make_com<OperationData>(newValueSize);

            HRESULT hr = replicator->BeginReplicate(
                operationData.GetRawPointer(),
                callback.GetRawPointer(),
                &newVersion,
                context.InitializationAddress());

            return hr;
        }

    private:
        __int64 const key_;
        static FABRIC_SEQUENCE_NUMBER const InvalidVersion = -1;
    };

    class TestReplicatePerf
    {
    protected:
        TestReplicatePerf() { }

        class DummyRoot : public Common::ComponentRoot
        {
        };
    public:
        static Common::ComponentRoot const & GetRoot();
    };

    namespace {
        class ReplicatorTestWrapper
        {
        public:
            ReplicatorTestWrapper()
                : factory_(TestReplicatePerf::GetRoot())
                , primary_()
            {
                VERIFY_IS_TRUE(factory_.Open(L"0").IsSuccess(), L"ComReplicatorFactory opened");

                auto partition = new ComTestStatefulServicePartition(Common::Guid::NewGuid());
                IReplicatorHealthClientSPtr temp;
                auto hr = factory_.CreateReplicator(
                    0LL,
                    partition,
                    new ComTestStateProvider(0, -1, TestReplicatePerf::GetRoot()),
                    nullptr,
                    false,
                    move(temp),
                    stateReplicator_.InitializationAddress());

                ASSERT_IFNOT(
                    SUCCEEDED(hr),
                    "Create replicator failed with {0:x}",
                    hr);

                IFabricPrimaryReplicator *replicatorObj;
                hr = stateReplicator_->QueryInterface(
                    IID_IFabricPrimaryReplicator,
                    reinterpret_cast<void**>(&replicatorObj));

                ASSERT_IFNOT(
                    SUCCEEDED(hr),
                    "Query for IID_IFabricPrimaryReplicator failed with {0:x}",
                    hr);

                primary_.SetAndAddRef(replicatorObj);

                Common::AutoResetEvent event;
                ComPointer<ComAsyncOperationCallbackHelper> openCallback = make_com<ComAsyncOperationCallbackHelper>(
                    [&](IFabricAsyncOperationContext * context)
                {
                    ComPointer<IFabricStringResult> stringResult;
                    replicatorObj->EndOpen(context, stringResult.InitializationAddress());
                    event.Set();
                });

                ComPointer<IFabricAsyncOperationContext> openContext;
                hr = replicatorObj->BeginOpen(openCallback.GetRawPointer(), openContext.InitializationAddress());
                event.Wait();

                ComPointer<ComAsyncOperationCallbackHelper> crCallback = make_com<ComAsyncOperationCallbackHelper>(
                    [&](IFabricAsyncOperationContext * context)
                {
                    replicatorObj->EndChangeRole(context);
                    event.Set();
                });

                ComPointer<IFabricAsyncOperationContext> crContext;
                FABRIC_EPOCH epoch;
                epoch.DataLossNumber = 1;
                epoch.ConfigurationNumber = 122;
                epoch.Reserved = NULL;
                hr = replicatorObj->BeginChangeRole(&epoch, FABRIC_REPLICA_ROLE_PRIMARY, crCallback.GetRawPointer(), crContext.InitializationAddress());
                event.Wait();
            }

            ~ReplicatorTestWrapper()
            {
                VERIFY_IS_TRUE(factory_.Close().IsSuccess(), L"ComReplicatorFactory closed");
            }

            Common::ComPointer<IFabricStateReplicator> GetReplicator() const
            {
                return stateReplicator_;
            }

        private:

            ComReplicatorFactory factory_;
            ComPointer<IFabricStateReplicator> stateReplicator_;
            ComPointer<IFabricPrimaryReplicator> primary_;
        };
    }

    class Test
    {
    public:
        static void Execute(
            LONG maxOutstanding,
            LONG dataSize,
            LONG numberOfOperations,
            Common::ComPointer<IFabricStateReplicator> const & replicator)
        {
            Test t(maxOutstanding, dataSize, numberOfOperations, replicator);
            return t.Run();
        }

        static ktl::Awaitable<void> ExecuteAsync(
            LONG maxOutstanding,
            LONG dataSize,
            LONG numberOfOperations,
            KAllocator & allocator,
            Common::ComPointer<IFabricStateReplicator> const & replicator,
            ComProxyStateReplicator & proxyReplicator)
        {
            Test t(maxOutstanding, dataSize, numberOfOperations, replicator);
            co_await t.RunAsync(allocator, proxyReplicator);
            co_return;
        }

    private:
        Test(
            LONG maxOutstanding,
            LONG dataSize,
            LONG totalOperations,
            Common::ComPointer<IFabricStateReplicator> const & replicator)
            : maxOutstanding_(maxOutstanding)
            , dataSize_(dataSize)
            , totalOperations_(totalOperations)
            , numberOfOperations_(0)
            , inflightOperationCount_(0)
            , replicator_(replicator)
            , data_()
        {
            for (LONG i = 0; i < maxOutstanding; i++)
            {
                data_.push_back(ServiceEntry(i));
            }
        }

        static void StartReplicatingIfNeeded(ServiceEntry & entry, Test & test)
        {
            auto opCount = test.numberOfOperations_.load();

            if (opCount < test.totalOperations_)
            {
                ReplicateServiceEntry(entry, test);
            }
            else
            {
                Trace.WriteInfo(
                    PerfTestSource,
                    "ServiceEntry {0} stopped replicating",
                    entry.Key);
            }
        }

        static ktl::Awaitable<void> ReplicateServiceEntryAsync(
            ServiceEntry & entry,
            Test & test,
            ComProxyStateReplicator & replicator)
        {
            test.inflightOperationCount_ += 1;
            co_await replicator.ReplicateAsync(test.dataSize_);
            test.inflightOperationCount_ -= 1;

            test.numberOfOperations_ += 1;

            StartReplicatingIfNeeded(entry, test);
        }

        static ktl::Task StartReplicatingIfNeededAsync(
            ServiceEntry & entry,
            Test & test,
            ComProxyStateReplicator & replicator)
        {
            auto opCount = test.numberOfOperations_.load();

            if (opCount < test.totalOperations_)
            {
                co_await ReplicateServiceEntryAsync(entry, test, replicator);
            }
            else
            {
                Trace.WriteInfo(
                    PerfTestSource,
                    "ServiceEntry {0} stopped replicating",
                    entry.Key);
            }
        }

        static void ReplicateServiceEntry(ServiceEntry & entry, Test & test)
        {
            test.inflightOperationCount_ += 1;

            BOOLEAN completedSync = false;

            ComPointer<ComAsyncOperationCallbackHelper> callback = make_com<ComAsyncOperationCallbackHelper>(
                [&entry, &test](IFabricAsyncOperationContext * context)
            {
                BOOLEAN inCallbackCompletedSynchronously = ComAsyncOperationCallbackHelper::GetCompletedSynchronously(context);
                if (!inCallbackCompletedSynchronously)
                {
                    test.inflightOperationCount_ -= 1;
                    FABRIC_SEQUENCE_NUMBER lsn;

                    auto hr = test.replicator_->EndReplicate(context, &lsn);
                    if (hr == S_OK)
                    {
                        test.numberOfOperations_ += 1;
                    }

                    StartReplicatingIfNeeded(entry, test);
                }
            });

            FABRIC_SEQUENCE_NUMBER newLsn;
            ComPointer<IFabricAsyncOperationContext> beginContext;
            HRESULT hr = entry.BeginReplicate(
                test.replicator_,
                callback,
                beginContext,
                newLsn,
                test.dataSize_);

            if (hr != S_OK)
            {
                test.inflightOperationCount_ -= 1;

                Threadpool::Post(
                    [&entry, &test]
                {
                    StartReplicatingIfNeeded(entry, test);
                });

                return;
            }

            completedSync = ComAsyncOperationCallbackHelper::GetCompletedSynchronously(beginContext.GetRawPointer());

            if (completedSync)
            {
                --test.inflightOperationCount_;

                FABRIC_SEQUENCE_NUMBER lsn;
                hr = test.replicator_->EndReplicate(beginContext.GetRawPointer(), &lsn);
                if (hr == S_OK)
                {
                    ++test.numberOfOperations_;
                }

                StartReplicatingIfNeeded(entry, test);
            }
        }

        ktl::Awaitable<void> RunAsync(
            KAllocator & allocator,
            ComProxyStateReplicator & replicator)
        {
            double opsPerMillisecond = 0;
            double opsPerSecond = 0;
            Stopwatch watch;
            watch.Start();
            ComProxyStateReplicator::SPtr re = &replicator;

            for (LONG i = 0; i < maxOutstanding_; i++)
            {
                auto ref = &data_[i];

                    Trace.WriteInfo(
                        PerfTestSource,
                        "ServiceEntry {0} starting to replicate",
                        ref->Key);

                    StartReplicatingIfNeededAsync(*ref, *this, *re);
            }

            for (;;)
            {
                KTimer::SPtr timer;
                KTimer::Create(timer, allocator, 'abcd');
                co_await timer->StartTimerAsync(1000, nullptr);

                auto opCount = numberOfOperations_.load();
                auto inflightOpCount = inflightOperationCount_.load();
                if (opCount >= totalOperations_ &&
                    inflightOpCount == 0)
                {
                    break;
                }

                opsPerMillisecond = (double)numberOfOperations_.load() / (double)watch.ElapsedMilliseconds;
                opsPerSecond = 1000 * opsPerMillisecond;

                Trace.WriteInfo(
                    PerfTestSource,
                    "Ops Completed = {0}. Inflight ops = {1}. Waiting until {2}. OpsPerSecond = {3}",
                    opCount,
                    inflightOpCount,
                    totalOperations_,
                    opsPerSecond);
            }

            watch.Stop();

            Trace.WriteInfo(
                PerfTestSource,
                "Time taken {0}; Operations Per Second = {1}; Operations per Millisecond = {2}; numberOfOperations_.load()  = {3}; ElapsedMilliseconds = {4}",
                watch.Elapsed.ToString(),
                opsPerSecond,
                opsPerMillisecond,
                numberOfOperations_.load(),
                watch.ElapsedMilliseconds);

            co_return;
        }

        void Run()
        {
            double opsPerMillisecond = 0;
            double opsPerSecond = 0;
            Stopwatch watch;
            watch.Start();

            for (LONG i = 0; i < maxOutstanding_; i++)
            {
                auto ref = &data_[i];

                Threadpool::Post(
                    [ref, this]
                {
                    Trace.WriteInfo(
                        PerfTestSource,
                        "ServiceEntry {0} starting to replicate",
                        ref->Key);

                    StartReplicatingIfNeeded(*ref, *this);
                });
            }

            for (;;)
            {
                Sleep(1000);

                auto opCount = numberOfOperations_.load();
                auto inflightOpCount = inflightOperationCount_.load();
                if (opCount >= totalOperations_ &&
                    inflightOpCount == 0)
                {
                    break;
                }

                opsPerMillisecond = (double)numberOfOperations_.load() / (double)watch.ElapsedMilliseconds;
                opsPerSecond = 1000 * opsPerMillisecond;

                Trace.WriteInfo(
                    PerfTestSource,
                    "Ops Completed = {0}. Inflight ops = {1}. Waiting until {2}. OpsPerSecond = {3}",
                    opCount,
                    inflightOpCount,
                    totalOperations_,
                    opsPerSecond);
            }

            watch.Stop();

            Trace.WriteInfo(
                PerfTestSource,
                "Time taken {0}; Operations Per Second = {1}; Operations per Millisecond = {2}; numberOfOperations_.load()  = {3}; ElapsedMilliseconds = {4}",
                watch.Elapsed.ToString(),
                opsPerSecond,
                opsPerMillisecond,
                numberOfOperations_.load(),
                watch.ElapsedMilliseconds);
        }

        LONG const maxOutstanding_;
        LONG const dataSize_;
        LONG const totalOperations_;

        Common::atomic_long numberOfOperations_;
        Common::atomic_long inflightOperationCount_;
        Common::ComPointer<IFabricStateReplicator> replicator_;
        std::vector<ServiceEntry> data_;
    };

    LONG outstanding = 1000;
    LONG size = 128;
    LONG max = 2000000;

    /***********************************
    * TestReplicatePerf methods
    **********************************/
    Common::ComponentRoot const & TestReplicatePerf::GetRoot()
    {
        static std::shared_ptr<DummyRoot> root = std::make_shared<DummyRoot>();
        return *root;
    }

    BOOST_FIXTURE_TEST_SUITE(TestReplicatePerfSuite,TestReplicatePerf)

    BOOST_AUTO_TEST_CASE(BeginReplicatePerf)
    {
        ReplicatorTestWrapper wrapper;

        Test::Execute(
            outstanding,
            size,
            max,
            wrapper.GetReplicator());
    }

    BOOST_AUTO_TEST_CASE(BeginReplicatePerfKtl)
    {
        ReplicatorTestWrapper wrapper;
        KtlSystem* underlyingSystem;
        NTSTATUS status = KtlSystem::Initialize(FALSE, &underlyingSystem);
        CODING_ERROR_ASSERT(NT_SUCCESS(status));
        underlyingSystem->SetStrictAllocationChecks(TRUE);
        KAllocator& allocator = underlyingSystem->NonPagedAllocator();
        underlyingSystem->SetDefaultSystemThreadPoolUsage(FALSE);

        ComProxyStateReplicator::SPtr proxy;
        ComPointer<IFabricStateReplicator> replicator = wrapper.GetReplicator();
        ComProxyStateReplicator::Create(replicator, allocator, proxy);

        SyncAwait(Test::ExecuteAsync(
            outstanding,
            size,
            max,
            allocator,
            replicator,
            *proxy));
    }
    BOOST_AUTO_TEST_SUITE_END()
}


text:
#ifndef INCLUDE_ACKWARD_CORE_EXCEPTIONS_HPP
#define INCLUDE_ACKWARD_CORE_EXCEPTIONS_HPP

/** C++ counterparts to the standard Python exceptions.
 */

#include <Python.h>

#include <exception>

#include <boost/exception/all.hpp>

namespace boost { namespace python { class tuple; } }

namespace ackward {
namespace core {

/** The base for all ackward exceptions. */
class Exception : public virtual boost::exception,
                  public virtual std::exception
{};

/* A collection of C++ analogues for the standard Python exceptions.
 */

class AttributeError : public Exception {};
class ImportError : public Exception {};
class IndexError : public Exception {};
class IOError : public Exception {};
class KeyError : public Exception {};
class TypeError : public Exception {};
class ReferenceError : public Exception {};
class ValueError : public Exception {};
class StopIteration : public Exception {};

}}

#endif

ext: hpp

max_stars_repo_name: abingham/ackward

max_issues_repo_name: abingham/ackward

max_forks_repo_name: abingham/ackward


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_ARCH_COMMON_SCALAR_FUNCTION_DIVTRUNC_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_DIVTRUNC_HPP_INCLUDED

#include <boost/simd/function/definition/trunc.hpp>
#include <boost/simd/constant/valmax.hpp>
#include <boost/simd/constant/valmin.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/trunc.hpp>
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/config.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  BOOST_DISPATCH_OVERLOAD ( div_
                          , (typename A0)
                          , bd::cpu_
                          , bs::tag::trunc_
                          , bd::scalar_< bd::signed_<A0> >
                          , bd::scalar_< bd::signed_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( bd::functor<bs::tag::trunc_> const&
                                    , A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      if (!a0) return  Zero<A0>();
      if(a1)
      {
        return a0/a1;
      }
      else
        return ((a0>0) ? Valmax<A0>() : Valmin<A0>());

    }
  };

  BOOST_DISPATCH_OVERLOAD ( div_
                          , (typename A0)
                          , bd::cpu_
                          , bs::tag::trunc_
                          , bd::scalar_< bd::unsigned_<A0> >
                          , bd::scalar_< bd::unsigned_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( bd::functor<bs::tag::trunc_> const&
                                    , A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      if (!a0) return  Zero<A0>();
      if(a1)
      {
        return a0/a1;
      }
      else
        return Valmax<A0>();

    }
  };

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4723) // potential divide by 0
#endif

  BOOST_DISPATCH_OVERLOAD ( div_
                          , (typename A0)
                          , bd::cpu_
                          , bs::tag::trunc_
                          , bd::scalar_< bd::floating_<A0> >
                          , bd::scalar_< bd::floating_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( bd::functor<bs::tag::trunc_> const&
                                    , A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      return trunc(a0/a1);
    }
  };

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include <boost/program_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/log/trivial.hpp>

#include "common/cmd_helpers.h"

#include "helpers.h"
#include "condat_denoise.h"

namespace bpo = boost::program_options;
namespace ublas = boost::numeric::ublas;

namespace
{
    bpo::options_description initializeOptionsDescription()
    {
        using namespace std;

        bpo::options_description desc("Options");
        desc.add_options()
                ("help,h", "Print help message")
                ("input", bpo::value<string>(),
                        "Filename of a matrix market vector file "
                        "containing the noisiy input data set")
                ("output", bpo::value<string>()->default_value("-"),
                        "Filename of the matrix market vector file "
                        "the denoised data should be written to")
                ("lambda", bpo::value<double>(),
                        "Lambda coefficient used as regularizer in"
                        "the total-variation denoising problem")
                ("debug,d", "Turn on debug output if flag is set");

        return desc;
    }

    bool tryParseProgramOptions(const bpo::options_description& desc,
                                const int argc,
                                const char *argv[],
                                bpo::variables_map& vm)
    {
        using namespace std;
        try {
            bpo::positional_options_description ppos;
            ppos.add("input", 1);
            ppos.add("output", 2);

            bpo::store(bpo::command_line_parser(argc, argv)
                        .options(desc)
                        .positional(ppos)
                        .run(), vm);
            bpo::notify(vm);

            if (cmd::isHelpRequest(desc, vm)) {
                return cmd::SUCCESS;
            }

            bool is_valid = true;
            if (! vm.count("input")) {
                BOOST_LOG_TRIVIAL(error) << "'input' argument is required";
                is_valid = false;
            }

            if (! vm.count("output")) {
                BOOST_LOG_TRIVIAL(error) << "'output' argument is required";
                is_valid = false;
            }

            if (! vm.count("lambda")) {
                BOOST_LOG_TRIVIAL(error) << "'lambda' argument is required";
                is_valid = false;
            }

            return is_valid;
        }
        catch (bpo::error& e) {
            BOOST_LOG_TRIVIAL(error) << e.what();
            BOOST_LOG_TRIVIAL(error) << desc;
            return false;
        }
    }

    int runProgram(const bpo::options_description& desc,
                   const bpo::variables_map &vm)
    {
        using namespace std;
        typedef boost::numeric::ublas::vector<double> VectorType;

	auto lambda = vm["lambda"].as<double>();

        VectorType input, output;
        if (! cmd::loadInputVectorAndAdjustOutputSize(vm, input, output))
            return cmd::ERROR_UNHANDLED_EXCEPTION;

        TV1D_denoise(input, output, lambda);

        if (! cmd::saveOutputVector(vm, output))
            return cmd::ERROR_UNHANDLED_EXCEPTION;

        return cmd::SUCCESS;
    }
}

int main(const int argc, const char *argv[])
{
    using namespace std;

    cmd::configureLogging();
    auto desc = initializeOptionsDescription();

    try
    {
        // Define and parse the program options
        bpo::variables_map vm;
        if (! tryParseProgramOptions(desc, argc, argv, vm)) {
            return cmd::ERROR_IN_COMMAND_LINE;
        }

        return runProgram(desc, vm);
    }
    catch(std::exception& e)
    {

        cerr << "Unhandled Exception reached the top of main: "
                << e.what() << ", application will now exit" << endl;

        return cmd::ERROR_UNHANDLED_EXCEPTION;
    }
}

max_stars_repo_name: qubit-ulm/pwcs

max_issues_repo_name: qubit-ulm/pwcs

max_forks_repo_name: qubit-ulm/pwcs


text:
//  Copyright (c) 2013 Agustin Berge
//
//  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_UTIL_INVOKE_FUSED_HPP
#define HPX_UTIL_INVOKE_FUSED_HPP

#include <hpx/config.hpp>
#include <hpx/util/decay.hpp>
#include <hpx/util/invoke.hpp>
#include <hpx/util/move.hpp>
#include <hpx/util/tuple.hpp>
#include <hpx/util/detail/pack.hpp>
#include <hpx/util/detail/qualify_as.hpp>

#include <boost/type_traits/add_const.hpp>

namespace hpx { namespace util
{
    namespace detail
    {
        template <typename Indices, typename F>
        struct invoke_fused_result_of_impl;

        template <std::size_t ...Is, typename F, typename Tuple>
        struct invoke_fused_result_of_impl<
            detail::pack_c<std::size_t, Is...>, F(Tuple)
        > : invoke_result_of<
                F(typename detail::qualify_as<typename util::tuple_element<
                        Is, typename util::decay<Tuple>::type
                    >::type, Tuple>::type...)
            >
        {};
    }

    template <typename F>
    struct invoke_fused_result_of;

    template <typename F, typename Tuple>
    struct invoke_fused_result_of<F(Tuple)>
      : detail::invoke_fused_result_of_impl<
            typename detail::make_index_pack<
                util::tuple_size<typename util::decay<Tuple>::type>::value
            >::type
          , F(Tuple)
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    namespace detail
    {
        template <typename R, std::size_t ...Is, typename F, typename Tuple>
        BOOST_FORCEINLINE
        R
        invoke_fused_impl(detail::pack_c<std::size_t, Is...>,
            F && f, Tuple const& args)
        {
            return invoke_r<R>(
                std::forward<F>(f), util::get<Is>(args)...);
        }

        template <typename R, std::size_t ...Is, typename F, typename Tuple>
        BOOST_FORCEINLINE
        R
        invoke_fused_impl(detail::pack_c<std::size_t, Is...>, //-V659
            F && f, Tuple&& args)
        {
            return invoke_r<R>(
                std::forward<F>(f), util::get<Is>(std::move(args))...);
        }
    }

    template <typename R, typename F, typename ...Ts>
    BOOST_FORCEINLINE
    R
    invoke_fused_r(F && f, util::tuple<Ts...> const& args)
    {
        return detail::invoke_fused_impl<R>(
            typename detail::make_index_pack<sizeof...(Ts)>::type(),
            std::forward<F>(f), args);
    }

    template <typename R, typename F, typename ...Ts>
    BOOST_FORCEINLINE
    R
    invoke_fused_r(F && f, util::tuple<Ts...>&& args) //-V659
    {
        return detail::invoke_fused_impl<R>(
            typename detail::make_index_pack<sizeof...(Ts)>::type(),
            std::forward<F>(f), std::move(args));
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename F, typename ...Ts>
    BOOST_FORCEINLINE
    typename invoke_result_of<F(typename boost::add_const<Ts>::type...)>::type
    invoke_fused(F && f, util::tuple<Ts...> const& args)
    {
        typedef typename invoke_result_of<
            F(typename boost::add_const<Ts>::type...)
        >::type result_type;

        return detail::invoke_fused_impl<result_type>(
            typename detail::make_index_pack<sizeof...(Ts)>::type(),
            std::forward<F>(f), args);
    }

    template <typename F, typename ...Ts>
    BOOST_FORCEINLINE
    typename invoke_result_of<F(Ts...)>::type
    invoke_fused(F && f, util::tuple<Ts...>&& args) //-V659
    {
        typedef typename invoke_result_of<F(Ts...)>::type result_type;

        return detail::invoke_fused_impl<result_type>(
            typename detail::make_index_pack<sizeof...(Ts)>::type(),
            std::forward<F>(f), std::move(args));
    }
}}

#endif

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file    CameraResectioning.cpp
 * @brief   An example of gtsam for solving the camera resectioning problem
 * @author  Duy-Nguyen Ta
 * @date    Aug 23, 2011
 */

#include <gtsam/inference/Symbol.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/geometry/PinholeCamera.h>
#include <gtsam/geometry/Cal3_S2.h>
#include <boost/make_shared.hpp>

using namespace gtsam;
using namespace gtsam::noiseModel;
using symbol_shorthand::X;

/**
 * Unary factor on the unknown pose, resulting from meauring the projection of
 * a known 3D point in the image
 */
class ResectioningFactor: public NoiseModelFactor1<Pose3> {
  typedef NoiseModelFactor1<Pose3> Base;

  Cal3_S2::shared_ptr K_; ///< camera's intrinsic parameters
  Point3 P_;              ///< 3D point on the calibration rig
  Point2 p_;              ///< 2D measurement of the 3D point

public:

  /// Construct factor given known point P and its projection p
  ResectioningFactor(const SharedNoiseModel& model, const Key& key,
      const Cal3_S2::shared_ptr& calib, const Point2& p, const Point3& P) :
      Base(model, key), K_(calib), P_(P), p_(p) {
  }

  /// evaluate the error
  virtual Vector evaluateError(const Pose3& pose, boost::optional<Matrix&> H =
      boost::none) const {
    PinholeCamera<Cal3_S2> camera(pose, *K_);
    return camera.project(P_, H, boost::none, boost::none) - p_;
  }
};

/*******************************************************************************
 * Camera: f = 1, Image: 100x100, center: 50, 50.0
 * Pose (ground truth): (Xw, -Yw, -Zw, [0,0,2.0]')
 * Known landmarks:
 *    3D Points: (10,10,0) (-10,10,0) (-10,-10,0) (10,-10,0)
 * Perfect measurements:
 *    2D Point:  (55,45)   (45,45)    (45,55)     (55,55)
 *******************************************************************************/
int main(int argc, char* argv[]) {
  /* read camera intrinsic parameters */
  Cal3_S2::shared_ptr calib(new Cal3_S2(1, 1, 0, 50, 50));

  /* 1. create graph */
  NonlinearFactorGraph graph;

  /* 2. add factors to the graph */
  // add measurement factors
  SharedDiagonal measurementNoise = Diagonal::Sigmas(Vector2(0.5, 0.5));
  boost::shared_ptr<ResectioningFactor> factor;
  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,
          Point2(55, 45), Point3(10, 10, 0));
  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,
          Point2(45, 45), Point3(-10, 10, 0));
  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,
          Point2(45, 55), Point3(-10, -10, 0));
  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,
          Point2(55, 55), Point3(10, -10, 0));

  /* 3. Create an initial estimate for the camera pose */
  Values initial;
  initial.insert(X(1),
      Pose3(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(0, 0, 2)));

  /* 4. Optimize the graph using Levenberg-Marquardt*/
  Values result = LevenbergMarquardtOptimizer(graph, initial).optimize();
  result.print("Final result:\n");

  return 0;
}


text:
#include "FighterEntity.h"
#include "../Config/PlayerMovement.h"
#include "../Config/GameRules.h"
#include <boost/math/constants/constants.hpp>

#include <DescentEngine/src/EntityEngine/EntityEngine.h>
#include <DescentEngine/src/Pathfinding/Pathfinding.h>
#include <DescentEngine/src/Pathfinding/Node.h>
#include <DescentEngine/src/Timing.h>
#include <bullet/btBulletCollisionCommon.h>

FighterEntity::FighterEntity(Vector2 intialPosition, Rectangle2 boundingBox) :
		MultiVisualEntity(intialPosition, boundingBox), m_dead(false), m_life(GameRules::FighterLife), m_attackTime(
				EnemyBehaviour::AttacDelay), m_lastHit(-1.0f) {
	m_doesCollisionStick = true;
	setCollisionGroup(GameCollisionGroups::Characters);
	setCollisionMask(GameCollisionGroups::Characters_CollidesWith);
}

int FighterEntity::getCurrentSekktor() const {
	auto dir = getDirection();

	float cosPhi = acos(dir.y());
	// handle left sektor
	if (dir.x() < 0.0f) {
		cosPhi = boost::math::constants::pi<float>() + boost::math::constants::pi<float>() - cosPhi;
	}
	float sektor = (cosPhi / (2.0f * boost::math::constants::pi<float>())) * 8.0f;
	// rotate, so the up / down position will be in the middle of a sekktor
	// and not on the border
	sektor += 0.5f;
	// handle wrap around
	if (sektor < 0.0f) {
		sektor = std::fabs(0.5f + sektor);
	}
	if (sektor >= 8.0f) {
		sektor = 0.0f;
	}

	return std::floor(sektor);
}

void FighterEntity::updateVisual(Engines & eg) {
	const int sekktor = getCurrentSekktor();

	if (isDead()) {
		changeActiveVisual(eg, DescentTextureIds::Dead_0 + sekktor);
	} else if (getJumpAction().isActive()) {
		changeActiveVisual(eg, DescentTextureIds::Jump_0 + sekktor);
	} else if (getKickAction().isActive()) {
		changeActiveVisual(eg, DescentTextureIds::Kick_0 + sekktor);
	} else if (getHitAction().isActive()) {
		changeActiveVisual(eg, DescentTextureIds::Hit_0 + sekktor);
		// todo: use movement here so only walk when we actually move
	} else if (wasMoved()) {
		changeActiveVisual(eg, DescentTextureIds::Walk_0 + sekktor);
	} else {
		// idle animation
		// todo: call only when needed
		changeActiveVisual(eg, DescentTextureIds::Stand_0 + sekktor);
	}
}

void FighterEntity::validateActions(float deltaT, float hitRegenTime) {
	// todo: not so nice, make this more generic
	getJumpAction().validate(deltaT, PlayerMovement::JumpRegenerationTime);
	getKickAction().validate(deltaT, PlayerMovement::JumpRegenerationTime);
	getHitAction().validate(deltaT, hitRegenTime);
}

void FighterEntity::die() {
	m_dead = true;
	setCollisionGroup(GameCollisionGroups::CharactersDead);
	setCollisionMask(GameCollisionGroups::CharactersDead_CollidesWith);
	logging::Debug<>() << "A Fighter died !";
}

float FighterEntity::runTo(Vector2 location, float maxSpeed, float deltaT, EntityEngine & entNG,
		float closeThreshold) {

	constexpr float minimumMoveSq(util::sq(0.1f));

	// we are almost there already ...
	if (util::withinDelta(getPosition(), location, minimumMoveSq)) {
		return 0.0f;
	}

	bool runPathfinding = true;

	if (m_nextNode.isValid())
		if (!util::withinDelta(getPosition(), m_nextNode.getValue(), minimumMoveSq)) {
			// just move further to the last node found
			// not close enough to this node, yet
			runPathfinding = false;
		}

	if (runPathfinding) {
		Pathfinding & finding = entNG.getPathfinding();

		Node * startNode = entNG.findClosestNode(this->getPosition());
		Node * endNode = entNG.findClosestNode(location);

		assert(startNode);
		assert(endNode);

		//Timing tm;
		finding.reset();
		finding.resetNodes(entNG.getPathfindingNodes());
		const auto path = finding.pathToNode(startNode, endNode);
		//float dt = tm.end();
		//logging::Info() << "Pathfinding took " << dt << " seconds";

		// move to the next node:
		const float distToTarget = startNode->distanceTo(endNode);
		if (path.size() > 1) {
			const Vector2 nextLocation = path[1]->Location;
			m_nextNode.setValue(nextLocation);
		} else {
			m_nextNode.invalidate();
			return 0.0f;
		}
	}
	const Vector2 conVector(m_nextNode.getValue() - getPosition());
	const float dist = conVector.mag();
	const Vector2 dir = conVector.normalizedCopy();

	if (dir.nonZero()) {
		const float maxSpeedPerTimeStep = maxSpeed * deltaT;

		const Vector2 maxMove = dir * maxSpeedPerTimeStep;
		setDirection(dir);
		setMoveDelta(maxMove);
	}

	const float distToTarget = (getPosition() - location).mag();

	return distToTarget;
}

max_stars_repo_name: poseidn/KungFoo-legacy

max_issues_repo_name: poseidn/KungFoo-legacy

max_forks_repo_name: poseidn/KungFoo-legacy


text:
#include "onepass/storage.hpp"

#include <cryptopp/base64.h>

#include <boost/algorithm/string.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <fstream>
#include <sstream>

#include "cryptopp/cryptlib.h"
#include "cryptopp/files.h"
#include "cryptopp/osrng.h"
#include "cryptopp/salsa.h"
#include "cryptopp/secblock.h"
#include "onepass/database.hpp"

using namespace onepass::storage;

void Storage::read(
    Database &database,
    const std::string password,
    const std::string filename,
    EncodeType encodeType,
    EncryptType encryptType)
{
  if (encryptType == EncryptType::Salsa2)
  {
    CryptoPP::byte digest[CryptoPP::SHA256::DIGESTSIZE];
    CryptoPP::Salsa20::Decryption decryption;
    CryptoPP::SecByteBlock sbb(8);
    memset(sbb, 0x10101110, sbb.size());
    CryptoPP::SHA256().CalculateDigest(
        digest, reinterpret_cast<const CryptoPP::byte *>(password.c_str()), password.length());
    decryption.SetKeyWithIV(digest, CryptoPP::SHA256::DIGESTSIZE, sbb, sbb.size());

    if (encodeType == EncodeType::None)
    {
      std::string decrypted;
      CryptoPP::FileSource database2(
          filename.c_str(), true, new CryptoPP::StreamTransformationFilter(decryption, new CryptoPP::StringSink(decrypted)));
      std::istringstream iss(decrypted);
      boost::archive::text_iarchive iar(iss);
      iar >> database;
    }
    if (encodeType == EncodeType::Url || encodeType == EncodeType::Base64)
    {
      std::ifstream ifs(filename);
      if (ifs.is_open())
      {
        std::stringstream ss;
        ss << ifs.rdbuf();
        ss.str(decode(ss.str(), encodeType));
        std::string decrypted;
        CryptoPP::StringSource stringSource(
            ss.str(), true, new CryptoPP::StreamTransformationFilter(decryption, new CryptoPP::StringSink(decrypted)));
        std::istringstream iss(decrypted);
        boost::archive::text_iarchive iar(iss);
        iar >> database;
      }
    }
  }
  if (encryptType == EncryptType::None)
  {
    std::ifstream ifs(filename);
    if (ifs.is_open())
    {
      std::stringstream ss;
      ss << ifs.rdbuf();
      ss.str(decode(ss.str(), encodeType));
      boost::archive::text_iarchive iar(ss);
      iar >> database;
    }
  }
}

void Storage::save(const Database &database, const std::string filename, EncodeType encodeType, EncryptType encryptType)
{
  if (encryptType == EncryptType::Salsa2)
  {
    CryptoPP::byte digest[CryptoPP::SHA256::DIGESTSIZE];
    CryptoPP::SecByteBlock sbb(8);
    CryptoPP::Salsa20::Encryption encryption;

    memset(sbb, 0x10101110, sbb.size());
    CryptoPP::SHA256().CalculateDigest(
        digest, reinterpret_cast<const CryptoPP::byte *>(database.getPassword().c_str()), database.getPassword().length());
    encryption.SetKeyWithIV(digest, CryptoPP::SHA256::DIGESTSIZE, sbb, sbb.size());

    std::ostringstream oss;
    boost::archive::text_oarchive oar{ oss };
    oar << database;

    if (encodeType == EncodeType::None)
    {
      CryptoPP::StringSource stringSource(
          oss.str(), true, new CryptoPP::StreamTransformationFilter(encryption, new CryptoPP::FileSink(filename.c_str())));
    }
    if (encodeType == EncodeType::Base64 || encodeType == EncodeType::Url)
    {
      std::string encrypted;
      CryptoPP::StringSource stringSource(
          oss.str(), true, new CryptoPP::StreamTransformationFilter(encryption, new CryptoPP::StringSink(encrypted)));

      std::ofstream ofs;
      ofs.open(filename.c_str(), std::ios::out);
      if (ofs.is_open())
      {
        ofs << encode(encrypted, encodeType);
        ofs.close();
      }
    }
  }
  if (encryptType == EncryptType::None)
  {
    std::stringstream ss;
    std::ofstream ofs;
    ofs.open(filename.c_str(), std::ios::out);
    if (ofs.is_open())
    {
      boost::archive::text_oarchive oar{ ss };
      oar << database;
      ofs << encode(ss.str(), encodeType);
      ofs.close();
    }
    else
      throw "Error opening file";
  }
}

bool Storage::doesFileExists(std::string const path)
{
  std::ifstream file(path.c_str());
  return file.good();
}

std::string Storage::encode(const std::string &value, EncodeType encodeType)
{
  switch (encodeType)
  {
    case EncodeType::Url: return encodeUrl64(value);
    case EncodeType::Base64: return encode64(value);
    case EncodeType::None: return value;
    default: return encode64(value);
  }
}

std::string Storage::decode(const std::string &value, EncodeType encodeType)
{
  switch (encodeType)
  {
    case EncodeType::Url: return decodeUrl64(value);
    case EncodeType::Base64: return decode64(value);
    case EncodeType::None: return value;
    default: return decode64(value);
  }
}

std::string Storage::decode64(const std::string &value)
{
  std::string decoded;
  using namespace CryptoPP;
  StringSource ss(value, true, new Base64Decoder(new StringSink(decoded)));
  return decoded;
}

std::string Storage::encode64(const std::string &value)
{
  std::string encoded;
  using namespace CryptoPP;
  StringSource ss(
      reinterpret_cast<const byte *>(value.c_str()), value.size(), true, new Base64Encoder(new StringSink(encoded)));
  return encoded;
}

std::string Storage::decodeUrl64(const std::string &value)
{
  std::string decoded;
  using namespace CryptoPP;
  StringSource ss(value, true, new Base64URLDecoder(new StringSink(decoded)));
  return decoded;
}

std::string Storage::encodeUrl64(const std::string &value)
{
  std::string encoded;
  using namespace CryptoPP;
  StringSource ss(
      reinterpret_cast<const byte *>(value.c_str()), value.size(), true, new Base64URLEncoder(new StringSink(encoded)));
  return encoded;
}

max_stars_repo_name: inql/OnePass

max_issues_repo_name: inql/OnePass

max_forks_repo_name: inql/OnePass


text:
#define BOOST_TEST_MODULE Helper
#define BOOST_DYN_LINK
#define BOOST_TEST_MAIN

#include <type_traits>
#include <string>

#include <boost/test/included/unit_test.hpp>

#include "dachs/helper/probable.hpp"

using namespace dachs::helper;

BOOST_AUTO_TEST_SUITE(helper)

BOOST_AUTO_TEST_SUITE(helper)

BOOST_AUTO_TEST_CASE(string_error)
{
    enum class test {
        foo, bar, baz
    };

    static_assert(std::is_same<typename probable<int>::success_type, int>::value, "");
    static_assert(std::is_same<typename probable<int>::failure_type, std::string>::value, "");
    static_assert(std::is_same<typename probable<int, char>::failure_type, char>::value, "");

    auto const p1 = make_probable<test>(test::bar);
    BOOST_CHECK(p1.success());
    BOOST_CHECK(!p1.failure());

    auto const r1 = p1.get();
    BOOST_CHECK(r1);
    BOOST_CHECK(*r1 == test::bar);
    BOOST_CHECK(p1.get_unsafe() == test::bar);
    BOOST_CHECK(p1.raw_value().which() == 0u);

    auto const f1 = p1.get_error();
    BOOST_CHECK(!f1);

    probable<test> const p2 = oops("error occurred!");
    BOOST_CHECK(!p2.success());
    BOOST_CHECK(p2.failure());

    auto const r2 = p2.get();
    BOOST_CHECK(!r2);

    auto const f2 = p2.get_error();
    BOOST_CHECK(f2);
    BOOST_CHECK(*f2 == "error occurred!");
    BOOST_CHECK(p2.get_error_unsafe() == "error occurred!");
    BOOST_CHECK(p2.raw_value().which() == 1u);

    auto p3 = probably(test::baz);
    p3 = test::foo;
    auto foo = test::foo;
    p3 = foo;
    auto const foo2 = foo;
    p3 = foo2;

    auto p4 = p3;
    probable<test> p5 = test::foo;
    BOOST_CHECK(p5.success());

    BOOST_CHECK(p4 == p5);
    BOOST_CHECK(p1 != p5);
    BOOST_CHECK(p2 != p5);
    BOOST_CHECK(p2 == p2);
    BOOST_CHECK(p5 < p1);

    auto const g = make_probable_generator<test>();
    auto const p6 = g(test::foo);
    BOOST_CHECK(p6.success());

    probable<test> const p7 = oops_fmt("there is %1% errors", 7);
    BOOST_CHECK(p7.failure());
    BOOST_CHECK(*p7.get_error() == "there is 7 errors");
    oops_fmt("%1%, %2%, %3%", 1, 3.14, "aaa");
    oops_fmt("does not contain any formatters");
}

BOOST_AUTO_TEST_CASE(user_defined_error)
{
    enum class test {
        foo, bar, baz
    };

    enum class error {
        err1, err2, err3
    };

    using test_type = probable<test, error>;

    test_type const p1 = test::bar;
    BOOST_CHECK(p1.success());
    BOOST_CHECK(!p1.failure());

    auto const r1 = p1.get();
    BOOST_CHECK(r1);
    BOOST_CHECK(*r1 == test::bar);
    BOOST_CHECK(p1.get_unsafe() == test::bar);
    BOOST_CHECK(p1.raw_value().which() == 0u);

    auto const f1 = p1.get_error();
    BOOST_CHECK(!f1);

    test_type const p2 = oops<error>(error::err1);
    BOOST_CHECK(!p2.success());
    BOOST_CHECK(p2.failure());

    auto const r2 = p2.get();
    BOOST_CHECK(!r2);

    auto const f2 = p2.get_error();
    BOOST_CHECK(f2);
    BOOST_CHECK(*f2 == error::err1);
    BOOST_CHECK(p2.get_error_unsafe() == error::err1);
    BOOST_CHECK(p2.raw_value().which() == 1u);
}

BOOST_AUTO_TEST_CASE(edge_case_string)
{
    auto const p = make_probable<std::string>("aaaa");
    BOOST_CHECK(p.success());
    auto const r = p.get();
    BOOST_CHECK(r);
    BOOST_CHECK(*r == "aaaa");
    auto const v = p.get_value_or_error();

    probable<std::string> const p2 = oops("bbbb");
    BOOST_CHECK(p2.failure());
    auto const f = p2.get_error();
    BOOST_CHECK(f);
    BOOST_CHECK(*f == "bbbb");
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: rhysd/Dachs

max_stars_repo_licenses: NCSA MIT

max_issues_repo_name: maekawatoshiki/Dachs

max_issues_repo_licenses: NCSA MIT

max_forks_repo_name: maekawatoshiki/Dachs

max_forks_repo_licenses: NCSA MIT


text:
/*
 * TreeIkSolverVel_wdls.hpp
 *
 *  Created on: Nov 28, 2008
 *      Author: rubensmits
 */

#ifndef TREEIKSOLVERVEL_WDLS_HPP_
#define TREEIKSOLVERVEL_WDLS_HPP_

#include "treeiksolver.hpp"
#include "treejnttojacsolver.hpp"
#include <Eigen/Core>

namespace KDL {

    class TreeIkSolverVel_wdls: public TreeIkSolverVel {
    public:
        static const int E_SVD_FAILED = -100; //! Child SVD failed

        TreeIkSolverVel_wdls(const Tree& tree, const std::vector<std::string>& endpoints);
        virtual ~TreeIkSolverVel_wdls();

        virtual double CartToJnt(const JntArray& q_in, const Twists& v_in, JntArray& qdot_out);

        /*
         * Set the joint space weighting matrix
         *
         * @param weight_js joint space weighting symmetric matrix,
         * default : identity.  M_q : This matrix being used as a
         * weight for the norm of the joint space speed it HAS TO BE
         * symmetric and positive definite. We can actually deal with
         * matrices containing a symmetric and positive definite block
         * and 0s otherwise. Taking a diagonal matrix as an example, a
         * 0 on the diagonal means that the corresponding joints will
         * not contribute to the motion of the system. On the other
         * hand, the bigger the value, the most the corresponding
         * joint will contribute to the overall motion. The obtained
         * solution q_dot will actually minimize the weighted norm
         * sqrt(q_dot'*(M_q^-2)*q_dot). In the special case we deal
         * with, it does not make sense to invert M_q but what is
         * important is the physical meaning of all this : a joint
         * that has a zero weight in M_q will not contribute to the
         * motion of the system and this is equivalent to saying that
         * it gets an infinite weight in the norm computation.  For
         * more detailed explanation : vincent.padois@upmc.fr
         */
        void setWeightJS(const Eigen::MatrixXd& Mq);
        const Eigen::MatrixXd& getWeightJS() const {return Wq;}

        /*
         * Set the task space weighting matrix
         *
         * @param weight_ts task space weighting symmetric matrix,
         * default: identity M_x : This matrix being used as a weight
         * for the norm of the error (in terms of task space speed) it
         * HAS TO BE symmetric and positive definite. We can actually
         * deal with matrices containing a symmetric and positive
         * definite block and 0s otherwise. Taking a diagonal matrix
         * as an example, a 0 on the diagonal means that the
         * corresponding task coordinate will not be taken into
         * account (ie the corresponding error can be really big). If
         * the rank of the jacobian is equal to the number of task
         * space coordinates which do not have a 0 weight in M_x, the
         * weighting will actually not impact the results (ie there is
         * an exact solution to the velocity inverse kinematics
         * problem). In cases without an exact solution, the bigger
         * the value, the most the corresponding task coordinate will
         * be taken into account (ie the more the corresponding error
         * will be reduced). The obtained solution will minimize the
         * weighted norm sqrt(|x_dot-Jq_dot|'*(M_x^2)*|x_dot-Jq_dot|).
         * For more detailed explanation : vincent.padois@upmc.fr
         */
        void setWeightTS(const Eigen::MatrixXd& Mx);
        const Eigen::MatrixXd& getWeightTS() const {return Wy;}

        void setLambda(const double& lambda);
        double getLambda () const {return lambda;}

    private:
        Tree tree;
        TreeJntToJacSolver jnttojacsolver;
        Jacobians jacobians;

        Eigen::MatrixXd J, Wy, Wq, J_Wq, Wy_J_Wq, U, V, Wy_U, Wq_V;
        Eigen::VectorXd t, Wy_t, qdot, tmp, S;
        double lambda;
    };

}

#endif /* TREEIKSOLVERVEL_WDLS_HPP_ */

max_stars_repo_name: rocos-sia/rocos-app