<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <memory>
#include <string>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/system/DiscoveryProxy.h"
#include "joynr/Settings.h"
#include "joynr/types/Version.h"
#include "joynr/system/RoutingTypes/MqttAddress.h"
#include "joynr/system/RoutingTypes/ChannelAddress.h"
#include "joynr/serializer/Serializer.h"

#include "tests/JoynrTest.h"
#include "tests/utils/MockObjects.h"

using namespace joynr;

class SystemServicesDiscoveryTest : public ::testing::Test {
public:
    std::string settingsFilename;
    std::unique_ptr<Settings> settings;
    std::string discoveryDomain;
    std::string discoveryProviderParticipantId;
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverHttp;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt;
    std::shared_ptr<ITransportMessageSender> mockMessageSenderMqtt;
    DiscoveryQos discoveryQos;
    std::shared_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder;
    std::shared_ptr<joynr::system::DiscoveryProxy> discoveryProxy;
    std::int64_t lastSeenDateMs;
    std::int64_t expiryDateMs;
    std::string publicKeyId;

    SystemServicesDiscoveryTest() :
        settingsFilename("test-resources/SystemServicesDiscoveryTest.settings"),
        settings(std::make_unique<Settings>(settingsFilename)),
        discoveryDomain(),
        discoveryProviderParticipantId(),
        runtime(nullptr),
        mockMessageReceiverHttp(std::make_shared<MockTransportMessageReceiver>()),
        mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()),
        mockMessageSenderMqtt(std::make_shared<MockTransportMessageSender>()),
        discoveryQos(),
        discoveryProxyBuilder(nullptr),
        discoveryProxy(nullptr),
        lastSeenDateMs(-1),
        expiryDateMs(-1),
        publicKeyId("")
    {
        SystemServicesSettings systemSettings(*settings);
        systemSettings.printSettings();
        discoveryDomain = systemSettings.getDomain();
        discoveryProviderParticipantId = systemSettings.getCcDiscoveryProviderParticipantId();

        discoveryQos.setCacheMaxAgeMs(1000);
        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
        discoveryQos.addCustomParameter("fixedParticipantId", discoveryProviderParticipantId);
        discoveryQos.setDiscoveryTimeoutMs(50);

        std::string httpChannelId("http_SystemServicesDiscoveryTest.ChannelId");
        std::string httpEndPointUrl("http_SystemServicesRoutingTest.endPointUrl");
        std::string mqttTopic("mqtt_SystemServicesRoutingTest.topic");
        std::string mqttBrokerUrl("mqtt_SystemServicesRoutingTest.brokerUrl");

        using system::RoutingTypes::ChannelAddress;
        using system::RoutingTypes::MqttAddress;

        std::string serializedChannelAddress = joynr::serializer::serializeToJson(ChannelAddress(httpEndPointUrl, httpChannelId));
        std::string serializedMqttAddress = joynr::serializer::serializeToJson(MqttAddress(mqttBrokerUrl, mqttTopic));

        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedChannelAddress));
        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt)), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedMqttAddress));

        //runtime can only be created, after MockCommunicationManager has been told to return
        //a channelId for getReceiveChannelId.
        runtime = std::make_unique<JoynrClusterControllerRuntime>(
                std::move(settings),
                mockMessageReceiverHttp,
                nullptr,
                mockMessageReceiverMqtt,
                mockMessageSenderMqtt);
        // discovery provider is normally registered in JoynrClusterControllerRuntime::create
        runtime->registerDiscoveryProvider();
    }

    ~SystemServicesDiscoveryTest(){
        runtime->deleteChannel();
        runtime->stopExternalCommunication();
        std::remove(settingsFilename.c_str());
    }

    void SetUp(){
        discoveryProxyBuilder = runtime->createProxyBuilder<joynr::system::DiscoveryProxy>(discoveryDomain);
    }

    void TearDown(){
        // Delete persisted files
        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());
    }

private:
    DISALLOW_COPY_AND_ASSIGN(SystemServicesDiscoveryTest);
};

TEST_F(SystemServicesDiscoveryTest, discoveryProviderIsAvailable)
{
    JOYNR_EXPECT_NO_THROW(
        discoveryProxy = discoveryProxyBuilder
                ->setMessagingQos(MessagingQos(5000))
                ->setDiscoveryQos(discoveryQos)
                ->build();
    );
}

TEST_F(SystemServicesDiscoveryTest, lookupUnknowParticipantReturnsEmptyResult)
{
    discoveryProxy = discoveryProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;
    std::string domain("SystemServicesDiscoveryTest.Domain.A");
    std::string interfaceName("SystemServicesDiscoveryTest.InterfaceName.A");
    joynr::types::DiscoveryQos discoveryQos(
                5000,                                     // max cache age
                5000,                                     // discovery ttl
                joynr::types::DiscoveryScope::LOCAL_ONLY, // discovery scope
                false                                     // provider must support on change subscriptions
    );

    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_TRUE(result.empty());
}

TEST_F(SystemServicesDiscoveryTest, add)
{
    discoveryProxy = discoveryProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;
    std::string domain("SystemServicesDiscoveryTest.Domain.A");
    std::string interfaceName("SystemServicesDiscoveryTest.InterfaceName.A");
    std::string participantId("SystemServicesDiscoveryTest.ParticipantID.A");
    joynr::types::DiscoveryQos discoveryQos(
                5000,                                     // max cache age
                5000,                                     // discovery ttl
                joynr::types::DiscoveryScope::LOCAL_ONLY, // discovery scope
                false                                     // provider must support on change subscriptions
    );
    joynr::types::ProviderQos providerQos(
                std::vector<joynr::types::CustomParameter>(), // custom provider parameters
                1,                                      // priority
                joynr::types::ProviderScope::LOCAL,     // scope for provider registration
                false                                   // provider supports on change subscriptions
    );
    joynr::types::Version providerVersion(47, 11);
    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;
    joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry(
                providerVersion,
                domain,
                interfaceName,
                participantId,
                providerQos,
                lastSeenDateMs,
                expiryDateMs,
                publicKeyId,
                true
    );
    expectedResult.push_back(discoveryEntry);

    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_TRUE(result.empty());

    try {
        discoveryProxy->add(discoveryEntry);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "add was not successful";
    }

    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_EQ(expectedResult, result);
}

TEST_F(SystemServicesDiscoveryTest, remove)
{
    discoveryProxy = discoveryProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    std::string domain("SystemServicesDiscoveryTest.Domain.A");
    std::string interfaceName("SystemServicesDiscoveryTest.InterfaceName.A");
    std::string participantId("SystemServicesDiscoveryTest.ParticipantID.A");
    joynr::types::DiscoveryQos discoveryQos(
                5000,                                     // max cache age
                5000,                                     // discovery ttl
                joynr::types::DiscoveryScope::LOCAL_ONLY, // discovery scope
                false                                     // provider must support on change subscriptions
    );
    joynr::types::ProviderQos providerQos(
                std::vector<joynr::types::CustomParameter>(), // custom provider parameters
                1,                                      // priority
                joynr::types::ProviderScope::LOCAL,     // scope for provider registration
                false                                   // provider supports on change subscriptions
    );
    joynr::types::Version providerVersion(47, 11);
    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;
    joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry(
                providerVersion,
                domain,
                interfaceName,
                participantId,
                providerQos,
                lastSeenDateMs,
                expiryDateMs,
                publicKeyId,
                true
    );
    expectedResult.push_back(discoveryEntry);

    try {
        discoveryProxy->add(discoveryEntry);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "add was not successful";
    }

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;
    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_EQ(expectedResult, result);

    try {
        discoveryProxy->remove(participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "remove was not successful";
    }

    result.clear();
    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_TRUE(result.empty());
}
<commit_msg>[C++] Fixed SystemServicesDiscoveryTest<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <memory>
#include <string>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/system/DiscoveryProxy.h"
#include "joynr/Settings.h"
#include "joynr/types/Version.h"
#include "joynr/system/RoutingTypes/MqttAddress.h"
#include "joynr/system/RoutingTypes/ChannelAddress.h"
#include "joynr/serializer/Serializer.h"

#include "tests/JoynrTest.h"
#include "tests/utils/MockObjects.h"

using namespace joynr;

class SystemServicesDiscoveryTest : public ::testing::Test {
public:
    std::string settingsFilename;
    std::unique_ptr<Settings> settings;
    std::string discoveryDomain;
    std::string discoveryProviderParticipantId;
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverHttp;
    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt;
    std::shared_ptr<ITransportMessageSender> mockMessageSenderMqtt;
    DiscoveryQos discoveryQos;
    std::shared_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder;
    std::shared_ptr<joynr::system::DiscoveryProxy> discoveryProxy;
    std::int64_t lastSeenDateMs;
    std::int64_t expiryDateMs;
    std::string publicKeyId;

    SystemServicesDiscoveryTest() :
        settingsFilename("test-resources/SystemServicesDiscoveryTest.settings"),
        settings(std::make_unique<Settings>(settingsFilename)),
        discoveryDomain(),
        discoveryProviderParticipantId(),
        runtime(),
        mockMessageReceiverHttp(std::make_shared<MockTransportMessageReceiver>()),
        mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()),
        mockMessageSenderMqtt(std::make_shared<MockTransportMessageSender>()),
        discoveryQos(),
        discoveryProxyBuilder(nullptr),
        discoveryProxy(nullptr),
        lastSeenDateMs(-1),
        expiryDateMs(-1),
        publicKeyId("")
    {
        SystemServicesSettings systemSettings(*settings);
        systemSettings.printSettings();
        discoveryDomain = systemSettings.getDomain();
        discoveryProviderParticipantId = systemSettings.getCcDiscoveryProviderParticipantId();

        discoveryQos.setCacheMaxAgeMs(1000);
        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
        discoveryQos.addCustomParameter("fixedParticipantId", discoveryProviderParticipantId);
        discoveryQos.setDiscoveryTimeoutMs(50);

        std::string httpChannelId("http_SystemServicesDiscoveryTest.ChannelId");
        std::string httpEndPointUrl("http_SystemServicesRoutingTest.endPointUrl");
        std::string mqttTopic("mqtt_SystemServicesRoutingTest.topic");
        std::string mqttBrokerUrl("mqtt_SystemServicesRoutingTest.brokerUrl");

        using system::RoutingTypes::ChannelAddress;
        using system::RoutingTypes::MqttAddress;

        std::string serializedChannelAddress = joynr::serializer::serializeToJson(ChannelAddress(httpEndPointUrl, httpChannelId));
        std::string serializedMqttAddress = joynr::serializer::serializeToJson(MqttAddress(mqttBrokerUrl, mqttTopic));

        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedChannelAddress));
        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt)), getGlobalClusterControllerAddress())
                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedMqttAddress));

        //runtime can only be created, after MockCommunicationManager has been told to return
        //a channelId for getReceiveChannelId.
        runtime = std::make_shared<JoynrClusterControllerRuntime>(
                std::move(settings),
                mockMessageReceiverHttp,
                nullptr,
                mockMessageReceiverMqtt,
                mockMessageSenderMqtt);
        // discovery provider is normally registered in JoynrClusterControllerRuntime::create
        runtime->registerDiscoveryProvider();
    }

    ~SystemServicesDiscoveryTest(){
        runtime->unregisterDiscoveryProvider();
        runtime->deleteChannel();
        runtime->stopExternalCommunication();
        std::remove(settingsFilename.c_str());
    }

    void SetUp(){
        discoveryProxyBuilder = runtime->createProxyBuilder<joynr::system::DiscoveryProxy>(discoveryDomain);
    }

    void TearDown(){
        // Delete persisted files
        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());
    }

