text:
#include <iostream>
#include <boost/numeric/meta_math/is_prime.hpp>

int main()
{
    const long int i= 10001;

    std::cout << i << " is " << (meta_math::is_prime<i>::value ? "" : "not ") << "prime.\n";

    return 0;
}

ext: cpp


text:
// Copyright (c) 2007-2008 Sean Kent
//
// 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 )
//
// $LastChangedBy: washuhibiki $ - $LastChangedDate: 2008-05-13 13:45:12 -0700 (Tue, 13 May 2008) $

#if !BOOST_PP_IS_ITERATING
#ifndef IG_INDUSTRY_LANGAUGES_RUBY_DETAIL_CONSTRUCTOR_REGISTRY
#define IG_INDUSTRY_LANGAUGES_RUBY_DETAIL_CONSTRUCTOR_REGISTRY

#include <boost/preprocessor/repetition.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/list/at.hpp>
#include <boost/preprocessor/list/for_each_product.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/to_list.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>
#include <map>
#include <string>

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable: 4100 ) // unreferenced formal parameters
#pragma warning( disable: 4101 ) // unreferenced formal parameters
#endif

namespace industry { namespace languages { namespace ruby { namespace detail {
	template<class T, unsigned int A>
	struct constructor_registry;

	template<class T, class Sig, unsigned int A>
	struct constructor_registry_impl {
	};

#	define BOOST_PP_ITERATION_LIMITS (0, 17)
#	define BOOST_PP_FILENAME_1       <industry/languages/ruby/detail/constructor_registry.hpp>
#	include BOOST_PP_ITERATE()

}}}}
#endif//IG_INDUSTRY_LANGAUGES_RUBY_DETAIL_CONSTRUCTOR_REGISTRY
#else
#define n BOOST_PP_ITERATION()
#define FUNCTION_ARG_TYPE(i) BOOST_PP_CAT(typename func_type::arg, BOOST_PP_CAT(BOOST_PP_INC(i),_type))
#define DO_TEST_FUNC_ARG(z,i,data) if (!ruby_value<FUNCTION_ARG_TYPE(i)>::is_a(argv[i])) return false;
#define DO_WRAP_FUNC_ARG(z,i,data) (ruby_value<FUNCTION_ARG_TYPE(i)>::from(argv[i]))

template<class T, class Sig>
struct constructor_registry_impl<T, Sig, n> {
	typedef boost::function<Sig> func_type;
	static void reg() {
		std::vector<constructor_registry_entry>& m = constructor_registry<T, n>::get_constructors();
		constructor_registry_entry entry = { &test_match , &f };
		m.push_back(entry);
	}

	static bool test_match(int argc, VALUE* argv, VALUE self) {
		BOOST_PP_REPEAT(n, DO_TEST_FUNC_ARG, BOOST_PP_EMPTY); // returns false if mismatch
		return true;
	}
	static VALUE f(int argc, VALUE* argv, VALUE self) {
		T* ptr = ruby_value<T*>::from(self);
		new (ptr) T(BOOST_PP_ENUM(n, DO_WRAP_FUNC_ARG, BOOST_PP_EMPTY));
		instance_registry<T>::ruby_initialized(ptr,self); // inject self
		instance_registry<T>::register_ruby_owned(ptr);
		return self;
	}
};

#undef n
#undef DO_WRAP_VALUE
#undef DO_WRAP_VALUE_MEMBER
#undef FUNCTION_ARG_TYPE
#endif

ext: hpp

max_stars_repo_name: MaulingMonkey/libindustry

max_issues_repo_name: MaulingMonkey/libindustry

max_forks_repo_name: MaulingMonkey/libindustry


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 "client/client.h"

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

namespace Naming
{
    using namespace Common;
    using namespace Client;
    using namespace std;
    using namespace Api;
    using namespace Client;
    using namespace ServiceModel;

    class ComFabricClientTest
    {
    protected:
        HRESULT CreateComFabricClient(
            USHORT connectionStringsSize,
            LPCWSTR const *connectionStrings,
            REFIID riid,
            void ** fabricClient);
    };

    //
    // Temporarily overwrites a referenced value in the constructor, and restores the old value
    // in the destructor when it goes out of scope.
    //
    template<class T>
    class ScopeChange
    {
        DENY_COPY(ScopeChange);
    public:
        ScopeChange(T & target, T value) : original_(target), target_(target) { target_ = value; }
        ~ScopeChange() { target_ = original_; }
    private:
        T original_;
        T & target_;
    };

    // Test class to convert from async to sync.
    class ComTestCallback : public IFabricAsyncOperationCallback, private Common::ComUnknownBase
    {
        DENY_COPY(ComTestCallback)
        COM_INTERFACE_LIST1(ComTestCallback, IID_IFabricAsyncOperationCallback, IFabricAsyncOperationCallback)
    public:
        ComTestCallback() : wait_(false) { }
        void STDMETHODCALLTYPE Invoke(IFabricAsyncOperationContext *) { wait_.Set(); }
        void Wait() { wait_.WaitOne(); }
    private:
        AutoResetEvent wait_;
    };

    void CheckHRESULT(
        HRESULT hr,
        HRESULT expectedHr)
    {
         VERIFY_IS_TRUE_FMT(hr == expectedHr,
            "CheckHRESULT: Expected {0}, got {1}",
            ErrorCode::FromHResult(expectedHr).ErrorCodeValueToString().c_str(),
            ErrorCode::FromHResult(hr).ErrorCodeValueToString().c_str());

    }

    //
    // Note: Parameter Validation is part of both the COM client API Wrapper(api\ComfabricClient)
    // as well as the Client Implementation(Client\FabricClientImpl).
    // Public type -> Internal Type is conversion is validated at the COM layer. The correctness of
    // the internal type object is checked in the Client implementation.
    //
    void ExpectGatewayNotReachable(
        __in ComPointer<IFabricServiceManagementClient> & client,
        __in FABRIC_SERVICE_DESCRIPTION & service)
    {
        ComPointer<ComTestCallback> callback; callback.SetNoAddRef(new ComTestCallback());
        ComPointer<IFabricAsyncOperationContext> context;
        DWORD timeout = 2 * static_cast<DWORD>(Client::ClientConfig::GetConfig().ConnectionInitializationTimeout.TotalMilliseconds());
        HRESULT hr = client->BeginCreateService(
            &service, timeout, callback.GetRawPointer(), context.InitializationAddress());
        if (SUCCEEDED(hr))
        {
            VERIFY_IS_TRUE(hr == S_OK);
            callback->Wait();
            hr = client->EndCreateService(context.GetRawPointer());
        }

        CheckHRESULT(hr, FABRIC_E_GATEWAY_NOT_REACHABLE);
    }

    void ExpectInvalidArg(
        __in ComPointer<IFabricServiceManagementClient> & client,
        __in FABRIC_SERVICE_DESCRIPTION & service)
    {
        ComPointer<ComTestCallback> callback; callback.SetNoAddRef(new ComTestCallback());
        ComPointer<IFabricAsyncOperationContext> context;
        HRESULT hr = client->BeginCreateService(
            &service, 0, callback.GetRawPointer(), context.InitializationAddress());
        if (SUCCEEDED(hr))
        {
            VERIFY_IS_TRUE(hr == S_OK);
            callback->Wait();
            hr = client->EndCreateService(context.GetRawPointer());
        }

        CheckHRESULT(hr, E_INVALIDARG);
    }

    typedef std::function<HRESULT(DWORD, IFabricAsyncOperationCallback *, IFabricAsyncOperationContext **)> BeginOperationCallback;
    typedef std::function<HRESULT(IFabricAsyncOperationContext *)> EndOperationCallback;
    void ExpectInvalidNameUriError(
        BeginOperationCallback const & beginOperationCallback,
        EndOperationCallback const & endOperationCallback = nullptr)
    {
        DWORD timeout = 1000;
        ComPointer<ComTestCallback> callback; callback.SetNoAddRef(new ComTestCallback());
        ComPointer<IFabricAsyncOperationContext> context;
        HRESULT hr = beginOperationCallback(timeout, callback.GetRawPointer(), context.InitializationAddress());
        if (SUCCEEDED(hr) && endOperationCallback != nullptr)
        {
            VERIFY_IS_TRUE(hr == S_OK);
            callback->Wait();
            hr = endOperationCallback(context.GetRawPointer());
        }

        CheckHRESULT(hr, FABRIC_E_INVALID_NAME_URI);
    }

    void ExpectInvalidArg(BeginOperationCallback const & operationCallback)
    {
        DWORD timeout = 1000;
        ComPointer<ComTestCallback> callback; callback.SetNoAddRef(new ComTestCallback());
        ComPointer<IFabricAsyncOperationContext> context;
        HRESULT hr = operationCallback(timeout, callback.GetRawPointer(), context.InitializationAddress());

        CheckHRESULT(hr, E_INVALIDARG);
    }

    HRESULT ComFabricClientTest::CreateComFabricClient(
        USHORT connectionStringsSize,
        LPCWSTR const *connectionStrings,
        REFIID riid,
        void ** fabricClient)
    {
        IClientFactoryPtr factoryPtr;
        auto error = ClientFactory::CreateClientFactory(
            connectionStringsSize,
            connectionStrings,
            factoryPtr);

        if (!error.IsSuccess()) { return error.ToHResult(); }

        ComPointer<Api::ComFabricClient> comClient;
        auto hr = Api::ComFabricClient::CreateComFabricClient(factoryPtr, comClient);

        if (FAILED(hr)) { return hr; }

        hr = comClient->QueryInterface(riid, fabricClient);

        return hr;
    }