private:
    DISALLOW_COPY_AND_ASSIGN(SystemServicesDiscoveryTest);
};

TEST_F(SystemServicesDiscoveryTest, discoveryProviderIsAvailable)
{
    JOYNR_EXPECT_NO_THROW(
        discoveryProxy = discoveryProxyBuilder
                ->setMessagingQos(MessagingQos(5000))
                ->setDiscoveryQos(discoveryQos)
                ->build();
    );
}

TEST_F(SystemServicesDiscoveryTest, lookupUnknowParticipantReturnsEmptyResult)
{
    discoveryProxy = discoveryProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;
    std::string domain("SystemServicesDiscoveryTest.Domain.A");
    std::string interfaceName("SystemServicesDiscoveryTest.InterfaceName.A");
    joynr::types::DiscoveryQos discoveryQos(
                5000,                                     // max cache age
                5000,                                     // discovery ttl
                joynr::types::DiscoveryScope::LOCAL_ONLY, // discovery scope
                false                                     // provider must support on change subscriptions
    );

    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_TRUE(result.empty());
}

TEST_F(SystemServicesDiscoveryTest, add)
{
    discoveryProxy = discoveryProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;
    std::string domain("SystemServicesDiscoveryTest.Domain.A");
    std::string interfaceName("SystemServicesDiscoveryTest.InterfaceName.A");
    std::string participantId("SystemServicesDiscoveryTest.ParticipantID.A");
    joynr::types::DiscoveryQos discoveryQos(
                5000,                                     // max cache age
                5000,                                     // discovery ttl
                joynr::types::DiscoveryScope::LOCAL_ONLY, // discovery scope
                false                                     // provider must support on change subscriptions
    );
    joynr::types::ProviderQos providerQos(
                std::vector<joynr::types::CustomParameter>(), // custom provider parameters
                1,                                      // priority
                joynr::types::ProviderScope::LOCAL,     // scope for provider registration
                false                                   // provider supports on change subscriptions
    );
    joynr::types::Version providerVersion(47, 11);
    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;
    joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry(
                providerVersion,
                domain,
                interfaceName,
                participantId,
                providerQos,
                lastSeenDateMs,
                expiryDateMs,
                publicKeyId,
                true
    );
    expectedResult.push_back(discoveryEntry);

    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_TRUE(result.empty());

    try {
        discoveryProxy->add(discoveryEntry);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "add was not successful";
    }

    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_EQ(expectedResult, result);
}

TEST_F(SystemServicesDiscoveryTest, remove)
{
    discoveryProxy = discoveryProxyBuilder
            ->setMessagingQos(MessagingQos(5000))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    std::string domain("SystemServicesDiscoveryTest.Domain.A");
    std::string interfaceName("SystemServicesDiscoveryTest.InterfaceName.A");
    std::string participantId("SystemServicesDiscoveryTest.ParticipantID.A");
    joynr::types::DiscoveryQos discoveryQos(
                5000,                                     // max cache age
                5000,                                     // discovery ttl
                joynr::types::DiscoveryScope::LOCAL_ONLY, // discovery scope
                false                                     // provider must support on change subscriptions
    );
    joynr::types::ProviderQos providerQos(
                std::vector<joynr::types::CustomParameter>(), // custom provider parameters
                1,                                      // priority
                joynr::types::ProviderScope::LOCAL,     // scope for provider registration
                false                                   // provider supports on change subscriptions
    );
    joynr::types::Version providerVersion(47, 11);
    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;
    joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry(
                providerVersion,
                domain,
                interfaceName,
                participantId,
                providerQos,
                lastSeenDateMs,
                expiryDateMs,
                publicKeyId,
                true
    );
    expectedResult.push_back(discoveryEntry);

    try {
        discoveryProxy->add(discoveryEntry);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "add was not successful";
    }

    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;
    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_EQ(expectedResult, result);

    try {
        discoveryProxy->remove(participantId);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "remove was not successful";
    }

    result.clear();
    try {
        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);
    } catch (const exceptions::JoynrException& e) {
        ADD_FAILURE()<< "lookup was not successful";
    }
    EXPECT_TRUE(result.empty());
}
<|endoftext|>


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

#include "rclcpp/exceptions.hpp"

#include <cstdio>
#include <functional>
#include <string>

using namespace std::string_literals;