    BOOST_FIXTURE_TEST_SUITE(ComFabricClientTestSuite,ComFabricClientTest)

    BOOST_AUTO_TEST_CASE(TestSecuritySettingsParameterValidation)
    {
        LPCWSTR connectionStringItem = L"127.0.0.1:12340";
        ComPointer<IFabricClientSettings> comFabricClient;
        HRESULT hrClient = CreateComFabricClient(
            1,
            &connectionStringItem,
            IID_IFabricClientSettings,
            comFabricClient.VoidInitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        FABRIC_SECURITY_CREDENTIALS securityCredentials;
        securityCredentials.Kind = FABRIC_SECURITY_CREDENTIAL_KIND_X509;
        securityCredentials.Value = NULL;

        HRESULT hr = comFabricClient->SetSecurityCredentials(&securityCredentials);
        CheckHRESULT(hr, ErrorCodeValue::InvalidCredentials);

        ULONG keepAliveInterval = 10;
        hr = comFabricClient->SetKeepAlive(keepAliveInterval);
        VERIFY_SUCCEEDED(hr, L"SetKeepAlive successful");

#ifndef PLATFORM_UNIX
        wstring storeName = X509Default::StoreName();
        wstring emptyString = L"";
        FABRIC_X509_CREDENTIALS x509Credentials = {0};
        x509Credentials.AllowedCommonNames = NULL;
        x509Credentials.AllowedCommonNameCount = 0;
        x509Credentials.ProtectionLevel = FABRIC_PROTECTION_LEVEL_ENCRYPTANDSIGN;

        x509Credentials.StoreLocation = FABRIC_X509_STORE_LOCATION_CURRENTUSER;

        x509Credentials.StoreName = storeName.c_str();
        x509Credentials.FindType = FABRIC_X509_FIND_TYPE_FINDBYSUBJECTNAME;
        x509Credentials.FindValue = NULL;
        securityCredentials.Value = &x509Credentials;

        hr = comFabricClient->SetSecurityCredentials(&securityCredentials);
        CheckHRESULT(hr, ErrorCodeValue::InvalidSubjectName);

        x509Credentials.FindType = FABRIC_X509_FIND_TYPE_FINDBYTHUMBPRINT;

        hr = comFabricClient->SetSecurityCredentials(&securityCredentials);
        CheckHRESULT(hr, ErrorCodeValue::InvalidX509Thumbprint);

        x509Credentials.FindValue = (void*)emptyString.c_str();

        hr = comFabricClient->SetSecurityCredentials(&securityCredentials);
        CheckHRESULT(hr, ErrorCodeValue::InvalidX509Thumbprint);

        x509Credentials.FindType = FABRIC_X509_FIND_TYPE_FINDBYSUBJECTNAME;
        x509Credentials.FindValue = (void*)emptyString.c_str();

        hr = comFabricClient->SetSecurityCredentials(&securityCredentials);
        CheckHRESULT(hr, ErrorCodeValue::InvalidSubjectName);

        x509Credentials.StoreName = emptyString.c_str();
        hr = comFabricClient->SetSecurityCredentials(&securityCredentials);
        CheckHRESULT(hr, ErrorCodeValue::InvalidX509StoreName);
#endif
    }

    BOOST_AUTO_TEST_CASE(TestServiceParameterValidation)
    {
        LPCWSTR connectionStringItem = L"127.0.0.1:12340";

        ComPointer<IFabricClientSettings> comFabricClient;
        HRESULT hrClient = CreateComFabricClient(
            1,
            &connectionStringItem,
            IID_IFabricClientSettings,
            comFabricClient.VoidInitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        ComPointer<IFabricServiceManagementClient> client;
        hrClient = comFabricClient->QueryInterface(IID_IFabricServiceManagementClient, (void**)client.InitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        FABRIC_SERVICE_DESCRIPTION service; memset(&service, 0, sizeof(service));
        FABRIC_STATEFUL_SERVICE_DESCRIPTION stateful; memset(&stateful, 0, sizeof(stateful));
        FABRIC_UNIFORM_INT64_RANGE_PARTITION_SCHEME_DESCRIPTION partition; memset(&partition, 0, sizeof(partition));

        service.Kind = FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL;
        service.Value = &stateful;

        stateful.ServiceName = L"fabric:/MyService";
        stateful.ServiceTypeName = L"MyServiceType";
        stateful.InitializationData = NULL;
        stateful.InitializationDataSize = 0;
        stateful.PartitionScheme = FABRIC_PARTITION_SCHEME_UNIFORM_INT64_RANGE;
        stateful.PartitionSchemeDescription = &partition;
        stateful.TargetReplicaSetSize = 3;
        stateful.MinReplicaSetSize = 2;
        stateful.PlacementConstraints = NULL;
        stateful.CorrelationCount = 0;
        stateful.Correlations = NULL;
        stateful.MetricCount = 0;
        stateful.Metrics = NULL;
        stateful.HasPersistedState = TRUE;

        partition.PartitionCount = 3;
        partition.LowKey = 0;
        partition.HighKey = 99;

        Trace.WriteInfo("ComFabricClientTestSource", "Original service description should pass validation and timeout.");
        ExpectGatewayNotReachable(client, service);

        {
            Trace.WriteInfo("ComFabricClientTestSource", "Empty service metric name should fail.");
            FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION metric = {0};
            metric.Name = NULL;
            metric.Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_LOW;
            metric.PrimaryDefaultLoad = 1;
            metric.SecondaryDefaultLoad = 1;
            ScopeChange<FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION *> descChange(
                stateful.Metrics,
                &metric);
            ScopeChange<ULONG> countChange(
                stateful.MetricCount,
                1);
            ExpectInvalidArg(client, service);
        }

        {
            Trace.WriteInfo("ComFabricClientTestSource", "Invalid correlation scheme should fail.");
            FABRIC_SERVICE_CORRELATION_DESCRIPTION correlation = {0};
            correlation.ServiceName = L"fabric:/AnotherService";
            correlation.Scheme = FABRIC_SERVICE_CORRELATION_SCHEME_INVALID;
            ScopeChange<FABRIC_SERVICE_CORRELATION_DESCRIPTION *> descChange(
                stateful.Correlations,
                &correlation);
            ScopeChange<ULONG> countChange(
                stateful.CorrelationCount,
                1);
            ExpectInvalidArg(client, service);
        }

        {
            Trace.WriteInfo("ComFabricClientTestSource", "Empty correlation service name should fail.");
            FABRIC_SERVICE_CORRELATION_DESCRIPTION correlation = {0};
            correlation.ServiceName = NULL;
            correlation.Scheme = FABRIC_SERVICE_CORRELATION_SCHEME_AFFINITY;
            ScopeChange<FABRIC_SERVICE_CORRELATION_DESCRIPTION *> descChange(
                stateful.Correlations,
                &correlation);
            ScopeChange<ULONG> countChange(
                stateful.CorrelationCount,
                1);
            ExpectInvalidArg(client, service);
        }

        {
            Trace.WriteInfo("ComFabricClientTestSource", "Correlation service name is same to the current service name should fail.");
            FABRIC_SERVICE_CORRELATION_DESCRIPTION correlation = {0};
            correlation.ServiceName = L"fabric:/MyService";
            correlation.Scheme = FABRIC_SERVICE_CORRELATION_SCHEME_AFFINITY;
            ScopeChange<FABRIC_SERVICE_CORRELATION_DESCRIPTION *> descChange(
                stateful.Correlations,
                &correlation);
            ScopeChange<ULONG> countChange(
                stateful.CorrelationCount,
                1);
            ExpectInvalidArg(client, service);
        }

        {
            Trace.WriteInfo("ComFabricClientTestSource", "Correlation service name is not a valid Uri fail.");
            FABRIC_SERVICE_CORRELATION_DESCRIPTION correlation = {0};
            correlation.ServiceName = L"MyService";
            correlation.Scheme = FABRIC_SERVICE_CORRELATION_SCHEME_AFFINITY;
            ScopeChange<FABRIC_SERVICE_CORRELATION_DESCRIPTION *> descChange(
                stateful.Correlations,
                &correlation);
            ScopeChange<ULONG> countChange(
                stateful.CorrelationCount,
                1);
            ExpectInvalidArg(client, service);
        }

        {
            Trace.WriteInfo("ComFabricClientTestSource", "Invalid placement constraint should fail.");
            ScopeChange<LPCWSTR> change(
                stateful.PlacementConstraints,
                L"Invalid Placement Constraint (TM)");
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "Non-positive partition count should fail.");
            ScopeChange<LONG> change(
                partition.PartitionCount,
                0);
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "Non-positive target replica set size should fail.");
            ScopeChange<LONG> change(
                stateful.TargetReplicaSetSize,
                0);
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "LowKey larger than HighKey should fail.");
            ScopeChange<LONGLONG> change(
                partition.LowKey,
                partition.HighKey + 1);
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "one key per partition should succeed.");
            // (high-low)+1: the +1 is because high and low are inclusive.  E.g. [0,1] includes 2 keys: 0 and 1.
            ScopeChange<LONG> change(
                partition.PartitionCount,
                static_cast<LONG>(partition.HighKey - partition.LowKey) + 1);
            ExpectGatewayNotReachable(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "key-range smaller than partition count should fail.");
            // (high-low)+2: the +2 is because of +1 from previous case, and +1 to make the range 1 too large.
            ScopeChange<LONG> change(
                partition.PartitionCount,
                static_cast<LONG>((partition.HighKey - partition.LowKey) + 2));
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "All int64 values in a single partition should succeed.");
            ScopeChange<LONGLONG> lowKeyChange(
                partition.LowKey,
                numeric_limits<LONGLONG>::min());
            ScopeChange<LONGLONG> highKeyChange(
                partition.HighKey,
                numeric_limits<LONGLONG>::max());
            ScopeChange<LONG> partitionCountChange(
                partition.PartitionCount,
                1);
            ExpectGatewayNotReachable(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "Non-positive MinReplicaSetSize should fail.");
            ScopeChange<LONG> change(
                stateful.MinReplicaSetSize,
                0);
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "MinReplicaSetSize greater than TargetReplicaSetSize should fail.");
            ScopeChange<LONG> change(
                stateful.MinReplicaSetSize,
                stateful.TargetReplicaSetSize + 1);
            ExpectInvalidArg(client, service);
        }
    }

    BOOST_AUTO_TEST_CASE(TestServiceParameterValidationWithNamedPartition)
    {
        LPCWSTR connectionStringItem = L"127.0.0.1:12341";

        ComPointer<IFabricClientSettings> comFabricClient;
        HRESULT hrClient = CreateComFabricClient(
            1,
            &connectionStringItem,
            IID_IFabricClientSettings,
            comFabricClient.VoidInitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        ComPointer<IFabricServiceManagementClient> client;
        hrClient = comFabricClient->QueryInterface(IID_IFabricServiceManagementClient, (void**)client.InitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        FABRIC_SERVICE_DESCRIPTION service; memset(&service, 0, sizeof(service));
        FABRIC_STATEFUL_SERVICE_DESCRIPTION stateful; memset(&stateful, 0, sizeof(stateful));
        FABRIC_NAMED_PARTITION_SCHEME_DESCRIPTION partition; memset(&partition, 0, sizeof(partition));

        service.Kind = FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL;
        service.Value = &stateful;

        stateful.ServiceName = L"fabric:/MyService";
        stateful.ServiceTypeName = L"MyServiceType";
        stateful.InitializationData = NULL;
        stateful.InitializationDataSize = 0;
        stateful.PartitionScheme = FABRIC_PARTITION_SCHEME_NAMED;
        stateful.PartitionSchemeDescription = &partition;
        stateful.TargetReplicaSetSize = 3;
        stateful.MinReplicaSetSize = 2;
        stateful.PlacementConstraints = NULL;
        stateful.CorrelationCount = 0;
        stateful.Correlations = NULL;
        stateful.MetricCount = 0;
        stateful.Metrics = NULL;
        stateful.HasPersistedState = TRUE;

        {
            Trace.WriteInfo("ComFabricClientTestSource", "At least one partition name must be defined: test should fail");
            partition.PartitionCount = 0;
            vector<LPCWSTR> partitionNames;
            partition.Names = partitionNames.data();
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "Empty partition names are not allowed: test should fail");
            vector<LPCWSTR> partitionNames;
            partitionNames.push_back(L"");
            partition.PartitionCount = 1;
            partition.Names = partitionNames.data();
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "Duplicate partition names are not allowed: test should fail");
            vector<LPCWSTR> partitionNames;
            partitionNames.push_back(L"test");
            partitionNames.push_back(L"test");
            partition.PartitionCount = 2;
            partition.Names = partitionNames.data();
            ExpectInvalidArg(client, service);
        }
        {
            Trace.WriteInfo("ComFabricClientTestSource", "Different partition names are allowed: test should succeed");
            vector<LPCWSTR> partitionNames;
            partitionNames.push_back(L"A");
            partitionNames.push_back(L"B");
            partition.PartitionCount = 2;
            partition.Names = partitionNames.data();
            ExpectGatewayNotReachable(client, service);
        }
    }

    class MockServiceChangeHandler : public IFabricServicePartitionResolutionChangeHandler, private ComUnknownBase
    {
         BEGIN_COM_INTERFACE_LIST(MockServiceChangeHandler)
            COM_INTERFACE_ITEM(IID_IUnknown,IFabricServicePartitionResolutionChangeHandler)
            COM_INTERFACE_ITEM(IID_IFabricServicePartitionResolutionChangeHandler,IFabricServicePartitionResolutionChangeHandler)
        END_COM_INTERFACE_LIST()
    public:
        void STDMETHODCALLTYPE OnChange(IFabricServiceManagementClient *, LONGLONG, IFabricResolvedServicePartitionResult *, HRESULT) { }
    };

    BOOST_AUTO_TEST_CASE(TestInvalidRegisterCallbackParameters)
    {
        LPCWSTR connectionStringItem = L"127.0.0.1:12340";

        // Make the max message size smaller, to test invalid request for too large name + partition name
        ServiceModelConfig::GetConfig().MaxMessageSize = 1024;

        ComPointer<IFabricPropertyManagementClient> propertyClient;
        HRESULT hrClient = CreateComFabricClient(
            1,
            &connectionStringItem,
            IID_IFabricPropertyManagementClient,
            propertyClient.VoidInitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        ComPointer<IFabricServiceManagementClient> serviceClient;
        hrClient = propertyClient->QueryInterface(IID_IFabricServiceManagementClient, (void**)serviceClient.InitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        ComPointer<MockServiceChangeHandler> handler = make_com<MockServiceChangeHandler>();
        LONGLONG handle;
        HRESULT hr;

        // No name
        Trace.WriteInfo("ComFabricClientTestSource", "RegisterServicePartitionResolutionChangeHandler with null uri: test should fail");
        hr = serviceClient->RegisterServicePartitionResolutionChangeHandler(NULL, FABRIC_PARTITION_KEY_TYPE_NONE, NULL, handler.GetRawPointer(), &handle);
        CheckHRESULT(hr, E_POINTER);

        // Invalid Uri
        Trace.WriteInfo("ComFabricClientTestSource", "RegisterServicePartitionResolutionChangeHandler with invalid uri: test should fail");
        wstring invalidName = L"fabric://RegisterServicePartitionResolutionChangeHandler";
        hr = serviceClient->RegisterServicePartitionResolutionChangeHandler(invalidName.c_str(), FABRIC_PARTITION_KEY_TYPE_NONE, NULL, handler.GetRawPointer(), &handle);
        CheckHRESULT(hr, FABRIC_E_INVALID_NAME_URI);

        Trace.WriteInfo("ComFabricClientTestSource", "RegisterServicePartitionResolutionChangeHandler with null partition name: test should fail");
        wstring validName(L"fabric:/RegisterServicePartitionResolutionChangeHandler");
        hr = serviceClient->RegisterServicePartitionResolutionChangeHandler(validName.c_str(), FABRIC_PARTITION_KEY_TYPE_STRING, NULL, handler.GetRawPointer(), &handle);
        CheckHRESULT(hr, E_POINTER);

        Trace.WriteInfo("ComFabricClientTestSource", "RegisterServicePartitionResolutionChangeHandler empty partition name: test should fail");
        wstring partitionName;
        LPWSTR p(const_cast<LPWSTR>(partitionName.c_str()));
        hr = serviceClient->RegisterServicePartitionResolutionChangeHandler(validName.c_str(), FABRIC_PARTITION_KEY_TYPE_STRING, p, handler.GetRawPointer(), &handle);
        CheckHRESULT(hr, E_INVALIDARG);

        Trace.WriteInfo("ComFabricClientTestSource", "RegisterServicePartitionResolutionChangeHandler too large name/partition name: test should fail");
        wstring temp(CommonConfig::GetConfig().MaxNamingUriLength / 2 + 1, L'A');
        wstring longName;
        StringWriter(longName).Write("fabric:/{0}", temp);
        LPWSTR propPtr(const_cast<LPWSTR>(longName.c_str()));
        hr = serviceClient->RegisterServicePartitionResolutionChangeHandler(longName.c_str(), FABRIC_PARTITION_KEY_TYPE_STRING, propPtr, handler.GetRawPointer(), &handle);
        CheckHRESULT(hr, FABRIC_E_VALUE_TOO_LARGE);

        NamingConfig::GetConfig().Test_Reset();
        ClientConfig::GetConfig().Test_Reset();
    }

    BOOST_AUTO_TEST_CASE(TestInvalidLpcwstrValidation)
    {
        LPCWSTR connectionStringItem = L"127.0.0.1:12340";

        ComPointer<IFabricPropertyManagementClient> propertyClient;
        HRESULT hrClient = CreateComFabricClient(
            1,
            &connectionStringItem,
            IID_IFabricPropertyManagementClient,
            propertyClient.VoidInitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        CommonConfig::GetConfig().MaxNamingUriLength = 13;
        ServiceModelConfig::GetConfig().MaxPropertyNameLength = 13;

        wstring invalidName(L"fabric:/NameThatGoesOverThe/MaxNamingUriSize");
        wstring invalidProperty(L"fabric:/PropertyThatGoesOverThe/MaxPropertySize");
        wstring invalidEmptyProperty(L"");
        wstring validName(L"fabric:/name1");
        wstring validProperty(L"fabric:/prop1");

        // Name operations
        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginCreateName(invalidName.c_str(), timeout, callback, context);
            });

        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginDeleteName(invalidName.c_str(), timeout, callback, context);
            });

        // Property operations

        // Put
        BYTE byteData(0);
        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyBinary(invalidName.c_str(), validProperty.c_str(), 1, &byteData, timeout, callback, context);
            });

        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyBinary(validName.c_str(), invalidProperty.c_str(), 1, &byteData, timeout, callback, context);
            });

         ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyBinary(validName.c_str(), invalidEmptyProperty.c_str(), 1, &byteData, timeout, callback, context);
            });

        // Delete
        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginDeleteProperty(invalidName.c_str(), validProperty.c_str(), timeout, callback, context);
            });

        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginDeleteProperty(validName.c_str(), invalidProperty.c_str(), timeout, callback, context);
            });

        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginDeleteProperty(validName.c_str(), invalidEmptyProperty.c_str(), timeout, callback, context);
            });

        // Get
        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginGetProperty(invalidName.c_str(), validProperty.c_str(), timeout, callback, context);
            });

         ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginGetProperty(validName.c_str(), invalidProperty.c_str(), timeout, callback, context);
            });

        // GetMetadata
        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginGetPropertyMetadata(invalidName.c_str(), validProperty.c_str(), timeout, callback, context);
            });

        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginGetPropertyMetadata(validName.c_str(), invalidProperty.c_str(), timeout, callback, context);
            });

        ExpectInvalidArg([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginGetPropertyMetadata(validName.c_str(), invalidEmptyProperty.c_str(), timeout, callback, context);
            });

        NamingConfig::GetConfig().Test_Reset();
        CommonConfig::GetConfig().Test_Reset();
     }

    BOOST_AUTO_TEST_CASE(TestInvalidNameUriValidation)
    {
        LPCWSTR connectionStringItem = L"127.0.0.1:12340";

        ComPointer<IFabricPropertyManagementClient> propertyClient;
        HRESULT hrClient = CreateComFabricClient(
            1,
            &connectionStringItem,
            IID_IFabricPropertyManagementClient,
            propertyClient.VoidInitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        // ---------------------------------------------------------------------
        // IFabricPropertyManagementClient methods

        wstring invalidName(L"fabric://CreateName");
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginCreateName(invalidName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://DeleteName";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginDeleteName(invalidName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://NameExists";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginNameExists(invalidName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://EnumerateSubNames";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginEnumerateSubNames(invalidName.c_str(), NULL, false, timeout, callback, context);
            });

        invalidName = L"fabric://PutPropertyBinary";
        wstring propertyName(L"MyProperty");
        BYTE byteData(0);
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyBinary(invalidName.c_str(), propertyName.c_str(), 1, &byteData, timeout, callback, context);
            });

        invalidName = L"fabric://PutPropertyInt64";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyInt64(invalidName.c_str(), propertyName.c_str(), 0, timeout, callback, context);
            });

        invalidName = L"fabric://PutPropertyDouble";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyDouble(invalidName.c_str(), propertyName.c_str(), 0, timeout, callback, context);
            });

        invalidName = L"fabric://PutPropertyWString";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyWString(invalidName.c_str(), propertyName.c_str(), propertyName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://PutPropertyGuid";
        ::GUID guid;
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginPutPropertyGuid(invalidName.c_str(), propertyName.c_str(), &guid, timeout, callback, context);
            });

        invalidName = L"fabric://DeleteProperty";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginDeleteProperty(invalidName.c_str(), propertyName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://GetPropertyMetadata";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginGetPropertyMetadata(invalidName.c_str(), propertyName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://GetProperty";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginGetProperty(invalidName.c_str(), propertyName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://SubmitPropertyBatch";
        FABRIC_PROPERTY_BATCH_OPERATION batch; memset(&batch, 0, sizeof(batch));
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginSubmitPropertyBatch(invalidName.c_str(), 1, &batch, timeout, callback, context);
            });

        invalidName = L"fabric://EnumerateProperties";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return propertyClient->BeginEnumerateProperties(invalidName.c_str(), FALSE, NULL, timeout, callback, context);
            });

        // ---------------------------------------------------------------------
        // IFabricServiceManagementClient methods

        ComPointer<IFabricServiceManagementClient> serviceClient;
        hrClient = propertyClient->QueryInterface(IID_IFabricServiceManagementClient, (void**)serviceClient.InitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        FABRIC_SERVICE_DESCRIPTION service;
        FABRIC_STATEFUL_SERVICE_DESCRIPTION stateful;

        memset(&service, 0, sizeof(service));
        memset(&stateful, 0, sizeof(stateful));

        service.Kind = FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL;
        service.Value = &stateful;

        wstring typeName(L"AppType_App0:Package:Type");
        wstring validName(L"fabric:/CreateService.Application");
        invalidName = L"fabric://CreateService.Application";
        stateful.ApplicationName = invalidName.c_str();
        stateful.ServiceName = validName.c_str();
        stateful.ServiceTypeName = typeName.c_str();
        stateful.PartitionScheme = FABRIC_PARTITION_SCHEME_SINGLETON;
        stateful.InitializationData = NULL;
        stateful.InitializationDataSize = 0;
        stateful.TargetReplicaSetSize = 3;
        stateful.MinReplicaSetSize = 2;
        stateful.PlacementConstraints = NULL;
        stateful.CorrelationCount = 0;
        stateful.Correlations = NULL;
        stateful.MetricCount = 0;
        stateful.Metrics = NULL;
        stateful.HasPersistedState = TRUE;

        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return serviceClient->BeginCreateService(&service, timeout, callback, context);
            },
            [&](IFabricAsyncOperationContext *context) -> HRESULT{ return serviceClient->EndCreateService(context); });

        validName = L"fabric:/CreateService.Service";
        invalidName = L"fabric://CreateService.Service";
        stateful.ApplicationName = validName.c_str();
        stateful.ServiceName = invalidName.c_str();
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return serviceClient->BeginCreateService(&service, timeout, callback, context);
            },
            [&](IFabricAsyncOperationContext *context) -> HRESULT{ return serviceClient->EndCreateService(context); });

        validName = L"fabric:/CreateServiceFromTemplate";
        invalidName = L"fabric://CreateServiceFromTemplate";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return serviceClient->BeginCreateServiceFromTemplate(invalidName.c_str(), validName.c_str(), typeName.c_str(), 0, NULL, timeout, callback, context);
            });

        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return serviceClient->BeginCreateServiceFromTemplate(validName.c_str(), invalidName.c_str(), typeName.c_str(), 0, NULL, timeout, callback, context);
            });

        invalidName = L"fabric://DeleteService";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return serviceClient->BeginDeleteService(invalidName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://GetServiceDescription";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return serviceClient->BeginGetServiceDescription(invalidName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://ResolveService";
        FABRIC_PARTITION_KEY_TYPE keyType = FABRIC_PARTITION_KEY_TYPE_NONE;
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return serviceClient->BeginResolveServicePartition(invalidName.c_str(), keyType, NULL, NULL, timeout, callback, context);
            });

        // --------------------------------------------------------------------
        // IFabricApplicationManagementClient methods

        ComPointer<IFabricApplicationManagementClient> managementClient;
        hrClient = propertyClient->QueryInterface(IID_IFabricApplicationManagementClient, (void**)managementClient.InitializationAddress());
        CheckHRESULT(hrClient, S_OK);

        invalidName = L"fabric://CreateApplication";
        FABRIC_APPLICATION_DESCRIPTION application;
        memset(&application, 0, sizeof(application));
        application.ApplicationName = invalidName.c_str();
        application.ApplicationTypeName = typeName.c_str();
        application.ApplicationTypeVersion = typeName.c_str();
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return managementClient->BeginCreateApplication(&application, timeout, callback, context);
            },
            [&](IFabricAsyncOperationContext *context) -> HRESULT{ return managementClient->EndCreateApplication(context); });

        invalidName = L"fabric://UpgradeApplication";
        FABRIC_APPLICATION_UPGRADE_DESCRIPTION upgrade;
        memset(&upgrade, 0, sizeof(upgrade));
        FABRIC_ROLLING_UPGRADE_POLICY_DESCRIPTION policyDescription;
        memset(&policyDescription, 0, sizeof(policyDescription));
        policyDescription.RollingUpgradeMode = FABRIC_ROLLING_UPGRADE_MODE_UNMONITORED_AUTO;
        upgrade.ApplicationName = invalidName.c_str();
        upgrade.TargetApplicationTypeVersion = typeName.c_str();
        upgrade.UpgradeKind = FABRIC_APPLICATION_UPGRADE_KIND_ROLLING;
        upgrade.UpgradePolicyDescription = &policyDescription;

        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return managementClient->BeginUpgradeApplication(&upgrade, timeout, callback, context);
            },
            [&](IFabricAsyncOperationContext *context) -> HRESULT{ return managementClient->EndUpgradeApplication(context); });

        invalidName = L"fabric://GetApplicationUpgradeProgress";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return managementClient->BeginGetApplicationUpgradeProgress(invalidName.c_str(), timeout, callback, context);
            });

        invalidName = L"fabric://DeleteApplication";
        ExpectInvalidNameUriError([&](DWORD timeout, IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context) -> HRESULT
            {
                return managementClient->BeginDeleteApplication(invalidName.c_str(), timeout, callback, context);
            });
    }

    BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: gridgentoo/ServiceFabricAzure

max_issues_repo_name: gridgentoo/ServiceFabricAzure

max_forks_repo_name: gridgentoo/ServiceFabricAzure


text:
#ifndef __gautier_graphics_InteractiveRegion__
#define __gautier_graphics_InteractiveRegion__
#include <dlib/geometry.h>

#include <allegro5/allegro_color.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>

/*
	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 . Software distributed under the License is distributed on an "AS IS" BASIS, NO WARRANTIES OR CONDITIONS OF ANY KIND, explicit or implicit. See the License for details on permissions and limitations.
*/
namespace gautier {
        namespace graphics {
class InteractiveRegion {
        public:
        InteractiveRegion();

	using InteractionCallBackType = void(*)(int lineNumber);

        void SetInteractiveCallBack(InteractionCallBackType);

        void SetDimensions(double const& left, double const& top, double const& right, double const& bottom);
        void SetFont(ALLEGRO_FONT* font, int const& fontBoxX, int const& fontBoxY, int const& fontBoxW, int const& fontBoxH);

        void SetLineColorRGB(double const& r, double const& g, double const& b, double const& a);
        void SetLinePointSize(double const& size);
        void SetFillColorRGB(double const& r, double const& g, double const& b, double const& a);
        void SetTextColorRGB(double const& r, double const& g, double const& b, double const& a);