namespace rclcpp
{
namespace exceptions
{

std::string
NameValidationError::format_error(
  const char * name_type,
  const char * name,
  const char * error_msg,
  size_t invalid_index)
{
  std::string msg = "";
  msg += "Invalid "s + name_type + ": " + error_msg + ":\n";
  msg += "  '"s + name + "'\n";
  msg += "   "s + std::string(invalid_index, ' ') + "^\n";
  return msg;
}

void
throw_from_rcl_error(
  rcl_ret_t ret,
  const std::string & prefix,
  const rcl_error_state_t * error_state,
  void (* reset_error)())
{
  if (RCL_RET_OK == ret) {
    throw std::invalid_argument("ret is RCL_RET_OK");
  }
  if (!error_state) {
    error_state = rcl_get_error_state();
  }
  if (!error_state) {
    throw std::runtime_error("rcl error state is not set");
  }
  std::string formated_prefix = prefix;
  if (!prefix.empty()) {
    formated_prefix += ": ";
  }
  RCLErrorBase base_exc(ret, error_state);
  if (reset_error) {
    reset_error();
  }
  switch (ret) {
    case RCL_RET_BAD_ALLOC:
      throw RCLBadAlloc(base_exc);
    case RCL_RET_INVALID_ARGUMENT:
      throw RCLInvalidArgument(base_exc, formated_prefix);
    default:
      throw RCLError(base_exc, formated_prefix);
  }
}

RCLErrorBase::RCLErrorBase(rcl_ret_t ret, const rcl_error_state_t * error_state)
: ret(ret), message(error_state->message), file(error_state->file), line(error_state->line_number),
  formatted_message(rcl_get_error_string().str)
{}

RCLError::RCLError(
  rcl_ret_t ret,
  const rcl_error_state_t * error_state,
  const std::string & prefix)
: RCLError(RCLErrorBase(ret, error_state), prefix)
{}

RCLError::RCLError(
  const RCLErrorBase & base_exc,
  const std::string & prefix)
: RCLErrorBase(base_exc), std::runtime_error(prefix + base_exc.formatted_message)
{}

RCLBadAlloc::RCLBadAlloc(rcl_ret_t ret, const rcl_error_state_t * error_state)
: RCLBadAlloc(RCLErrorBase(ret, error_state))
{}

RCLBadAlloc::RCLBadAlloc(const RCLErrorBase & base_exc)
: RCLErrorBase(base_exc), std::bad_alloc()
{}

RCLInvalidArgument::RCLInvalidArgument(
  rcl_ret_t ret,
  const rcl_error_state_t * error_state,
  const std::string & prefix)
: RCLInvalidArgument(RCLErrorBase(ret, error_state), prefix)
{}

RCLInvalidArgument::RCLInvalidArgument(
  const RCLErrorBase & base_exc,
  const std::string & prefix)
: RCLErrorBase(base_exc), std::invalid_argument(prefix + base_exc.formatted_message)
{}

}  // namespace exceptions
}  // namespace rclcpp
<commit_msg>[WIP] Exception Generator function for implementing "from_rcl_error" (#678)<commit_after>// Copyright 2016 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "rclcpp/exceptions.hpp"

#include <cstdio>
#include <functional>
#include <string>

using namespace std::string_literals;

namespace rclcpp
{
namespace exceptions
{

std::string
NameValidationError::format_error(
  const char * name_type,
  const char * name,
  const char * error_msg,
  size_t invalid_index)
{
  std::string msg = "";
  msg += "Invalid "s + name_type + ": " + error_msg + ":\n";
  msg += "  '"s + name + "'\n";
  msg += "   "s + std::string(invalid_index, ' ') + "^\n";
  return msg;
}

std::exception_ptr
from_rcl_error(
  rcl_ret_t ret,
  const std::string & prefix,
  const rcl_error_state_t * error_state,
  void (* reset_error)())
{
  if (RCL_RET_OK == ret) {
    throw std::invalid_argument("ret is RCL_RET_OK");
  }
  if (!error_state) {
    error_state = rcl_get_error_state();
  }
  if (!error_state) {
    throw std::runtime_error("rcl error state is not set");
  }
  std::string formatted_prefix = prefix;
  if (!prefix.empty()) {
    formatted_prefix += ": ";
  }
  RCLErrorBase base_exc(ret, error_state);
  if (reset_error) {
    reset_error();
  }
  switch (ret) {
    case RCL_RET_BAD_ALLOC:
      return std::make_exception_ptr(RCLBadAlloc(base_exc));
    case RCL_RET_INVALID_ARGUMENT:
      return std::make_exception_ptr(RCLInvalidArgument(base_exc, formatted_prefix));
    default:
      return std::make_exception_ptr(RCLError(base_exc, formatted_prefix));
  }
}

void
throw_from_rcl_error(
  rcl_ret_t ret,
  const std::string & prefix,
  const rcl_error_state_t * error_state,
  void (* reset_error)())
{
  // We expect this to either throw a standard error,
  // or to generate an error pointer (which is caught
  // in err, and immediately thrown)
  auto err = from_rcl_error(ret, prefix, error_state, reset_error);
  std::rethrow_exception(err);
}

RCLErrorBase::RCLErrorBase(rcl_ret_t ret, const rcl_error_state_t * error_state)
: ret(ret), message(error_state->message), file(error_state->file), line(error_state->line_number),
  formatted_message(rcl_get_error_string().str)
{}

RCLError::RCLError(
  rcl_ret_t ret,
  const rcl_error_state_t * error_state,
  const std::string & prefix)
: RCLError(RCLErrorBase(ret, error_state), prefix)
{}

RCLError::RCLError(
  const RCLErrorBase & base_exc,
  const std::string & prefix)
: RCLErrorBase(base_exc), std::runtime_error(prefix + base_exc.formatted_message)
{}

RCLBadAlloc::RCLBadAlloc(rcl_ret_t ret, const rcl_error_state_t * error_state)
: RCLBadAlloc(RCLErrorBase(ret, error_state))
{}

RCLBadAlloc::RCLBadAlloc(const RCLErrorBase & base_exc)
: RCLErrorBase(base_exc), std::bad_alloc()
{}

RCLInvalidArgument::RCLInvalidArgument(
  rcl_ret_t ret,
  const rcl_error_state_t * error_state,
  const std::string & prefix)
: RCLInvalidArgument(RCLErrorBase(ret, error_state), prefix)
{}

RCLInvalidArgument::RCLInvalidArgument(
  const RCLErrorBase & base_exc,
  const std::string & prefix)
: RCLErrorBase(base_exc), std::invalid_argument(prefix + base_exc.formatted_message)
{}

}  // namespace exceptions
}  // namespace rclcpp
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

#include "modules/prediction/common/prediction_gflags.h"

#include <cmath>
#include <limits>

// System gflags
DEFINE_string(prediction_module_name, "prediction",
              "Default prediction module name");
DEFINE_string(prediction_conf_file,
              "/apollo/modules/prediction/conf/prediction_conf.pb.txt",
              "Default conf file for prediction");
DEFINE_string(prediction_adapter_config_filename,
              "/apollo/modules/prediction/conf/adapter.conf",
              "Default conf file for prediction");
DEFINE_string(prediction_data_dir,
              "/apollo/modules/prediction/data/prediction/",
              "Prefix of files to store feature data");
DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode");
DEFINE_double(
    prediction_test_duration, std::numeric_limits<double>::infinity(),
    "The runtime duration in test mode (in seconds). Negative value will not "
    "restrict the runtime duration.");

DEFINE_bool(prediction_offline_mode, false, "Prediction offline mode");
DEFINE_string(
    prediction_offline_bags, "",
    "a list of bag files or directories for offline mode. The items need to be "
    "separated by colon ':'.  If this value is not set, the prediction module "
    "will use the listen to published ros topic mode.");

DEFINE_double(prediction_duration, 8.0, "Prediction duration (in seconds)");
DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds");
DEFINE_double(double_precision, 1e-6, "precision of double");
DEFINE_double(min_prediction_length, 20.0,
              "Minimal length of prediction trajectory");

// Bag replay timestamp gap
DEFINE_double(replay_timestamp_gap, 10.0,
              "Max timestamp gap for rosbag replay");
DEFINE_int32(max_num_dump_feature, 50000,
             "Max number of features to dump");

// Map
DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane");
DEFINE_double(lane_search_radius_in_junction, 15.0,
              "Search radius for a candidate lane");
DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction");

// Scenario
DEFINE_double(junction_distance_threshold, 10.0, "Distance threshold "
              "to junction to consider as junction scenario");
DEFINE_bool(enable_prioritize_obstacles, false,
            "If to enable the functionality to prioritize obstacles");
DEFINE_bool(enable_junction_feature, false,
            "If to enable building junction feature for obstacles");

// Obstacle features
DEFINE_uint32(cruise_historical_frame_length, 5,
              "The number of historical frames of the obstacle"
              "that the cruise model will look at.");
DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking");
DEFINE_double(max_acc, 4.0, "Upper bound of acceleration");
DEFINE_double(min_acc, -4.0, "Lower bound of deceleration");
DEFINE_double(max_speed, 35.0, "Max speed");
DEFINE_double(max_angle_diff_to_adjust_velocity, M_PI / 6.0,
              "The maximal angle diff to adjust velocity heading.");
DEFINE_double(q_var, 0.01, "Processing noise covariance");
DEFINE_double(r_var, 0.25, "Measurement noise covariance");
DEFINE_double(p_var, 0.1, "Error covariance");
DEFINE_double(go_approach_rate, 0.995,
              "The rate to approach to the reference line of going straight");

DEFINE_int32(min_still_obstacle_history_length, 4,
             "Min # historical frames for still obstacles");
DEFINE_int32(max_still_obstacle_history_length, 10,
             "Min # historical frames for still obstacles");
DEFINE_double(still_obstacle_speed_threshold, 2.0,
              "Speed threshold for still obstacles");
DEFINE_double(still_pedestrian_speed_threshold, 0.5,
              "Speed threshold for still pedestrians");
DEFINE_double(still_obstacle_position_std, 1.0,
              "Position standard deviation for still obstacles");
DEFINE_double(still_pedestrian_position_std, 0.5,
              "Position standard deviation for still obstacles");
DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time.");
DEFINE_double(target_lane_gap, 2.0, "gap between two lane points.");
DEFINE_int32(max_num_current_lane, 2, "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff, M_PI / 2.0,
              "Max angle difference for a candiate lane");
DEFINE_int32(max_num_current_lane_in_junction, 1,
             "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane_in_junction, 1,
             "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff_in_junction, M_PI / 6.0,
              "Max angle difference for a candiate lane");
DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc");
DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation");
DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian");
DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration");
DEFINE_double(prediction_pedestrian_total_time, 10.0,
              "Total prediction time for pedestrians");
DEFINE_double(still_speed, 0.01, "speed considered to be still");
DEFINE_string(evaluator_vehicle_mlp_file,
              "/apollo/modules/prediction/data/mlp_vehicle_model.bin",
              "mlp model file for vehicle evaluator");
DEFINE_string(evaluator_vehicle_rnn_file,
              "/apollo/modules/prediction/data/rnn_vehicle_model.bin",
              "rnn model file for vehicle evaluator");
DEFINE_string(evaluator_cruise_vehicle_go_model_file,
              "/apollo/modules/prediction/data/cruise_go_vehicle_model.bin",
              "Vehicle cruise go model file");
DEFINE_string(evaluator_cruise_vehicle_cutin_model_file,
              "/apollo/modules/prediction/data/cruise_cutin_vehicle_model.bin",
              "Vehicle cruise cutin model file");
DEFINE_string(evaluator_vehicle_junction_mlp_file,
              "/apollo/modules/prediction/data/junction_mlp_vehicle_model.bin",
              "Vehicle junction MLP model file");
DEFINE_int32(max_num_obstacles, 100,
             "maximal number of obstacles stored in obstacles container.");
DEFINE_double(valid_position_diff_threshold, 0.5,
              "threshold of valid position difference");
DEFINE_double(valid_position_diff_rate_threshold, 0.075,
              "threshold of valid position difference rate");
DEFINE_double(split_rate, 0.5, "obstacle split rate for adjusting velocity");
DEFINE_double(rnn_min_lane_relatice_s, 5.0,
              "Minimal relative s for RNN model.");
DEFINE_bool(adjust_velocity_by_obstacle_heading, false,
            "Use obstacle heading for velocity.");
DEFINE_bool(adjust_velocity_by_position_shift, false,
            "adjust velocity heading to lane heading");
DEFINE_bool(adjust_vehicle_heading_by_lane, true,
            "adjust vehicle heading by lane");
DEFINE_double(heading_filter_param, 0.99, "heading filter parameter");
DEFINE_uint32(max_num_lane_point, 20,
              "The maximal number of lane points to store");

// Validation checker
DEFINE_double(centripetal_acc_coeff, 0.5,
              "Coefficient of centripetal acceleration probability");

// Obstacle trajectory
DEFINE_bool(enable_cruise_regression, false,
            "If enable using regression in cruise model");
DEFINE_double(lane_sequence_threshold, 0.5,
              "Threshold for trimming lane sequence trajectories");
DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC");
DEFINE_bool(enable_lane_sequence_acc, false,
            "If use acceleration in lane sequence.");
DEFINE_bool(enable_trim_prediction_trajectory, false,
            "If trim the prediction trajectory to avoid crossing"
            "protected adc planning trajectory.");
DEFINE_bool(enable_trajectory_validation_check, false,
            "If check the validity of prediction trajectory.");
DEFINE_double(distance_beyond_junction, 0.5,
              "If the obstacle is in junction more than this threshold,"
              "consider it in junction.");
DEFINE_double(adc_trajectory_search_length, 10.0,
              "How far to search junction along adc planning trajectory");
DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes");
DEFINE_double(default_lateral_approach_speed, 0.5,
              "Default lateral speed approaching to center of lane");
DEFINE_double(centripedal_acc_threshold, 2.0,
              "Threshold of centripedal acceleration.");

// move sequence prediction
DEFINE_double(time_upper_bound_to_lane_center, 6.0,
              "Upper bound of time to get to the lane center");
DEFINE_double(time_lower_bound_to_lane_center, 1.0,
              "Lower bound of time to get to the lane center");
DEFINE_double(sample_time_gap, 0.25,
              "Gap of time to sample time to get to the lane center");
DEFINE_double(cost_alpha, 100.0,
              "The coefficient of lateral acceleration in cost function");
DEFINE_double(default_time_to_lat_end_state, 5.0,
              "The default time to lane center");
DEFINE_double(turning_curvature_lower_bound, 0.02,
              "The curvature lower bound of turning lane");
DEFINE_double(turning_curvature_upper_bound, 0.14,
              "The curvature upper bound of turning lane");
DEFINE_double(speed_at_lower_curvature, 8.5,
              "The speed at turning lane with lower bound curvature");
DEFINE_double(speed_at_upper_curvature, 3.0,
              "The speed at turning lane with upper bound curvature");
DEFINE_double(cost_function_alpha, 0.25,
              "alpha of the cost function for best trajectory selection,"
              "alpha weighs the influence by max lateral acceleration"
              "and that by the total time. The larger alpha gets, the"
              "more cost function values trajectory with shorter times,"
              "and vice versa.");
DEFINE_double(cost_function_sigma, 5.0,
              "This is the sigma for the bell curve that is used by"
              "the cost function in move-sequence-trajectory-predictor."
              "The bell curve has its average equal to the time to cross"
              "lane predicted by the model.");
DEFINE_bool(use_bell_curve_for_cost_function, false,
            "Whether to use bell curve for the cost function or not.");

DEFINE_int32(road_graph_max_search_horizon, 20,
             "Maximal search depth for buiding road graph");
<commit_msg>Prediction: enlarge the max num of obstacles in LRU cache<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

#include "modules/prediction/common/prediction_gflags.h"

#include <cmath>
#include <limits>

// System gflags
DEFINE_string(prediction_module_name, "prediction",
              "Default prediction module name");
DEFINE_string(prediction_conf_file,
              "/apollo/modules/prediction/conf/prediction_conf.pb.txt",
              "Default conf file for prediction");
DEFINE_string(prediction_adapter_config_filename,
              "/apollo/modules/prediction/conf/adapter.conf",
              "Default conf file for prediction");
DEFINE_string(prediction_data_dir,
              "/apollo/modules/prediction/data/prediction/",
              "Prefix of files to store feature data");
DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode");
DEFINE_double(
    prediction_test_duration, std::numeric_limits<double>::infinity(),
    "The runtime duration in test mode (in seconds). Negative value will not "
    "restrict the runtime duration.");

DEFINE_bool(prediction_offline_mode, false, "Prediction offline mode");
DEFINE_string(
    prediction_offline_bags, "",
    "a list of bag files or directories for offline mode. The items need to be "
    "separated by colon ':'.  If this value is not set, the prediction module "
    "will use the listen to published ros topic mode.");

DEFINE_double(prediction_duration, 8.0, "Prediction duration (in seconds)");
DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds");
DEFINE_double(double_precision, 1e-6, "precision of double");
DEFINE_double(min_prediction_length, 20.0,
              "Minimal length of prediction trajectory");

// Bag replay timestamp gap
DEFINE_double(replay_timestamp_gap, 10.0,
              "Max timestamp gap for rosbag replay");
DEFINE_int32(max_num_dump_feature, 50000,
             "Max number of features to dump");

// Map
DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane");
DEFINE_double(lane_search_radius_in_junction, 15.0,
              "Search radius for a candidate lane");
DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction");

// Scenario
DEFINE_double(junction_distance_threshold, 10.0, "Distance threshold "
              "to junction to consider as junction scenario");
DEFINE_bool(enable_prioritize_obstacles, false,
            "If to enable the functionality to prioritize obstacles");
DEFINE_bool(enable_junction_feature, false,
            "If to enable building junction feature for obstacles");

// Obstacle features
DEFINE_uint32(cruise_historical_frame_length, 5,
              "The number of historical frames of the obstacle"
              "that the cruise model will look at.");
DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking");
DEFINE_double(max_acc, 4.0, "Upper bound of acceleration");
DEFINE_double(min_acc, -4.0, "Lower bound of deceleration");
DEFINE_double(max_speed, 35.0, "Max speed");
DEFINE_double(max_angle_diff_to_adjust_velocity, M_PI / 6.0,
              "The maximal angle diff to adjust velocity heading.");
DEFINE_double(q_var, 0.01, "Processing noise covariance");
DEFINE_double(r_var, 0.25, "Measurement noise covariance");
DEFINE_double(p_var, 0.1, "Error covariance");
DEFINE_double(go_approach_rate, 0.995,
              "The rate to approach to the reference line of going straight");

DEFINE_int32(min_still_obstacle_history_length, 4,
             "Min # historical frames for still obstacles");
DEFINE_int32(max_still_obstacle_history_length, 10,
             "Min # historical frames for still obstacles");
DEFINE_double(still_obstacle_speed_threshold, 2.0,
              "Speed threshold for still obstacles");
DEFINE_double(still_pedestrian_speed_threshold, 0.5,
              "Speed threshold for still pedestrians");
DEFINE_double(still_obstacle_position_std, 1.0,
              "Position standard deviation for still obstacles");
DEFINE_double(still_pedestrian_position_std, 0.5,
              "Position standard deviation for still obstacles");
DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time.");
DEFINE_double(target_lane_gap, 2.0, "gap between two lane points.");
DEFINE_int32(max_num_current_lane, 2, "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff, M_PI / 2.0,
              "Max angle difference for a candiate lane");
DEFINE_int32(max_num_current_lane_in_junction, 1,
             "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane_in_junction, 1,
             "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff_in_junction, M_PI / 6.0,
              "Max angle difference for a candiate lane");
DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc");
DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation");
DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian");
DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration");
DEFINE_double(prediction_pedestrian_total_time, 10.0,
              "Total prediction time for pedestrians");
DEFINE_double(still_speed, 0.01, "speed considered to be still");
DEFINE_string(evaluator_vehicle_mlp_file,
              "/apollo/modules/prediction/data/mlp_vehicle_model.bin",
              "mlp model file for vehicle evaluator");
DEFINE_string(evaluator_vehicle_rnn_file,
              "/apollo/modules/prediction/data/rnn_vehicle_model.bin",
              "rnn model file for vehicle evaluator");
DEFINE_string(evaluator_cruise_vehicle_go_model_file,
              "/apollo/modules/prediction/data/cruise_go_vehicle_model.bin",
              "Vehicle cruise go model file");
DEFINE_string(evaluator_cruise_vehicle_cutin_model_file,
              "/apollo/modules/prediction/data/cruise_cutin_vehicle_model.bin",
              "Vehicle cruise cutin model file");
DEFINE_string(evaluator_vehicle_junction_mlp_file,
              "/apollo/modules/prediction/data/junction_mlp_vehicle_model.bin",
              "Vehicle junction MLP model file");
DEFINE_int32(max_num_obstacles, 300,
             "maximal number of obstacles stored in obstacles container.");
DEFINE_double(valid_position_diff_threshold, 0.5,
              "threshold of valid position difference");
DEFINE_double(valid_position_diff_rate_threshold, 0.075,
              "threshold of valid position difference rate");
DEFINE_double(split_rate, 0.5, "obstacle split rate for adjusting velocity");
DEFINE_double(rnn_min_lane_relatice_s, 5.0,
              "Minimal relative s for RNN model.");
DEFINE_bool(adjust_velocity_by_obstacle_heading, false,
            "Use obstacle heading for velocity.");
DEFINE_bool(adjust_velocity_by_position_shift, false,
            "adjust velocity heading to lane heading");
DEFINE_bool(adjust_vehicle_heading_by_lane, true,
            "adjust vehicle heading by lane");
DEFINE_double(heading_filter_param, 0.99, "heading filter parameter");
DEFINE_uint32(max_num_lane_point, 20,
              "The maximal number of lane points to store");

// Validation checker
DEFINE_double(centripetal_acc_coeff, 0.5,
              "Coefficient of centripetal acceleration probability");

// Obstacle trajectory
DEFINE_bool(enable_cruise_regression, false,
            "If enable using regression in cruise model");
DEFINE_double(lane_sequence_threshold, 0.5,
              "Threshold for trimming lane sequence trajectories");
DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC");
DEFINE_bool(enable_lane_sequence_acc, false,
            "If use acceleration in lane sequence.");
DEFINE_bool(enable_trim_prediction_trajectory, false,
            "If trim the prediction trajectory to avoid crossing"
            "protected adc planning trajectory.");
DEFINE_bool(enable_trajectory_validation_check, false,
            "If check the validity of prediction trajectory.");
DEFINE_double(distance_beyond_junction, 0.5,
              "If the obstacle is in junction more than this threshold,"
              "consider it in junction.");
DEFINE_double(adc_trajectory_search_length, 10.0,
              "How far to search junction along adc planning trajectory");
DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes");
DEFINE_double(default_lateral_approach_speed, 0.5,
              "Default lateral speed approaching to center of lane");
DEFINE_double(centripedal_acc_threshold, 2.0,
              "Threshold of centripedal acceleration.");

// move sequence prediction
DEFINE_double(time_upper_bound_to_lane_center, 6.0,
              "Upper bound of time to get to the lane center");
DEFINE_double(time_lower_bound_to_lane_center, 1.0,
              "Lower bound of time to get to the lane center");
DEFINE_double(sample_time_gap, 0.25,
              "Gap of time to sample time to get to the lane center");
DEFINE_double(cost_alpha, 100.0,
              "The coefficient of lateral acceleration in cost function");
DEFINE_double(default_time_to_lat_end_state, 5.0,
              "The default time to lane center");
DEFINE_double(turning_curvature_lower_bound, 0.02,
              "The curvature lower bound of turning lane");
DEFINE_double(turning_curvature_upper_bound, 0.14,
              "The curvature upper bound of turning lane");
DEFINE_double(speed_at_lower_curvature, 8.5,
              "The speed at turning lane with lower bound curvature");
DEFINE_double(speed_at_upper_curvature, 3.0,
              "The speed at turning lane with upper bound curvature");
DEFINE_double(cost_function_alpha, 0.25,
              "alpha of the cost function for best trajectory selection,"
              "alpha weighs the influence by max lateral acceleration"
              "and that by the total time. The larger alpha gets, the"
              "more cost function values trajectory with shorter times,"
              "and vice versa.");
DEFINE_double(cost_function_sigma, 5.0,
              "This is the sigma for the bell curve that is used by"
              "the cost function in move-sequence-trajectory-predictor."
              "The bell curve has its average equal to the time to cross"
              "lane predicted by the model.");
DEFINE_bool(use_bell_curve_for_cost_function, false,
            "Whether to use bell curve for the cost function or not.");

DEFINE_int32(road_graph_max_search_horizon, 20,
             "Maximal search depth for buiding road graph");
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/animationqt/sequenceeditorpanel/sequenceeditorwidget.h>
#include <modules/animationqt/sequenceeditorpanel/sequenceeditorpanel.h>
#include <modules/animationqt/sequenceeditorpanel/keyframeeditorwidget.h>

#include <modules/animation/datastructures/propertytrack.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QComboBox>
#include <warn/pop>

/**
 * TODO:
 * * Listen to updates to easing from outside
 */

namespace inviwo {

namespace animation {
SequenceEditorWidget::SequenceEditorWidget(KeyframeSequence& sequence, Track& track,
                                           SequenceEditorPanel* panel)
    : QWidget(panel), sequence_(sequence), track_(track) {
    setObjectName("SequenceEditorWidget");
    sequence_.addObserver(this);

    auto layout = new QVBoxLayout();
    setLayout(layout);

    auto label = new QLabel(track_.getName().c_str());
    auto font = label->font();
    font.setBold(true);
    label->setFont(font);
    layout->addWidget(label);

    keyframesLayout_ = new QVBoxLayout();
    layout->addLayout(keyframesLayout_);

	if (dynamic_cast<BasePropertyTrack*>(&track)) {
        auto easingLayout = new QHBoxLayout();
        layout->addLayout(easingLayout);

        easingComboBox_ = new QComboBox();
        easingLayout->addWidget(new QLabel("Easing: "));
        easingLayout->addWidget(easingComboBox_);

        auto currentEasing = sequence_.getEasingType();

        for (auto e = easing::FirstEasingType; e <= easing::LastEasingType; ++e) {
            std::ostringstream oss;
            oss << e;
            easingComboBox_->addItem(oss.str().c_str(), QVariant((int)e));
            if (currentEasing == e) {
                easingComboBox_->setCurrentIndex(easingComboBox_->count() - 1);
            }
        }

        void (QComboBox::*signal)(int) = &QComboBox::currentIndexChanged;
        connect(easingComboBox_, signal,
                [this](int index) { sequence_.setEasingType(static_cast<easing::EasingType>(index)); });
    }

    for (size_t i = 0; i < sequence_.size(); i++) {
        onKeyframeAdded(&sequence_[i], &sequence_);
    }

    updateVisibility();
}

void SequenceEditorWidget::updateVisibility() {
    setVisible(sequence_.isSelected() || sequence_.isAnyKeyframeSelected());
}

void SequenceEditorWidget::onKeyframeSequenceSelectionChanged(KeyframeSequence* seq) {
    updateVisibility();
}

void SequenceEditorWidget::onKeyframeAdded(Keyframe* key, KeyframeSequence* seq) {
    auto w = new KeyframeEditorWidget(*key, this);
    keyframesLayout_->addWidget(w);
    keyframeEditorWidgets_[key] = w;
    setReorderNeeded();
}

void SequenceEditorWidget::onKeyframeRemoved(Keyframe* key, KeyframeSequence* seq) {
    auto widget = keyframeEditorWidgets_[key];
    keyframeEditorWidgets_.erase(key);
    keyframesLayout_->removeWidget(widget);
    setReorderNeeded();
}

void SequenceEditorWidget::setReorderNeeded() { reorderNeeded_ = true; }

void SequenceEditorWidget::onKeyframeSequenceEasingChanged(KeyframeSequence* seq) {
    easingComboBox_->blockSignals(true);
    auto index = easingComboBox_->findData(QVariant((int)seq->getEasingType()));
    easingComboBox_->setCurrentIndex(index);
    easingComboBox_->blockSignals(false);
}

void SequenceEditorWidget::reorderKeyframes() {

    std::vector<KeyframeEditorWidget*> widgets(keyframeEditorWidgets_.size());
    std::transform(keyframeEditorWidgets_.begin(), keyframeEditorWidgets_.end(), widgets.begin(),
                   [](auto pair) { return pair.second; });

    std::stable_sort(widgets.begin(), widgets.end(), [](auto a, auto b) {
        return a->getKeyframe().getTime().count() < b->getKeyframe().getTime().count();
    });

    bool orderChanged = false;
    size_t i = 0;
    for (auto w : widgets) {
        orderChanged |= keyframesLayout_->indexOf(w) != i++;
    }

    if (orderChanged) {
        for (auto w : widgets) {
            keyframesLayout_->removeWidget(w);
        }

        for (auto w : widgets) {
            keyframesLayout_->addWidget(w);
        }
    };
}

void SequenceEditorWidget::paintEvent(QPaintEvent* event) {
    if (reorderNeeded_) {
        reorderKeyframes();
        reorderNeeded_ = false;
    }

    QWidget::paintEvent(event);
}

}  // namespace animation

}  // namespace inviwo
<commit_msg>Animation: Bug fix for removing keyframe<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/animationqt/sequenceeditorpanel/sequenceeditorwidget.h>
#include <modules/animationqt/sequenceeditorpanel/sequenceeditorpanel.h>
#include <modules/animationqt/sequenceeditorpanel/keyframeeditorwidget.h>

#include <modules/animation/datastructures/propertytrack.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QComboBox>
#include <warn/pop>

/**
 * TODO:
 * * Listen to updates to easing from outside
 */

namespace inviwo {

namespace animation {
SequenceEditorWidget::SequenceEditorWidget(KeyframeSequence& sequence, Track& track,
                                           SequenceEditorPanel* panel)
    : QWidget(panel), sequence_(sequence), track_(track) {
    setObjectName("SequenceEditorWidget");
    sequence_.addObserver(this);

    auto layout = new QVBoxLayout();
    setLayout(layout);

    auto label = new QLabel(track_.getName().c_str());
    auto font = label->font();
    font.setBold(true);
    label->setFont(font);
    layout->addWidget(label);

    keyframesLayout_ = new QVBoxLayout();
    layout->addLayout(keyframesLayout_);

	if (dynamic_cast<BasePropertyTrack*>(&track)) {
        auto easingLayout = new QHBoxLayout();
        layout->addLayout(easingLayout);

        easingComboBox_ = new QComboBox();
        easingLayout->addWidget(new QLabel("Easing: "));
        easingLayout->addWidget(easingComboBox_);

        auto currentEasing = sequence_.getEasingType();

        for (auto e = easing::FirstEasingType; e <= easing::LastEasingType; ++e) {
            std::ostringstream oss;
            oss << e;
            easingComboBox_->addItem(oss.str().c_str(), QVariant((int)e));
            if (currentEasing == e) {
                easingComboBox_->setCurrentIndex(easingComboBox_->count() - 1);
            }
        }

        void (QComboBox::*signal)(int) = &QComboBox::currentIndexChanged;
        connect(easingComboBox_, signal,
                [this](int index) { sequence_.setEasingType(static_cast<easing::EasingType>(index)); });
    }

    for (size_t i = 0; i < sequence_.size(); i++) {
        onKeyframeAdded(&sequence_[i], &sequence_);
    }

    updateVisibility();
}

void SequenceEditorWidget::updateVisibility() {
    setVisible(sequence_.isSelected() || sequence_.isAnyKeyframeSelected());
}

void SequenceEditorWidget::onKeyframeSequenceSelectionChanged(KeyframeSequence* seq) {
    updateVisibility();
}

void SequenceEditorWidget::onKeyframeAdded(Keyframe* key, KeyframeSequence* seq) {
    auto w = new KeyframeEditorWidget(*key, this);
    keyframesLayout_->addWidget(w);
    keyframeEditorWidgets_[key] = w;
    setReorderNeeded();
}

void SequenceEditorWidget::onKeyframeRemoved(Keyframe* key, KeyframeSequence* seq) {
    auto it = keyframeEditorWidgets_.find(key);
    if (it != keyframeEditorWidgets_.end()) {
        keyframesLayout_->removeWidget(it->second);
        delete it->second;
        keyframeEditorWidgets_.erase(it);
        setReorderNeeded();
    }
}

void SequenceEditorWidget::setReorderNeeded() { reorderNeeded_ = true; }

void SequenceEditorWidget::onKeyframeSequenceEasingChanged(KeyframeSequence* seq) {
    easingComboBox_->blockSignals(true);
    auto index = easingComboBox_->findData(QVariant((int)seq->getEasingType()));
    easingComboBox_->setCurrentIndex(index);
    easingComboBox_->blockSignals(false);
}

void SequenceEditorWidget::reorderKeyframes() {

    std::vector<KeyframeEditorWidget*> widgets(keyframeEditorWidgets_.size());
    std::transform(keyframeEditorWidgets_.begin(), keyframeEditorWidgets_.end(), widgets.begin(),
                   [](auto pair) { return pair.second; });

    std::stable_sort(widgets.begin(), widgets.end(), [](auto a, auto b) {
        return a->getKeyframe().getTime().count() < b->getKeyframe().getTime().count();
    });

    bool orderChanged = false;
    size_t i = 0;
    for (auto w : widgets) {
        orderChanged |= keyframesLayout_->indexOf(w) != i++;
    }

    if (orderChanged) {
        for (auto w : widgets) {
            keyframesLayout_->removeWidget(w);
        }

        for (auto w : widgets) {
            keyframesLayout_->addWidget(w);
        }
    };
}

void SequenceEditorWidget::paintEvent(QPaintEvent* event) {
    if (reorderNeeded_) {
        reorderKeyframes();
        reorderNeeded_ = false;
    }

    QWidget::paintEvent(event);
}

}  // namespace animation

}  // namespace inviwo
<|endoftext|>


<commit_before>#include <cstring>

#include "benchmark/benchmark_api.h"
#include "test_configs.h"
#include "test_utils.h"

// Linear search on a sequence
static void BM_strstr(benchmark::State& state) {
  const unsigned N = state.range(0);
  char s1[N];
  char s2[N/16];
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, false);
  while (state.KeepRunning()) {
    // searching for all the elements.
    benchmark::DoNotOptimize(strstr(s1, s2));
  }
  state.SetComplexityN(N);
}