        void SetMouseChange(int const& mouseDirection, dlib::dpoint const& mousePosition);
        void SetMouseClick(bool const& leftButton, bool const& isDown, bool const& isUp, int const& mouseDirection, dlib::dpoint const& mousePosition);

        void SetData(std::vector<std::string>& data);
        void SetIsMultiline(bool const& isMultiline);

        bool GetIsVisualsSet();
        bool GetIsDataSet();

        double Left();
        double Top();
        double Right();
        double Bottom();

        void RenderSelf();

        private:
        void UpdateScrollTrack(const double& top);
        void RenderText();

        InteractionCallBackType
                _InteractionCallBack;

        dlib::drectangle
                _RegionDimensions, _ScrollDimensionsV;

        dlib::dpoint
                _MousePosition, _MousePositionLast;

        ALLEGRO_COLOR
                _LineColor, _FillColor, _TextColor,
                _ScrollBarFillColor, _ScrollBarTrackColor, _ScrollBarLineColor;

        ALLEGRO_FONT const*
                _Font;

        int
                _FontBoxX, _FontBoxY, _FontBoxW, _FontBoxH,
                _VisibleTextIndexStart;

        double
                _LinePointSize, _ScrollTrackYTop, _ScrollTrackYBottom,
                _ScrollY, _ScrollYText;
        int
                _MouseDirection;

        bool
                _IsVisualsSet, _IsDataSet, _IsMultiline;

        std::vector<std::string>
                _Data;
};
        }
}
#endif

ext: hxx


text:
/// \file   indication.hpp
///
/// \brief
///
/// \authors    Maarten P. Scholl
/// \date       2019-10-08
/// \copyright  Copyright 2017-2019 The Institute for New Economic Thinking,
///             Oxford Martin School, University of Oxford
///
///             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.
///
///             You may obtain instructions to fulfill the attribution
///             requirements in CITATION.cff
///
#ifndef ESL_INDICATION_HPP
#define ESL_INDICATION_HPP

#include <cstdint>

namespace esl::economics::markets {
    ///
    /// \brief  Denotes whether or not a quote that is sent is binding for
    ///         the sender, meaning that the sender must deliver at the quote
    ///         if the recipient accepts the offer.
    ///
    enum indication
    : std::uint8_t
    {
        firm,
        indicative
    };

}  // namespace esl::economics::markets

#ifdef WITH_MPI
#include <boost/mpi/datatype.hpp>
namespace boost::mpi {
    template<>
    struct is_mpi_datatype<esl::economics::markets::indication>
    : public mpl::true_
    {

    };
}  // namespace boost::mpi
#endif  // WITH_MPI

#endif  // ESL_INDICATION_HPP

max_stars_repo_name: rht/ESL

max_issues_repo_name: rht/ESL

max_forks_repo_name: vishalbelsare/ESL


text:
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdexcept>
#include <functional>
#include <random>
#include <Eigen/Geometry>
#include <visualization_msgs/Marker.h>
#include "arc_utilities/eigen_helpers.hpp"
#include "arc_utilities/eigen_helpers_conversions.hpp"
#include "arc_utilities/pretty_print.hpp"
#include "arc_utilities/voxel_grid.hpp"
#include "arc_utilities/simple_rrt_planner.hpp"
#include "uncertainty_planning_core/simple_pid_controller.hpp"
#include "uncertainty_planning_core/simple_uncertainty_models.hpp"
#include "uncertainty_planning_core/uncertainty_contact_planning.hpp"
#include "uncertainty_planning_core/simple_robot_models.hpp"
#include "uncertainty_planning_core/simple_samplers.hpp"
#include "uncertainty_planning_core/uncertainty_planning_core.hpp"
#include "fast_kinematic_simulator/fast_kinematic_simulator.hpp"
#include "fast_kinematic_simulator/simulator_environment_builder.hpp"
#include "uncertainty_planning_examples/config_common.hpp"

#ifndef BAXTER_LINKED_COMMON_CONFIG_HPP
#define BAXTER_LINKED_COMMON_CONFIG_HPP

namespace baxter_linked_common_config
{
    typedef simple_robot_models::SimpleJointModel SJM;
    typedef simple_robot_models::SimpleLinkedConfiguration SLC;

    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetDefaultOptions()
    {
        uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS options;
        options.clustering_type = uncertainty_contact_planning::CONVEX_REGION_SIGNATURE;
        options.planner_time_limit = 600.0;
        options.goal_bias = 0.15;
        options.step_size = 1.0;
        options.step_duration = 10.0;
        options.goal_probability_threshold = 0.51;
        options.goal_distance_threshold = 0.15; // 0.05;
        options.connect_after_first_solution = 0.25;
        options.signature_matching_threshold = 0.1;
        options.distance_clustering_threshold = M_PI_2;
        options.feasibility_alpha = 0.75;
        options.variance_alpha = 0.75;
        options.edge_attempt_count = 50u;
        options.num_particles = 1u;
        options.use_contact = true;
        options.use_reverse = true;
        options.use_spur_actions = true;
        options.max_exec_actions = 1000u;
        options.max_policy_exec_time = 300.0;
        options.num_policy_simulations = 1u;
        options.num_policy_executions = 1u;
        options.policy_action_attempt_count = 100u;
        options.debug_level = 0u;
        options.planner_log_file = "/tmp/baxter_planner_log.txt";
        options.policy_log_file = "/tmp/baxter_policy_log.txt";
        options.planned_policy_file = "/tmp/baxter_planned_policy.policy";
        options.executed_policy_file = "/dev/null";
        return options;
    }

    inline uncertainty_planning_core::PLANNING_AND_EXECUTION_OPTIONS GetOptions()
    {
        return uncertainty_planning_core::GetOptions(GetDefaultOptions());
    }

    inline config_common::TASK_CONFIG_PARAMS GetDefaultExtraOptions()
    {
        return config_common::TASK_CONFIG_PARAMS(0.03125, 25.0, 0.0, 0.0, "baxter_blocked_test_mod_env");
    }

    inline config_common::TASK_CONFIG_PARAMS GetExtraOptions()
    {
        return config_common::GetOptions(GetDefaultExtraOptions());
    }

    inline simple_robot_models::LINKED_ROBOT_CONFIG GetDefaultRobotConfig(const config_common::TASK_CONFIG_PARAMS& options)
    {
        const double env_resolution = options.environment_resolution;
        const double kp = 1.1;
        const double ki = 0.0;
        const double kd = 0.1;
        const double i_clamp = 0.0;
        const double velocity_limit = env_resolution * 2.0;
        const double max_sensor_noise = options.sensor_error;
        const double max_actuator_noise = options.actuator_error;
        const simple_robot_models::LINKED_ROBOT_CONFIG robot_config(kp, ki, kd, i_clamp, velocity_limit, max_sensor_noise, max_actuator_noise);
        return robot_config;
    }