// FIXME: Set a limit on the max number of iterations.
static void BM_strcat(benchmark::State& state) {
  const unsigned N = state.range(0);
  const unsigned s2_sz = 2;
  char s1[N];
  char s2[s2_sz];
  fillRandomChars(s1, s1+1, true);
  fillRandomChars(s2, s2+s2_sz, false);
  unsigned s1_sz = 1;
  while (state.KeepRunning()) {
    // searching for all the elements.
    // FIXME: strcat is tricky because it keeps concatenating
    // until the timer stops, that corrupts memory.
    benchmark::DoNotOptimize(strcat(s1, s2));
    s1_sz += s2_sz;
    if (s1_sz >= N) {
      state.SkipWithError("Memory corruption");
    }
  }
  state.SetComplexityN(N);
}

// Linear search on a sequence
static void BM_strchr(benchmark::State& state) {
  const unsigned N = state.range(0);
  char s1[N];
  char s2 = '1';
  fillRandomChars(s1, s1+N, true);
  while (state.KeepRunning()) {
    // searching for all the elements.
    benchmark::DoNotOptimize(strchr(s1, s2));
  }
  state.SetComplexityN(N);
}

static void BM_strcmp(benchmark::State& state) {
  const unsigned N = state.range(0);
  char s1[N];
  char s2[N/16];
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, true);
  unsigned i = 0;
  while (state.KeepRunning()) {
    // strcmp at varying positions
    benchmark::DoNotOptimize(strcmp(s1+(i++%N), s2));
  }
  state.SetComplexityN(N);
}