    inline Eigen::Isometry3d GetBaseTransform()
    {
        const Eigen::Isometry3d base_transform = Eigen::Translation3d(0.0, 0.0, 0.0) * Eigen::Quaterniond(Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitZ()));
        return base_transform;
    }

    inline SLC MakeBaxterLeftArmConfiguration(const std::vector<double>& joint_values)
    {
        assert(joint_values.size() == 7);
        SLC left_arm_configuration(7);
        const double left_s0 = joint_values[0];
        left_arm_configuration[0] = SJM(std::pair<double, double>(-1.70167993878, 1.70167993878), left_s0, SJM::REVOLUTE); // left_s0
        const double left_s1 = joint_values[1];
        left_arm_configuration[1] = SJM(std::pair<double, double>(-2.147, 1.047), left_s1, SJM::REVOLUTE); // left_s1
        const double left_e0 = joint_values[2];
        left_arm_configuration[2] = SJM(std::pair<double, double>(-3.05417993878, 3.05417993878), left_e0, SJM::REVOLUTE); // left_e0
        const double left_e1 = joint_values[3];
        left_arm_configuration[3] = SJM(std::pair<double, double>(-0.05, 2.618), left_e1, SJM::REVOLUTE); // left_e1
        const double left_w0 = joint_values[4];
        left_arm_configuration[4] = SJM(std::pair<double, double>(-3.059, 3.059), left_w0, SJM::REVOLUTE); // left_w0
        const double left_w1 = joint_values[5];
        left_arm_configuration[5] = SJM(std::pair<double, double>(-1.57079632679, 2.094), left_w1, SJM::REVOLUTE); // left_w1
        const double left_w2 = joint_values[6];
        left_arm_configuration[6] = SJM(std::pair<double, double>(-3.059, 3.059), left_w2, SJM::REVOLUTE); // left_w2
        return left_arm_configuration;
    }

    inline SLC MakeBaxterRightArmConfiguration(const std::vector<double>& joint_values)
    {
        assert(joint_values.size() == 7);
        SLC right_arm_configuration(7);
        const double right_s0 = joint_values[0];
        right_arm_configuration[0] = SJM(std::pair<double, double>(-1.70167993878, 1.70167993878), right_s0, SJM::REVOLUTE); // right_s0
        const double right_s1 = joint_values[1];
        right_arm_configuration[1] = SJM(std::pair<double, double>(-2.147, 1.047), right_s1, SJM::REVOLUTE); // right_s1
        const double right_e0 = joint_values[2];
        right_arm_configuration[2] = SJM(std::pair<double, double>(-3.05417993878, 3.05417993878), right_e0, SJM::REVOLUTE); // right_e0
        const double right_e1 = joint_values[3];
        right_arm_configuration[3] = SJM(std::pair<double, double>(-0.05, 2.618), right_e1, SJM::REVOLUTE); // right_e1
        const double right_w0 = joint_values[4];
        right_arm_configuration[4] = SJM(std::pair<double, double>(-3.059, 3.059), right_w0, SJM::REVOLUTE); // right_w0
        const double right_w1 = joint_values[5];
        right_arm_configuration[5] = SJM(std::pair<double, double>(-1.57079632679, 2.094), right_w1, SJM::REVOLUTE); // right_w1
        const double right_w2 = joint_values[6];
        right_arm_configuration[6] = SJM(std::pair<double, double>(-3.059, 3.059), right_w2, SJM::REVOLUTE); // right_w2
        return right_arm_configuration;
    }

    inline std::pair<SLC, SLC> GetStartAndGoal()
    {
        // Define the goals of the plan
        const SLC goal = MakeBaxterRightArmConfiguration(std::vector<double>{0.5821457090025145, -0.27496605622846043, 0.016490293469768196, 1.1508690861110316, -0.24045148850103862, -0.89, 0.06366020269724466});
        const SLC start = MakeBaxterRightArmConfiguration(std::vector<double>{0.119267, 1.047, -0.27535, -0.05, -1.29315, -1.218, -0.29184});
        return std::make_pair(start, goal);
    }

    inline SLC GetReferenceConfiguration()
    {
        const SLC reference_configuration = MakeBaxterRightArmConfiguration(std::vector<double>{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0});
        return reference_configuration;
    }

    inline std::vector<double> GetJointUncertaintyParams(const config_common::TASK_CONFIG_PARAMS& options)
    {
        const std::vector<double> uncertainty_params(7, options.actuator_error);
        return uncertainty_params;
    }

    inline std::vector<double> GetJointDistanceWeights()
    {
        const std::vector<double> max_velocities = {0.27, 0.27, 0.27, 0.27, 0.3, 0.3, 0.5};
        std::vector<double> distance_weights(max_velocities.size(), 0.0);
        for (size_t idx = 0; idx < max_velocities.size(); idx++)
        {
            distance_weights[idx] = 1.0 / max_velocities[idx];
        }
        return distance_weights;
    }

    inline void GetEndEffectorPoints(simple_robot_models::RobotLink& end_effector_link, const std::string& environment_id)
    {
        if (environment_id == "baxter_wrist_key_env")
        {
            // Key
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.175, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.2, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.225, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.25, 1.0));
            //
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.275, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.3, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.325, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.35, 1.0));
            //
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.025, 0.275, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.025, 0.3, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.025, 0.325, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.025, 0.35, 1.0));
            //
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.05, 0.275, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.05, 0.3, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.05, 0.325, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.05, 0.35, 1.0));
            //
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.075, 0.275, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.075, 0.3, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.075, 0.325, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.075, 0.35, 1.0));
            //
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.275, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.3, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.325, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.35, 1.0));
            //
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.275, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.3, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.325, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.35, 1.0));
            //
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.075, 0.0, 0.275, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.075, 0.0, 0.3, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.075, 0.0, 0.325, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.075, 0.0, 0.35, 1.0));
        }
        else if (environment_id == "baxter_blocked_test_env")
        {
            // Peg
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.175, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.2, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.225, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.24, 1.0));
        }
        else
        {
            // Peg
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.175, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.2, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.225, 1.0));
            end_effector_link.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.25, 1.0));
        }
    }

    typedef uncertainty_planning_core::LinkedActuatorModel BaxterJointActuatorModel;

    inline simple_robot_models::SimpleLinkedRobot<BaxterJointActuatorModel> GetRobot(const Eigen::Isometry3d& base_transform, const simple_robot_models::LINKED_ROBOT_CONFIG& joint_config, const std::vector<double>& joint_uncertainty_params, const std::vector<double>& joint_distance_weights, const std::string& environment_id)
    {
        const double s0_noise = joint_uncertainty_params[0];
        const double s1_noise = joint_uncertainty_params[1];
        const double e0_noise = joint_uncertainty_params[2];
        const double e1_noise = joint_uncertainty_params[3];
        const double w0_noise = joint_uncertainty_params[4];
        const double w1_noise = joint_uncertainty_params[5];
        const double w2_noise = joint_uncertainty_params[6];
        // Make the reference configuration
        const SLC reference_configuration = GetReferenceConfiguration();
        // Make the robot model
        simple_robot_models::RobotLink torso;
        torso.link_name = "torso";
        torso.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, 0.025, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.025, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.025, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.05, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.075, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.1, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.125, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.15, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.175, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.2, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.225, 0.0, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.225, 0.025, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.225, 0.05, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.225, 0.075, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.0, -0.225, 0.1, 1.0));
        torso.link_points->push_back(Eigen::Vector4d(0.025, -0.225, 0.1, 1.0));
        simple_robot_models::RobotLink right_arm_mount;
        right_arm_mount.link_name = "right_arm_mount";
        right_arm_mount.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_arm_mount.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.0, 1.0));
        right_arm_mount.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.0, 1.0));
        simple_robot_models::RobotLink right_upper_shoulder;
        right_upper_shoulder.link_name = "right_upper_shoulder";
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.025, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.05, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.075, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.1, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.125, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.15, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.175, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.2, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.225, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.25, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.275, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.275, 1.0));
        right_upper_shoulder.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.275, 1.0));
        simple_robot_models::RobotLink right_lower_shoulder;
        right_lower_shoulder.link_name = "right_lower_shoulder";
        right_lower_shoulder.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_lower_shoulder.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.0, 1.0));
        right_lower_shoulder.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.0, 1.0));
        right_lower_shoulder.link_points->push_back(Eigen::Vector4d(0.075, 0.0, 0.0, 1.0));
        right_lower_shoulder.link_points->push_back(Eigen::Vector4d(0.1, 0.0, 0.0, 1.0));
        simple_robot_models::RobotLink right_upper_elbow;
        right_upper_elbow.link_name = "right_upper_elbow";
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.025, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.05, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.075, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.1, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.125, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.15, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.175, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.2, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.225, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.25, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.25, 1.0));
        right_upper_elbow.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.25, 1.0));
        simple_robot_models::RobotLink right_lower_elbow;
        right_lower_elbow.link_name = "right_lower_elbow";
        right_lower_elbow.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_lower_elbow.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.0, 1.0));
        right_lower_elbow.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.0, 1.0));
        right_lower_elbow.link_points->push_back(Eigen::Vector4d(0.075, 0.0, 0.0, 1.0));
        right_lower_elbow.link_points->push_back(Eigen::Vector4d(0.1, 0.0, 0.0, 1.0));
        simple_robot_models::RobotLink right_upper_forearm;
        right_upper_forearm.link_name = "right_upper_forearm";
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.025, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.05, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.075, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.1, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.125, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.15, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.175, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.2, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.225, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.25, 1.0));
        right_upper_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.275, 1.0));
        simple_robot_models::RobotLink right_lower_forearm;
        right_lower_forearm.link_name = "right_lower_forearm";
        right_lower_forearm.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_lower_forearm.link_points->push_back(Eigen::Vector4d(0.025, 0.0, 0.0, 1.0));
        right_lower_forearm.link_points->push_back(Eigen::Vector4d(0.05, 0.0, 0.0, 1.0));
        right_lower_forearm.link_points->push_back(Eigen::Vector4d(0.075, 0.0, 0.0, 1.0));
        right_lower_forearm.link_points->push_back(Eigen::Vector4d(0.1, 0.0, 0.0, 1.0));
        right_lower_forearm.link_points->push_back(Eigen::Vector4d(0.125, 0.0, 0.0, 1.0));
        simple_robot_models::RobotLink right_wrist;
        right_wrist.link_name = "right_wrist";
        right_wrist.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));
        right_wrist.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.025, 1.0));
        right_wrist.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.05, 1.0));
        right_wrist.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.075, 1.0));
        right_wrist.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.1, 1.0));
        right_wrist.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.125, 1.0));
        right_wrist.link_points->push_back(Eigen::Vector4d(0.0, 0.0, 0.15, 1.0));
        // Get the end of the wrist/EE shape
        GetEndEffectorPoints(right_wrist, environment_id);
        const std::vector<simple_robot_models::RobotLink> links = {torso, right_arm_mount, right_upper_shoulder, right_lower_shoulder, right_upper_elbow, right_lower_elbow, right_upper_forearm, right_lower_forearm, right_wrist};
        const std::vector<std::pair<size_t, size_t>> allowed_self_collisions = {std::pair<size_t, size_t>(0, 1), std::pair<size_t, size_t>(1, 2), std::pair<size_t, size_t>(2, 3), std::pair<size_t, size_t>(3, 4), std::pair<size_t, size_t>(4, 5), std::pair<size_t, size_t>(5, 6), std::pair<size_t, size_t>(6, 7), std::pair<size_t, size_t>(7, 8)};
        // right_s0
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_arm_mount_joint;
        right_arm_mount_joint.name = "right_arm_mount_joint";
        right_arm_mount_joint.parent_link_index = 0;
        right_arm_mount_joint.child_link_index = 1;
        right_arm_mount_joint.joint_axis = Eigen::Vector3d::UnitZ();
        right_arm_mount_joint.joint_transform = Eigen::Translation3d(0.024645, -0.219645, 0.118588) * EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, -0.7854);
        right_arm_mount_joint.joint_model = SJM(std::make_pair(0.0, 0.0), 0.0, SJM::FIXED);
        // We don't need an uncertainty model for a fixed joint
        right_arm_mount_joint.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(joint_config);
        // right_s0
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_s0;
        right_s0.name = "right_s0";
        right_s0.parent_link_index = 1;
        right_s0.child_link_index = 2;
        right_s0.joint_axis = Eigen::Vector3d::UnitZ();
        right_s0.joint_transform = Eigen::Translation3d(0.055695, 0.0, 0.011038) * EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, 0.0);
        right_s0.joint_model = reference_configuration[0];
        const BaxterJointActuatorModel right_s0_joint_model(std::abs(s0_noise), 0.5);
        simple_robot_models::LINKED_ROBOT_CONFIG s0_config = joint_config;
        s0_config.velocity_limit = 0.27 * 0.75;
        right_s0.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(s0_config, right_s0_joint_model);
        // Base pitch
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_s1;
        right_s1.name = "right_s1";
        right_s1.parent_link_index = 2;
        right_s1.child_link_index = 3;
        right_s1.joint_axis = Eigen::Vector3d::UnitZ();
        right_s1.joint_transform = Eigen::Translation3d(0.069, 0.0, 0.27035) * EigenHelpers::QuaternionFromUrdfRPY(-1.57079632679, 0.0, 0.0);
        right_s1.joint_model = reference_configuration[1];
        const BaxterJointActuatorModel right_s1_joint_model(std::abs(s1_noise), 0.5);
        simple_robot_models::LINKED_ROBOT_CONFIG s1_config = joint_config;
        s1_config.velocity_limit = 0.27 * 0.75;
        right_s1.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(s1_config, right_s1_joint_model);
        // Elbow pitch
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_e0;
        right_e0.name = "right_e0";
        right_e0.parent_link_index = 3;
        right_e0.child_link_index = 4;
        right_e0.joint_axis = Eigen::Vector3d::UnitZ();
        right_e0.joint_transform = Eigen::Translation3d(0.102, 0.0, 0.0) * EigenHelpers::QuaternionFromUrdfRPY(1.57079632679, 0.0, 1.57079632679);
        right_e0.joint_model = reference_configuration[2];
        const BaxterJointActuatorModel right_e0_joint_model(std::abs(e0_noise), 0.5);
        simple_robot_models::LINKED_ROBOT_CONFIG e0_config = joint_config;
        e0_config.velocity_limit = 0.27 * 0.75;
        right_e0.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(e0_config, right_e0_joint_model);
        // Elbow roll
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_e1;
        right_e1.name = "right_e1";
        right_e1.parent_link_index = 4;
        right_e1.child_link_index = 5;
        right_e1.joint_axis = Eigen::Vector3d::UnitZ();
        right_e1.joint_transform = Eigen::Translation3d(0.069, 0.0, 0.26242) * EigenHelpers::QuaternionFromUrdfRPY(-1.57079632679, -1.57079632679, 0.0);
        right_e1.joint_model = reference_configuration[3];
        const BaxterJointActuatorModel right_e1_joint_model(std::abs(e1_noise), 0.5);
        simple_robot_models::LINKED_ROBOT_CONFIG e1_config = joint_config;
        e1_config.velocity_limit = 0.27 * 0.75;
        right_e1.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(e1_config, right_e1_joint_model);
        // Wrist pitch
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_w0;
        right_w0.name = "right_w0";
        right_w0.parent_link_index = 5;
        right_w0.child_link_index = 6;
        right_w0.joint_axis = Eigen::Vector3d::UnitZ();
        right_w0.joint_transform = Eigen::Translation3d(0.10359, 0.0, 0.0) * EigenHelpers::QuaternionFromUrdfRPY(1.57079632679, 0.0, 1.57079632679);
        right_w0.joint_model = reference_configuration[4];
        const BaxterJointActuatorModel right_w0_joint_model(std::abs(w0_noise), 1.0);
        simple_robot_models::LINKED_ROBOT_CONFIG w0_config = joint_config;
        w0_config.velocity_limit = 0.3 * 0.75;
        right_w0.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(w0_config, right_w0_joint_model);
        // Wrist roll
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_w1;
        right_w1.name = "right_w1";
        right_w1.parent_link_index = 6;
        right_w1.child_link_index = 7;
        right_w1.joint_axis = Eigen::Vector3d::UnitZ();
        right_w1.joint_transform = Eigen::Translation3d(0.01, 0.0, 0.2707) * EigenHelpers::QuaternionFromUrdfRPY(-1.57079632679, -1.57079632679, 0.0);
        right_w1.joint_model = reference_configuration[5];
        const BaxterJointActuatorModel right_w1_joint_model(std::abs(w1_noise), 1.0);
        simple_robot_models::LINKED_ROBOT_CONFIG w1_config = joint_config;
        w1_config.velocity_limit = 0.3 * 0.75;
        right_w1.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(w1_config, right_w1_joint_model);
        // Wrist roll
        simple_robot_models::RobotJoint<BaxterJointActuatorModel> right_w2;
        right_w2.name = "right_w2";
        right_w2.parent_link_index = 7;
        right_w2.child_link_index = 8;
        right_w2.joint_axis = Eigen::Vector3d::UnitZ();
        right_w2.joint_transform = Eigen::Translation3d(0.115975, 0.0, 0.0) * EigenHelpers::QuaternionFromUrdfRPY(1.57079632679, 0.0, 1.57079632679);
        right_w2.joint_model = reference_configuration[6];
        const BaxterJointActuatorModel right_w2_joint_model(std::abs(w2_noise), 1.0);
        simple_robot_models::LINKED_ROBOT_CONFIG w2_config = joint_config;
        w2_config.velocity_limit = 0.5 * 0.75;
        right_w2.joint_controller = simple_robot_models::JointControllerGroup<BaxterJointActuatorModel>(w2_config, right_w2_joint_model);
        const std::vector<simple_robot_models::RobotJoint<BaxterJointActuatorModel>> joints = {right_arm_mount_joint, right_s0, right_s1, right_e0, right_e1, right_w0, right_w1, right_w2};
        const simple_robot_models::SimpleLinkedRobot<BaxterJointActuatorModel> robot(base_transform, links, joints, allowed_self_collisions, reference_configuration, joint_distance_weights);
        return robot;
    }

    inline uncertainty_planning_core::LinkedSamplerPtr GetSampler()
    {
        // Make the sampler
        const SLC reference_configuration = GetReferenceConfiguration();
        return uncertainty_planning_core::LinkedSamplerPtr(new simple_samplers::SimpleLinkedBaseSampler<uncertainty_planning_core::PRNG>(reference_configuration));
    }

    inline uncertainty_planning_core::LinkedSimulatorPtr GetSimulator(const config_common::TASK_CONFIG_PARAMS& options, const int32_t debug_level)
    {
        const simulator_environment_builder::EnvironmentComponents environment_components = simulator_environment_builder::BuildCompleteEnvironment(options.environment_id, options.environment_resolution);
        const fast_kinematic_simulator::SolverParameters solver_params = fast_kinematic_simulator::GetDefaultSolverParameters();
        return fast_kinematic_simulator::MakeLinkedSimulator(environment_components.GetEnvironment(), environment_components.GetEnvironmentSDF(), environment_components.GetSurfaceNormalsGrid(), solver_params, options.simulation_controller_frequency, debug_level);
    }
}