static void BM_strcpy(benchmark::State& state) {
  const unsigned N = state.range(0);
  char s1[N];
  char s2[N/16];
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, true);
  unsigned i = 0;
  while (state.KeepRunning()) {
    // strcpy at varying positions.
    const unsigned offset = (i++%N)/2;
    benchmark::DoNotOptimize(strcpy(s1 + offset, s2));
  }
  state.SetComplexityN(N);
}

static void BM_strlen(benchmark::State& state) {
  const unsigned N = state.range(0);
  char s1[N];
  char s2[N/16];
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, true);
  unsigned i = 0;
  while (state.KeepRunning()) {
    // strlen at varying positions.
    benchmark::DoNotOptimize(strlen(s1+i++));
  }
  state.SetComplexityN(N);
}

/*strcat - concatenate two strings
strchr - string scanning operation
strcmp - compare two strings
strcpy - copy a string
strlen - get string length
strncat - concatenate one string with part of another
strncmp - compare parts of two strings
strncpy - copy part of a string
strrchr - string scanning operation*/

static const int MSize = L2;
COMPLEXITY_BENCHMARK(BM_strstr, MSize);
COMPLEXITY_BENCHMARK(BM_strcat, MSize);
COMPLEXITY_BENCHMARK(BM_strchr, MSize);
COMPLEXITY_BENCHMARK(BM_strcmp, MSize);
COMPLEXITY_BENCHMARK(BM_strcpy, MSize);
COMPLEXITY_BENCHMARK(BM_strlen, MSize);
BENCHMARK_MAIN()
<commit_msg>removed val array to conform to c++<commit_after>#include <cstring>

#include "benchmark/benchmark_api.h"
#include "test_configs.h"
#include "test_utils.h"

// Linear search on a sequence
static void BM_strstr(benchmark::State& state) {
  const unsigned N = state.range(0);
  char *s1 = (char*) malloc(N*sizeof(char));
  char *s2 = (char*) malloc(N/16*sizeof(char));
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, false);
  while (state.KeepRunning()) {
    // searching for all the elements.
    benchmark::DoNotOptimize(strstr(s1, s2));
  }
  free(s1);
  free(s2);
  state.SetComplexityN(N);
}

// FIXME: Set a limit on the max number of iterations.
static void BM_strcat(benchmark::State& state) {
  const unsigned N = state.range(0);
  const unsigned s2_sz = 2;
  char *s1 = (char*) malloc(N*sizeof(char));
  char *s2 = (char*) malloc(s2_sz*sizeof(char));
  fillRandomChars(s1, s1+1, true);
  fillRandomChars(s2, s2+s2_sz, false);
  unsigned s1_sz = 1;
  while (state.KeepRunning()) {
    // searching for all the elements.
    // FIXME: strcat is tricky because it keeps concatenating
    // until the timer stops, that corrupts memory.
    benchmark::DoNotOptimize(strcat(s1, s2));
    s1_sz += s2_sz;
    if (s1_sz >= N) {
      state.SkipWithError("Memory corruption");
    }
  }
  free(s1);
  free(s2);
  state.SetComplexityN(N);
}

// Linear search on a sequence
static void BM_strchr(benchmark::State& state) {
  const unsigned N = state.range(0);
  char s1[N];
  char s2 = '1';
  fillRandomChars(s1, s1+N, true);
  while (state.KeepRunning()) {
    // searching for all the elements.
    benchmark::DoNotOptimize(strchr(s1, s2));
  }
  state.SetComplexityN(N);
}

static void BM_strcmp(benchmark::State& state) {
  const unsigned N = state.range(0);
  char *s1 = (char*) malloc(N*sizeof(char));
  char *s2 = (char*) malloc(N/16*sizeof(char));
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, true);
  unsigned i = 0;
  while (state.KeepRunning()) {
    // strcmp at varying positions
    benchmark::DoNotOptimize(strcmp(s1+(i++%N), s2));
  }
  free(s1);
  free(s2);
  state.SetComplexityN(N);
}

static void BM_strcpy(benchmark::State& state) {
  const unsigned N = state.range(0);
  char *s1 = (char*) malloc(N*sizeof(char));
  char *s2 = (char*) malloc(N/16*sizeof(char));
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, true);
  unsigned i = 0;
  while (state.KeepRunning()) {
    // strcpy at varying positions.
    const unsigned offset = (i++%N)/2;
    benchmark::DoNotOptimize(strcpy(s1 + offset, s2));
  }
  free(s1);
  free(s2);
  state.SetComplexityN(N);
}

static void BM_strlen(benchmark::State& state) {
  const unsigned N = state.range(0);
  char *s1 = (char*) malloc(N*sizeof(char));
  char *s2 = (char*) malloc(N/16*sizeof(char));
  fillRandomChars(s1, s1+N, true);
  fillRandomChars(s2, s2+N/16, true);
  unsigned i = 0;
  while (state.KeepRunning()) {
    // strlen at varying positions.
    benchmark::DoNotOptimize(strlen(s1+i++));
  }
  free(s1);
  free(s2);
  state.SetComplexityN(N);
}

static const int MSize = L2;
COMPLEXITY_BENCHMARK(BM_strstr, MSize);
COMPLEXITY_BENCHMARK(BM_strcat, MSize);
COMPLEXITY_BENCHMARK(BM_strchr, MSize);
COMPLEXITY_BENCHMARK(BM_strcmp, MSize);
COMPLEXITY_BENCHMARK(BM_strcpy, MSize);
COMPLEXITY_BENCHMARK(BM_strlen, MSize);
BENCHMARK_MAIN()
<|endoftext|>


<commit_before>#include "catch.hpp"
#include "luapp11/lua.hpp"

TEST_CASE("global_test/protected", "Protected Calls") {

}

TEST_CASE("global_test/unprotected", "Unprotected Calls") {

}<commit_msg>Remove root_test.<commit_after><|endoftext|>


<commit_before>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>

class bitset
{
public:
	explicit bitset(size_t size) /*strong*/;

	bitset(bitset const & other) = delete;
	auto operator =(bitset const & other)->bitset & = delete;

	bitset(bitset && other) = delete;
	auto operator =(bitset && other)->bitset & = delete;

	auto set(size_t index) /*strong*/ -> void;
	auto reset(size_t index) /*strong*/ -> void;
	auto test(size_t index) /*strong*/ -> bool;

	auto size() /*noexcept*/ -> size_t;
	auto counter() /*noexcept*/ -> size_t;
private:
	std::unique_ptr<bool[]>  ptr_;
	size_t size_;
	size_t counter_;
};

bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0){}

auto bitset::set(size_t index)->void {
	if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; }
	else throw("bad_index");
}

auto bitset::reset(size_t index)->void {
	if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; }
	else throw("bad_index");
}

auto bitset::test(size_t index)->bool {
	if (index >= 0 && index < size_) return !ptr_[index];
	else throw("bad_index");
}

auto bitset::size()->size_t{ return size_; }

auto bitset::counter()->size_t{ return counter_; }

template <typename T>
class allocator{
public:
	explicit allocator(std::size_t size = 0) /*strong*/;
	allocator(allocator const & other) /*strong*/;
	auto operator =(allocator const & other)->allocator & = delete;
	~allocator();

	auto resize() /*strong*/ -> void;

	auto construct(T * ptr, T const & value) /*strong*/ -> void;
	auto destroy(T * ptr) /*noexcept*/ -> void;