#endif // BAXTER_LINKED_COMMON_CONFIG_HPP


text:
//
// Copyright 2013 Christian Henning
//
// 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 BOOST_GIL_EXTENSION_IO_RAW_HPP
#define BOOST_GIL_EXTENSION_IO_RAW_HPP

#include <boost/gil/extension/io/raw/read.hpp>

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>

// https://www.seehuhn.de/pages/matrixfn.html
#include <iostream>
#include <Eigen/Dense>
// #include "floatvectormatcher.hpp"

using namespace Eigen;

static const int N = 7;

TEST_CASE( "Column mean")
{
    MatrixXi m(3,3);
    m << 1,2,3,
         4,5,6,
         7,8,9;

    CHECK( m.col(1).mean() == 5.0);
}

TEST_CASE( "Simple eigen square root" )
{
    std::vector<double> mbuf(N*N);
    std::vector<double> mdbuf(N*N);
    Map<MatrixXd> m(mbuf.data(), N,N);
    Map<MatrixXd> md(mdbuf.data(),N,N);

    m = MatrixXd::Zero(N, N);

    m.diagonal(1).setConstant(-1);
    m.diagonal(-1).setConstant(-1);
    m.diagonal().setConstant(2);
    m(0, 0) = 1;
    m(N - 1, N - 1) = 1;

    std::cout << "Here is the matrix m:" << std::endl
         << m << std::endl;

    JacobiSVD<MatrixXd> svd(m, ComputeFullU);
    auto D = svd.singularValues().array().sqrt().matrix().asDiagonal();
    auto U = svd.matrixU();

    // SelfAdjointEigenSolver<MatrixXd> svd(m);
    // auto D = svd.eigenvalues().array().sqrt().matrix().asDiagonal();
    // auto U = svd.eigenvectors();

    auto d = U * D * U.transpose();
    md  = d * d;
    std::cout << "Here is the result of d * d" << std::endl;
    std::cout << md << std::endl;
    const auto expected = Catch::Matchers::Approx(mdbuf).margin(1e-10);
    CHECK_THAT( mbuf, expected );

}