	auto get() /*noexcept*/ -> T *;
	auto get() const /*noexcept*/ -> T const *;

	auto count() const /*noexcept*/ -> size_t;
	auto full() const /*noexcept*/ -> bool;
	auto empty() const /*noexcept*/ -> bool;
	auto swap(allocator & other) /*noexcept*/ -> void;
private:
	auto destroy(T * first, T * last) /*noexcept*/ -> void;
	size_t count_;
	T * ptr_;
	size_t size_;
	std::unique_ptr<bitset> map_;
};

template<typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)operator new(size*sizeof(T))), size_(size), map_(std::make_unique<bitset>(size)), count_(0) {}

template<typename T>
allocator<T>::allocator(allocator const& other) : allocator<T>(other.size_) {
	for (size_t i = 0; i < other.count_; i++) if(map_->test(i)) construct(ptr_ + i, other.ptr_[i]);
}

template<typename T>
allocator<T>::~allocator(){
	if (this->count() > 0) {
		destroy(ptr_, ptr_ + size_);
	}
	operator delete(ptr_);
}

template<typename T>
auto allocator<T>::resize()->void{
	allocator<T> al(size_ * 2 + (size_ == 0));
	for (size_t i = 0; i < size_; ++i) if (al.map_->test(i)) al.construct(al.get() + i, ptr_[i]);
	al.swap(*this);
}

template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void{
	if (ptr >= ptr_&&ptr < ptr_ + size_){
		new(ptr)T(value);
		map_->set(ptr - ptr_);
		++count_;
	}
	else { throw("error"); }
}

template<typename T>
auto allocator<T>::destroy(T* ptr)->void{
	if (!map_->test(ptr - ptr_) && ptr >= ptr_&&ptr <= ptr_ + this->count())
	{
		ptr->~T();
		map_->reset(ptr - ptr_);
		--count_;
	}
}

template<typename T>
auto allocator<T>::get()-> T* { return ptr_; }

template<typename T>
auto allocator<T>::get() const -> T const * { return ptr_; }

template<typename T>
auto allocator<T>::count() const -> size_t{ return count_; }

template<typename T>
auto allocator<T>::full() const -> bool { return (map_->counter() == size_); }

template<typename T>
auto allocator<T>::empty() const -> bool { return (map_->counter() == 0); }

template<typename T>
auto allocator<T>::destroy(T * first, T * last)->void{
	if (first >= ptr_&&last <= ptr_ + this->count())
	for (; first != last; ++first) {
		destroy(&*first);
	}
}

template<typename T>
auto allocator<T>::swap(allocator & other)->void{
	std::swap(ptr_, other.ptr_);
	std::swap(size_, other.size_);
	std::swap(map_, other.map_);
	std::swap(count_, other.count_);
}

template <typename T>
class stack {
public:
	explicit stack(size_t size = 0);
	stack(stack const & other); /*strong*/
	auto operator =(stack const & other) /*strong*/ -> stack &;

	auto empty() const /*noexcept*/ -> bool;
	auto count() const /*noexcept*/ -> size_t;

	auto push(T const & value) /*strong*/ -> void;
	auto pop() /*strong*/ -> std::shared_ptr<T>;
	//auto top()const -> const T&;

private:
	allocator<T> allocator_;
	auto throw_is_empty()/*strong*/ const -> void;
	mutable std::mutex m;
};

template <typename T>
stack<T>::stack(size_t size) : allocator_(size), m() {};

template <typename T>
stack<T>::stack(stack const & other) : allocator_(0), m()
{
	std::lock_guard<std::mutex> locker(other.m);
	allocator_.swap(allocator<T>(other.allocator_));
}

template <typename T>
auto stack<T>::operator=(const stack &other)->stack&
{
	if (this != &other)
	{
		std::lock(m, other.m);
		std::lock_guard<std::mutex> locker1(m, std::adopt_lock);
		std::lock_guard<std::mutex> locker2(other.m, std::adopt_lock);
		(allocator<T>(other.allocator_)).swap(allocator_);
	}
	return *this;
}

template<typename T>
auto stack<T>::empty() const->bool
{
	std::lock_guard<std::mutex> locker(m);
	return (allocator_.count() == 0);
}

template <typename T>
auto stack<T>::count() const ->size_t
{

	std::lock_guard<std::mutex> locker(m);
	return allocator_.count();
}

template <typename T>
auto stack<T>::push(T const &val)->void
{

	std::lock_guard<std::mutex> locker(m);
	if (allocator_.full())
	{
		allocator_.resize();
	}
	allocator_.construct(allocator_.get() + allocator_.count(), val);
}

template <typename T>
auto stack<T>::pop()->std::shared_ptr<T>
{
	std::lock_guard<std::mutex> locker(m);
	if (allocator_.count() == 0) throw_is_empty();
	std::shared_ptr<T> top_(std::make_shared<T>(std::move(allocator_.get()[allocator_.count() - 1])));
	allocator_.destroy(allocator_.get() + allocator_.count() - 1);
	return top_;
}
template <typename T>
auto stack<T>::throw_is_empty()const->void
{

	std::lock_guard<std::mutex> locker(m);
	throw("EMPTY!");
}
#endif
<commit_msg>Update stack.hpp<commit_after>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>
class bitset
{
public:
	explicit
		bitset(size_t size) /*strong*/;

	bitset(bitset const & other) = delete;
	auto operator =(bitset const & other)->bitset & = delete;

	bitset(bitset && other) = delete;
	auto operator =(bitset && other)->bitset & = delete;

	auto set(size_t index) /*strong*/ -> void;
	auto reset(size_t index) /*strong*/ -> void;
	auto test(size_t index) /*strong*/ -> bool;

	auto size() const /*noexcept*/ -> size_t;
	auto counter() const /*noexcept*/ -> size_t;

private:
	std::unique_ptr<bool[]>  ptr_;
	size_t size_;
	size_t counter_;
};

bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}

auto bitset::set(size_t index) -> void
{
	if (index < size_) {
		ptr_[index] = true;
		++counter_;
	}
	else throw("false_index");
}

auto bitset::reset(size_t index) -> void
{
	if (index < size_)
	{
		ptr_[index] = false;
		--counter_;
	}
	else throw("false_index");
}

auto bitset::test(size_t index) -> bool
{
	if (index < size_)
	{
		return !ptr_[index];
	}
	else throw("false_index");

}
auto bitset::size() const -> size_t
{
	return size_;
}

auto bitset::counter() const -> size_t
{
	return counter_;
}

template <typename T>
class allocator
{
public:
	explicit
		allocator(std::size_t size = 0) /*strong*/;
	allocator(allocator const & other) /*strong*/;
	auto operator =(allocator const & other)->allocator & = delete;
	~allocator();

	auto resize() /*strong*/ -> void;

	auto construct(T * ptr, T const & value) /*strong*/ -> void;
	auto destroy(T * ptr) /*noexcept*/ -> void;

	auto get() /*noexcept*/ -> T *;
	auto get() const /*noexcept*/ -> T const *;

	auto count() const /*noexcept*/ -> size_t;
	auto full() const /*noexcept*/ -> bool;
	auto empty() const /*noexcept*/ -> bool;
	auto swap(allocator & other) /*noexcept*/ -> void;
private:
	auto destroy(T * first, T * last) /*noexcept*/ -> void;

	T * ptr_;
	size_t size_;
	std::unique_ptr<bitset> map_;
};
template <typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};

template<typename T>
allocator<T>::allocator(allocator const& other) :
	allocator<T>(other.size_) {
	for (size_t i = 0; i < size_; ++i)
		if (other.map_->test(i))
			construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator() {
	destroy(ptr_, ptr_ + size_);
	operator delete(ptr_);
}

template<typename T>
auto allocator<T>::resize() -> void
{
	allocator<T> buff(size_ * 2 + (size_ == 0));
	for (size_t i = 0; i < size_; ++i) construct(buff.ptr_ + i, ptr_[i]);
	this->swap(buff);
}

template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void {
	if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) {
		new(ptr)T(value);
		map_->set(ptr - ptr_);
	}
	else throw("error");
}

template<typename T>
auto allocator<T>::destroy(T * ptr) -> void {
	if (ptr >= ptr_&&ptr <= ptr_ + this->size_) {
		if (!map_->test(ptr - ptr_)) {
			ptr->~T();
			map_->reset(ptr - ptr_);
		}
	}
	else throw("error");
}

template<typename T>
auto allocator<T>::destroy(T * first, T * last) -> void
{
	if (first >= ptr_&&last <= ptr_ + this->size_)
		for (; first != last; ++first) {
			destroy(&*first);
		}
}

template<typename T>
auto allocator<T>::get()-> T* {
	return ptr_;
}

template<typename T>
auto allocator<T>::get() const -> T const * {
	return ptr_;
}

template<typename T>
auto allocator<T>::count() const -> size_t
{
	return map_->counter();
}

template<typename T>
auto allocator<T>::full() const -> bool
{
	return map_->counter() == size_;
}

template<typename T>
auto allocator<T>::empty() const -> bool
{
	return map_->counter() == 0;
}

template<typename T>
auto allocator<T>::swap(allocator & other) -> void {
	std::swap(ptr_, other.ptr_);
	std::swap(map_, other.map_);
	std::swap(size_, other.size_);
	std::swap(count_, other.count_);
}
template <typename T>
class stack
{
public:
	explicit
	stack(size_t size = 0);
	stack(stack const & other);
	auto operator =(stack const & other) /*strong*/ -> stack &;

	auto empty() const /*noexcept*/ -> bool;
	auto count() const /*noexcept*/ -> size_t;

	auto push(T const & value) /*strong*/ -> void;
	auto pop() /*strong*/ -> void;
	auto top() /*strong*/ -> T &;
	auto top() const /*strong*/ -> T const &;

private:
	allocator<T> allocator_;
	mutable std::mutex m;
	auto throw_is_empty() const -> void;
};