max_stars_repo_name: diyabc/abcranger

max_issues_repo_name: vitorpavinato/abcranger

max_forks_repo_name: fradav/abcranger


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

    @copyright 2016 NumScale SAS

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

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

  /*!

    @ingroup group-hyperbolic
    This function object returns the hyperbolic secant: \f$1/\cosh(x)\f$.

    @see cosh, sinh, tanh, csch, sinhcosh

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

    @par Example:

      @snippet sech.cpp sech

    @par Possible output:

      @snippet sech.txt sech

  **/
  IEEEValue sech(IEEEValue const& x);
} }
#endif

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

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#pragma once

#include "indexer/feature_data.hpp"
#include "indexer/ftypes_mapping.hpp"

#include "coding/csv_reader.hpp"

#include "platform/platform.hpp"

#include "base/assert.hpp"
#include "base/logging.hpp"

#include <array>
#include <cstdint>
#include <initializer_list>
#include <sstream>
#include <string>
#include <utility>

#include <boost/optional.hpp>

namespace ftraits
{
template <typename Base, typename Value>
class TraitsBase
{
public:
  static boost::optional<Value> GetValue(feature::TypesHolder const & types)
  {
    auto const & instance = Instance();
    auto const it = Find(types);
    if (!instance.m_matcher.IsValid(it))
      return boost::none;

    return it->second;
  }

  static boost::optional<uint32_t> GetType(feature::TypesHolder const & types)
  {
    auto const & instance = Instance();
    auto const it = Find(types);
    if (!instance.m_matcher.IsValid(it))
      return boost::none;

    return it->first;
  }

private:
  using ConstIterator = typename ftypes::HashMapMatcher<uint32_t, Value>::ConstIterator;

  static ConstIterator Find(feature::TypesHolder const & types)
  {
    auto const & instance = Instance();

    auto const excluded = instance.m_excluded.Find(types);
    if (instance.m_excluded.IsValid(excluded))
      return instance.m_matcher.End();

    return instance.m_matcher.Find(types);
  }

protected:
  static TraitsBase const & Instance()
  {
    static Base instance;
    return instance;
  }

  ftypes::HashMapMatcher<uint32_t, Value> m_matcher;
  ftypes::HashSetMatcher<uint32_t> m_excluded;
};

enum UGCType
{
  UGCTYPE_NONE = 0u,
  UGCTYPE_RATING = 1u << 0,   // 1
  UGCTYPE_REVIEWS = 1u << 1,  // 2
  UGCTYPE_DETAILS = 1u << 2   // 4
};

using UGCTypeMask = unsigned;
using UGCRatingCategories = std::vector<std::string>;

struct UGCItem
{
  UGCItem() {}
  UGCItem(UGCTypeMask m, UGCRatingCategories && c)
    : m_mask(m), m_categories(std::move(c))
  {
  }

  UGCTypeMask m_mask = UGCTYPE_NONE;
  UGCRatingCategories m_categories;
};

class UGC : public TraitsBase<UGC, UGCItem>
{
  friend class TraitsBase;

  std::array<UGCType, 3> const m_masks = {{UGCTYPE_RATING, UGCTYPE_REVIEWS, UGCTYPE_DETAILS}};

  UGC()
  {
    coding::CSVReader reader;
    auto const fileReader = GetPlatform().GetReader("ugc_types.csv");
    reader.Read(*fileReader, [this](coding::CSVReader::Row const & row) {
      size_t constexpr kTypePos = 0;
      size_t constexpr kCategoriesPos = 4;

      ASSERT_EQUAL(row.size(), 5, ());

      UGCItem item(ReadMasks(row), ParseByWhitespaces(row[kCategoriesPos]));
      auto typePath = ParseByDashes(row[kTypePos]);

      if (IsUGCAvailable(item.m_mask))
        m_matcher.AppendType(std::move(typePath), std::move(item));
      else
        m_excluded.AppendType(std::move(typePath));
    });
  }

  UGCTypeMask ReadMasks(coding::CSVReader::Row const & row)
  {
    size_t constexpr kMasksBegin = 1;
    size_t constexpr kMasksEnd = 4;

    UGCTypeMask maskType = UGCTYPE_NONE;
    for (size_t i = kMasksBegin; i < kMasksEnd; i++)
    {
      int flag;
      if (!strings::to_int(row[i], flag))
      {
        LOG(LERROR, ("File ugc_types.csv must contain a bit mask of supported ugc traits!"));
        return UGCTYPE_NONE;
      }

      if (flag)
        maskType |= m_masks[i - 1];
    }

    return maskType;
  }

  std::vector<std::string> ParseByWhitespaces(std::string const & str)
  {
    std::istringstream iss(str);
    return {std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>()};
  }

  std::vector<std::string> ParseByDashes(std::string const & str)
  {
    std::vector<std::string> result;
    std::istringstream iss(str);
    for (std::string tmp; std::getline(iss,  tmp, '-'); )
      result.push_back(tmp);

    return result;
  }

public:
  static bool IsUGCAvailable(UGCTypeMask mask) { return mask != UGCTYPE_NONE; }
  static bool IsRatingAvailable(UGCTypeMask mask) { return mask & UGCTYPE_RATING; }
  static bool IsReviewsAvailable(UGCTypeMask mask) { return mask & UGCTYPE_REVIEWS; }
  static bool IsDetailsAvailable(UGCTypeMask mask) { return mask & UGCTYPE_DETAILS; }

  static bool IsUGCAvailable(feature::TypesHolder const & types)
  {
    auto const opt = GetValue(types);
    return opt ? IsUGCAvailable(opt->m_mask) : false;
  }
  static bool IsRatingAvailable(feature::TypesHolder const & types)
  {
    auto const opt = GetValue(types);
    return opt ? IsRatingAvailable(opt->m_mask) : false;
  }
  static bool IsReviewsAvailable(feature::TypesHolder const & types)
  {
    auto const opt = GetValue(types);
    return opt ? IsReviewsAvailable(opt->m_mask) : false;
  }
  static bool IsDetailsAvailable(feature::TypesHolder const & types)
  {
    auto const opt = GetValue(types);
    return opt ? IsDetailsAvailable(opt->m_mask) : false;
  }
  static UGCRatingCategories GetCategories(feature::TypesHolder const & types)
  {
    auto const opt = GetValue(types);
    if (opt)
      return opt->m_categories;
    return {};
  }
};

enum class WheelchairAvailability
{
  No,
  Yes,
  Limited
};

inline std::string DebugPrint(WheelchairAvailability wheelchair)
{
  switch (wheelchair)
  {
  case WheelchairAvailability::No: return "No";
  case WheelchairAvailability::Yes: return "Yes";
  case WheelchairAvailability::Limited: return "Limited";
  }
  UNREACHABLE();
}

class Wheelchair : public TraitsBase<Wheelchair, WheelchairAvailability>
{
  friend class TraitsBase;

  using TypesInitializer = std::initializer_list<std::initializer_list<char const *>>;

  Wheelchair()
  {
    m_matcher.Append<TypesInitializer>({{"wheelchair", "no"}}, WheelchairAvailability::No);
    m_matcher.Append<TypesInitializer>({{"wheelchair", "yes"}}, WheelchairAvailability::Yes);
    m_matcher.Append<TypesInitializer>({{"wheelchair", "limited"}},
                                       WheelchairAvailability::Limited);
  }
};

}  // namespace ftraits

max_stars_repo_name: ToshUxanoff/omim

max_issues_repo_name: MohammadMoeinfar/omim

max_forks_repo_name: vmihaylenko/omim