template <typename T>
size_t stack<T>::count() const
{
	//std::lock_guard<std::mutex> locker(m);
	return allocator_.count();
}
template <typename T>
stack<T>::stack(size_t size) :allocator_(size), m() {}

template <typename T>
stack<T>::stack(stack const & other) : allocator_(0), m() {
std::lock_guard<std::mutex> locker(other.m);
allocator_.swap(allocator<T>(other.allocator_));
}
template <typename T>
void stack<T>::push(T const &item) {
	std::lock_guard<std::mutex> locker(m);
	if (allocator_.full()) allocator_.resize();
	allocator_.construct(allocator_.get() + this->count(), item);
}
template<typename T>
void stack<T>::pop()
{
	std::lock_guard<std::mutex> locker(m);
	if (this->count() > 0)
		allocator_.destroy(allocator_.get() + (this->count() - 1));
	else throw_is_empty();
}
template<typename T>
auto stack<T>::top() -> T &
{
	std::lock_guard<std::mutex> locker(m);
	if (allocator_.count() == 0) {
		throw_is_empty();
	}
	return (*(allocator_.get() + allocator_.count() - 1));
}
template<typename T>
auto stack<T>::top() const -> T const &
{
	std::lock_guard<std::mutex> locker(m);
	if (allocator_.count() == 0) {
		throw_is_empty();
	}
	return (*(allocator_.get() + allocator_.count() - 1));
}

template<typename T>
auto stack<T>::throw_is_empty() const -> void
{
	throw("Stack is empty!");
}

template<typename T>
auto stack<T>::operator =(stack const & right)-> stack & {
	if (this != &right) {
		std::lock(m, right.m);
		std::lock_guard<std::mutex> locker1(m, std::adopt_lock);
		std::lock_guard<std::mutex> locker2(right.m, std::adopt_lock);
		allocator<T>(right.allocator_).swap(allocator_);
	}
	return *this;
}

#endif
<|endoftext|>


<commit_before>#include "peercred.h"

// POSIX
#include <sys/socket.h>
#include <sys/un.h>

// PDTK
#include <cxxutils/error_helpers.h>

#if defined(SO_PEERCRED) // Linux
#pragma message("Information: using SO_PEERCRED code")

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  (void)timeout;
  struct ucred data;
  socklen_t len = sizeof(data);

  int rval = getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &data, &len);

  if(len != sizeof(data))
    rval = posix::error(std::errc::invalid_argument);

  if(rval == posix::success_response)
  {
    cred.pid = data.pid;
    cred.uid = data.uid;
    cred.gid = data.gid;
  }
  return rval;
}

#elif defined(__sun) && defined(__SVR4) // Solaris
#pragma message("Information: using Solaris code")

#include <ucred.h>

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  (void)timeout;
  uproccred_t* data = nullptr;

  int rval = ::getpeerucred(socket, &data);

  if(rval == posix::success_response)
  {
    cred.pid = ucred_getpid (data);
    cred.uid = ucred_geteuid(data);
    cred.gid = ucred_getegid(data);
    ucred_free(data);
    if (cred.pid == pid_t(-1) ||
        cred.uid == uid_t(-1) ||
        cred.gid == gid_t(-1))
      rval = posix::error_response;
  }
  return rval;
}

#elif defined(LOCAL_PEEREID) // some BSDs/Darwin?
#pragma message("Information: using LOCAL_PEEREID code")

#include <sys/un.h>

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  (void)timeout;
  struct unpcbid data;
  socklen_t len = sizeof(data);

  int rval = getsockopt(socket, SOL_SOCKET, LOCAL_PEEREID, &data, &len);

  if(len != sizeof(data))
    rval = posix::error(std::errc::invalid_argument);

  if(rval == posix::success_response)
  {
    cred.pid = data.unp_pid;
    cred.uid = data.unp_euid;
    cred.gid = data.unp_egid;
  }
  return rval;
}

#elif defined(SCM_CREDS) // *BSD/Darwin/Hurd
#pragma message("Information: using SCM_CREDS code")

#include <memory>

#if defined(LOCAL_CREDS) && !defined(SO_PASSCRED)
# define SO_PASSCRED  LOCAL_CREDS
#endif

#ifndef SOL_SOCKET
# define SOL_SOCKET   0
#endif

#if defined(__FreeBSD__)
typedef sockcred creds_t;
#elif defined(__NetBSD__)
typedef cred creds_t;
#endif

#if !defined(SOCKCREDSIZE)
#define SOCKCREDSIZE(x)   CMSG_SPACE(sizeof(creds_t) + (sizeof(gid_t) * x))
#endif

// size = SOCKCREDSIZE(((creds_t*)CMSG_DATA(cmptr))->sc_ngroups);

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  return posix::error_response;
  /*
  static const int enable = 1;

  ::setsockopt(socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable));

  msghdr header = {};
  iovec iov = { nullptr, 0 };
  std::unique_ptr<char> aux_buffer(new char[CMSG_SPACE(sizeof(creds_t))]);

  header.msg_iov = &iov;
  header.msg_iovlen = 1;
  header.msg_control = aux_buffer.get();
  header.msg_controllen = CMSG_SPACE(sizeof(creds_t));

   cmsg_len = CMSG_LEN(SOCKCREDSIZE(ngroups))
                     cmsg_level = SOL_SOCKET
                     cmsg_type = SCM_CREDS

  posix::ssize_t byte_count = posix::recvmsg(socket, &header, 0);

  if(!byte_count ||
     byte_count == posix::error_response)
    return false;

  cmsghdr* cmsg = CMSG_FIRSTHDR(&header);
  if(header.msg_controllen != CMSG_SPACE(sizeof(creds_t)))

      cmsg->cmsg_level == SOL_SOCKET &&
      cmsg->cmsg_type == SCM_CREDS &&
      cmsg->cmsg_len == CMSG_LEN(sizeof(creds_t));
      */
}

#elif defined(__unix__)

#error no code yet for your operating system. :(

#else
#error Unsupported platform! >:(
#endif
<commit_msg>clean up<commit_after>#include "peercred.h"

// POSIX
#include <sys/socket.h>
#include <sys/un.h>

// PDTK
#include <cxxutils/error_helpers.h>

#if defined(SO_PEERCRED) // Linux
#pragma message("Information: using SO_PEERCRED code")

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  (void)timeout;
  struct ucred data;
  socklen_t len = sizeof(data);

  int rval = getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &data, &len);

  if(len != sizeof(data))
    rval = posix::error(std::errc::invalid_argument);

  if(rval == posix::success_response)
  {
    cred.pid = data.pid;
    cred.uid = data.uid;
    cred.gid = data.gid;
  }
  return rval;
}

#elif defined(__sun) && defined(__SVR4) // Solaris
#pragma message("Information: using Solaris code")

#include <ucred.h>

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  (void)timeout;
  uproccred_t* data = nullptr;

  int rval = ::getpeerucred(socket, &data);

  if(rval == posix::success_response)
  {
    cred.pid = ucred_getpid (data);
    cred.uid = ucred_geteuid(data);
    cred.gid = ucred_getegid(data);
    ucred_free(data);
    if (cred.pid == pid_t(-1) ||
        cred.uid == uid_t(-1) ||
        cred.gid == gid_t(-1))
      rval = posix::error_response;
  }
  return rval;
}

#elif defined(LOCAL_PEEREID) // NetBSD
#pragma message("Information: using LOCAL_PEEREID code")

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  (void)timeout;
  struct unpcbid data;
  socklen_t len = sizeof(data);

  int rval = getsockopt(socket, SOL_SOCKET, LOCAL_PEEREID, &data, &len);

  if(len != sizeof(data))
    rval = posix::error(std::errc::invalid_argument);

  if(rval == posix::success_response)
  {
    cred.pid = data.unp_pid;
    cred.uid = data.unp_euid;
    cred.gid = data.unp_egid;
  }
  return rval;
}

#elif defined(SCM_CREDS) // *BSD/Darwin/Hurd
#pragma message("Information: using SCM_CREDS code")

#include <memory>

#if defined(LOCAL_CREDS) && !defined(SO_PASSCRED)
# define SO_PASSCRED  LOCAL_CREDS
#endif

#ifndef SOL_SOCKET
# define SOL_SOCKET   0
#endif

#if defined(__FreeBSD__)
typedef sockcred creds_t;
#elif defined(__NetBSD__)
typedef cred creds_t;
#endif

#if !defined(SOCKCREDSIZE)
#define SOCKCREDSIZE(x)   CMSG_SPACE(sizeof(creds_t) + (sizeof(gid_t) * x))
#endif

// size = SOCKCREDSIZE(((creds_t*)CMSG_DATA(cmptr))->sc_ngroups);

int peercred(int socket, proccred_t& cred, int timeout) noexcept
{
  return posix::error_response;
  /*
  static const int enable = 1;

  ::setsockopt(socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable));

  msghdr header = {};
  iovec iov = { nullptr, 0 };
  std::unique_ptr<char> aux_buffer(new char[CMSG_SPACE(sizeof(creds_t))]);

  header.msg_iov = &iov;
  header.msg_iovlen = 1;
  header.msg_control = aux_buffer.get();
  header.msg_controllen = CMSG_SPACE(sizeof(creds_t));

   cmsg_len = CMSG_LEN(SOCKCREDSIZE(ngroups))
                     cmsg_level = SOL_SOCKET
                     cmsg_type = SCM_CREDS

  posix::ssize_t byte_count = posix::recvmsg(socket, &header, 0);

  if(!byte_count ||
     byte_count == posix::error_response)
    return false;

  cmsghdr* cmsg = CMSG_FIRSTHDR(&header);
  if(header.msg_controllen != CMSG_SPACE(sizeof(creds_t)))

      cmsg->cmsg_level == SOL_SOCKET &&
      cmsg->cmsg_type == SCM_CREDS &&
      cmsg->cmsg_len == CMSG_LEN(sizeof(creds_t));
      */
}

#elif defined(__unix__)

#error no code yet for your operating system. :(

#else
#error Unsupported platform! >:(
#endif
<|endoftext|>