<commit_before>#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <QWebSocket>
#include <QtTest/QtTest>

#include <LoginDialog.hpp>
#include <CommunicationManagerMock.hpp>
#include <ui_LoginDialog.h> // to get loginDialog UI definition

using namespace testing;

struct LoginDialogTestSuite : public ::testing::Test
{
    LoginDialogTestSuite();
    StrictMock<CommunicationManagerMock> communicationManagerMock;
    StrictMock<QWebSocket> webSocketMock;
    LoginDialog m_sut;
};

LoginDialogTestSuite::LoginDialogTestSuite()
    : communicationManagerMock{},
      webSocketMock{},
      m_sut(communicationManagerMock, webSocketMock)
{}

TEST_F(LoginDialogTestSuite, SuccesServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    EXPECT_CALL(communicationManagerMock, handle());
    emit webSocketMock.connected();
    EXPECT_EQ(1, buttonSpy.count());
}

TEST_F(LoginDialogTestSuite, SuccesAfterStateChangeServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    EXPECT_CALL(communicationManagerMock, handle());
    emit webSocketMock.stateChanged(QAbstractSocket::ConnectedState);
    EXPECT_EQ(1, buttonSpy.count());
}

TEST_F(LoginDialogTestSuite, FailAfterStateChangeServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    EXPECT_CALL(communicationManagerMock, handle()).Times(0);
    emit webSocketMock.stateChanged(QAbstractSocket::ConnectingState);
    EXPECT_EQ(1, buttonSpy.count());
}

TEST_F(LoginDialogTestSuite, FailServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    EXPECT_CALL(communicationManagerMock, handle()).Times(0);
    EXPECT_EQ(1, buttonSpy.count());
}

#include "LoginDialogTestSuite.moc"
<commit_msg>remove unused expectations<commit_after>#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <QWebSocket>
#include <QtTest/QtTest>

#include <LoginDialog.hpp>
#include <CommunicationManagerMock.hpp>
#include <ui_LoginDialog.h> // to get loginDialog UI definition

using namespace testing;

struct LoginDialogTestSuite : public ::testing::Test
{
    LoginDialogTestSuite();
    StrictMock<CommunicationManagerMock> communicationManagerMock;
    StrictMock<QWebSocket> webSocketMock;
    LoginDialog m_sut;
};

LoginDialogTestSuite::LoginDialogTestSuite()
    : communicationManagerMock{},
      webSocketMock{},
      m_sut(communicationManagerMock, webSocketMock)
{}

TEST_F(LoginDialogTestSuite, SuccesServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    EXPECT_CALL(communicationManagerMock, handle());
    emit webSocketMock.connected();
    EXPECT_EQ(1, buttonSpy.count());
}

TEST_F(LoginDialogTestSuite, SuccesAfterStateChangeServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    EXPECT_CALL(communicationManagerMock, handle());
    emit webSocketMock.stateChanged(QAbstractSocket::ConnectedState);
    EXPECT_EQ(1, buttonSpy.count());
}

TEST_F(LoginDialogTestSuite, FailAfterStateChangeServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    emit webSocketMock.stateChanged(QAbstractSocket::ConnectingState);
    EXPECT_EQ(1, buttonSpy.count());
}

TEST_F(LoginDialogTestSuite, FailServerConnection)
{
    QSignalSpy buttonSpy(m_sut.getUi()->login, SIGNAL(clicked(bool)));
    QTest::mouseClick(m_sut.getUi()->login, Qt::LeftButton);

    EXPECT_EQ(1, buttonSpy.count());
}

#include "LoginDialogTestSuite.moc"
<|endoftext|>


<commit_before>// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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 <stdlib.h>

#include "v8.h"
#include "macro-assembler.h"
#include "mips/macro-assembler-mips.h"
#include "mips/simulator-mips.h"
#include "cctest.h"

using namespace v8::internal;

typedef void* (*F)(int x, int y, int p2, int p3, int p4);

#define __ masm->

static byte to_non_zero(int n) {
  return static_cast<unsigned>(n) % 255 + 1;
}

static bool all_zeroes(const byte* beg, const byte* end) {
  CHECK(beg);
  CHECK(beg <= end);
  while (beg < end) {
    if (*beg++ != 0)
      return false;
  }
  return true;
}

TEST(CopyBytes) {
  CcTest::InitializeVM();
  Isolate* isolate = Isolate::Current();
  HandleScope handles(isolate);

  const int data_size = 1 * KB;
  size_t act_size;

  // Allocate two blocks to copy data between.
  byte* src_buffer = static_cast<byte*>(OS::Allocate(data_size, &act_size, 0));
  CHECK(src_buffer);
  CHECK(act_size >= static_cast<size_t>(data_size));
  byte* dest_buffer = static_cast<byte*>(OS::Allocate(data_size, &act_size, 0));
  CHECK(dest_buffer);
  CHECK(act_size >= static_cast<size_t>(data_size));

  // Storage for a0 and a1.
  byte* a0_;
  byte* a1_;

  MacroAssembler assembler(isolate, NULL, 0);
  MacroAssembler* masm = &assembler;

  // Code to be generated: The stuff in CopyBytes followed by a store of a0 and
  // a1, respectively.
  __ CopyBytes(a0, a1, a2, a3);
  __ li(a2, Operand(reinterpret_cast<int>(&a0_)));
  __ li(a3, Operand(reinterpret_cast<int>(&a1_)));
  __ sw(a0, MemOperand(a2));
  __ jr(ra);
  __ sw(a1, MemOperand(a3));

  CodeDesc desc;
  masm->GetCode(&desc);
  Object* code = isolate->heap()->CreateCode(
      desc,
      Code::ComputeFlags(Code::STUB),
      Handle<Code>())->ToObjectChecked();
  CHECK(code->IsCode());

  ::F f = FUNCTION_CAST< ::F>(Code::cast(code)->entry());

  // Initialise source data with non-zero bytes.
  for (int i = 0; i < data_size; i++) {
    src_buffer[i] = to_non_zero(i);
  }

  const int fuzz = 11;

  for (int size = 0; size < 600; size++) {
    for (const byte* src = src_buffer; src < src_buffer + fuzz; src++) {
      for (byte* dest = dest_buffer; dest < dest_buffer + fuzz; dest++) {
        memset(dest_buffer, 0, data_size);
        CHECK(dest + size < dest_buffer + data_size);
        (void) CALL_GENERATED_CODE(f, reinterpret_cast<int>(src),
                                      reinterpret_cast<int>(dest), size, 0, 0);
        // a0 and a1 should point at the first byte after the copied data.
        CHECK_EQ(src + size, a0_);
        CHECK_EQ(dest + size, a1_);
        // Check that we haven't written outside the target area.
        CHECK(all_zeroes(dest_buffer, dest));
        CHECK(all_zeroes(dest + size, dest_buffer + data_size));
        // Check the target area.
        CHECK_EQ(0, memcmp(src, dest, size));
      }
    }
  }

  // Check that the source data hasn't been clobbered.
  for (int i = 0; i < data_size; i++) {
    CHECK(src_buffer[i] == to_non_zero(i));
  }
}

#undef __
<commit_msg>MIPS: Add NaN test to cctest/test-macro-assembler-mips.<commit_after>// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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 <stdlib.h>

#include "v8.h"
#include "macro-assembler.h"
#include "mips/macro-assembler-mips.h"
#include "mips/simulator-mips.h"
#include "cctest.h"

using namespace v8::internal;

typedef void* (*F)(int x, int y, int p2, int p3, int p4);

#define __ masm->

static byte to_non_zero(int n) {
  return static_cast<unsigned>(n) % 255 + 1;
}

static bool all_zeroes(const byte* beg, const byte* end) {
  CHECK(beg);
  CHECK(beg <= end);
  while (beg < end) {
    if (*beg++ != 0)
      return false;
  }
  return true;
}

TEST(CopyBytes) {
  CcTest::InitializeVM();
  Isolate* isolate = Isolate::Current();
  HandleScope handles(isolate);

  const int data_size = 1 * KB;
  size_t act_size;

  // Allocate two blocks to copy data between.
  byte* src_buffer = static_cast<byte*>(OS::Allocate(data_size, &act_size, 0));
  CHECK(src_buffer);
  CHECK(act_size >= static_cast<size_t>(data_size));
  byte* dest_buffer = static_cast<byte*>(OS::Allocate(data_size, &act_size, 0));
  CHECK(dest_buffer);
  CHECK(act_size >= static_cast<size_t>(data_size));

  // Storage for a0 and a1.
  byte* a0_;
  byte* a1_;

  MacroAssembler assembler(isolate, NULL, 0);
  MacroAssembler* masm = &assembler;

  // Code to be generated: The stuff in CopyBytes followed by a store of a0 and
  // a1, respectively.
  __ CopyBytes(a0, a1, a2, a3);
  __ li(a2, Operand(reinterpret_cast<int>(&a0_)));
  __ li(a3, Operand(reinterpret_cast<int>(&a1_)));
  __ sw(a0, MemOperand(a2));
  __ jr(ra);
  __ sw(a1, MemOperand(a3));

  CodeDesc desc;
  masm->GetCode(&desc);
  Object* code = isolate->heap()->CreateCode(
      desc,
      Code::ComputeFlags(Code::STUB),
      Handle<Code>())->ToObjectChecked();
  CHECK(code->IsCode());

  ::F f = FUNCTION_CAST< ::F>(Code::cast(code)->entry());

  // Initialise source data with non-zero bytes.
  for (int i = 0; i < data_size; i++) {
    src_buffer[i] = to_non_zero(i);
  }

  const int fuzz = 11;

  for (int size = 0; size < 600; size++) {
    for (const byte* src = src_buffer; src < src_buffer + fuzz; src++) {
      for (byte* dest = dest_buffer; dest < dest_buffer + fuzz; dest++) {
        memset(dest_buffer, 0, data_size);
        CHECK(dest + size < dest_buffer + data_size);
        (void) CALL_GENERATED_CODE(f, reinterpret_cast<int>(src),
                                      reinterpret_cast<int>(dest), size, 0, 0);
        // a0 and a1 should point at the first byte after the copied data.
        CHECK_EQ(src + size, a0_);
        CHECK_EQ(dest + size, a1_);
        // Check that we haven't written outside the target area.
        CHECK(all_zeroes(dest_buffer, dest));
        CHECK(all_zeroes(dest + size, dest_buffer + data_size));
        // Check the target area.
        CHECK_EQ(0, memcmp(src, dest, size));
      }
    }
  }

  // Check that the source data hasn't been clobbered.
  for (int i = 0; i < data_size; i++) {
    CHECK(src_buffer[i] == to_non_zero(i));
  }
}

static void TestNaN(const char *code) {
  // NaN value is different on MIPS and x86 architectures, and TEST(NaNx)
  // tests checks the case where a x86 NaN value is serialized into the
  // snapshot on the simulator during cross compilation.
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> context = CcTest::NewContext(PRINT_EXTENSION);
  v8::Context::Scope context_scope(context);

  v8::Local<v8::Script> script = v8::Script::Compile(v8_str(code));
  v8::Local<v8::Object> result = v8::Local<v8::Object>::Cast(script->Run());
  // Have to populate the handle manually, as it's not Cast-able.
  i::Handle<i::JSObject> o =
      v8::Utils::OpenHandle<v8::Object, i::JSObject>(result);
  i::Handle<i::JSArray> array1(reinterpret_cast<i::JSArray*>(*o));
  i::FixedDoubleArray* a = i::FixedDoubleArray::cast(array1->elements());
  double value = a->get_scalar(0);
  CHECK(std::isnan(value) &&
        i::BitCast<uint64_t>(value) ==
        i::BitCast<uint64_t>(
            i::FixedDoubleArray::canonical_not_the_hole_nan_as_double()));
}

TEST(NaN0) {
  TestNaN(
          "var result;"
          "for (var i = 0; i < 2; i++) {"
          "  result = new Array(Number.NaN, Number.POSITIVE_INFINITY);"
          "}"
          "result;");
}

TEST(NaN1) {
  TestNaN(
          "var result;"
          "for (var i = 0; i < 2; i++) {"
          "  result = [NaN];"
          "}"
          "result;");
}

#undef __
<|endoftext|>


<commit_before>#ifndef BULL_CORE_ASSETS_ASSETMANAGER_HPP
#define BULL_CORE_ASSETS_ASSETMANAGER_HPP

#include <map>

#include <Bull/Core/Memory/String.hpp>
#include <Bull/Core/Pattern/Singleton.hpp>

namespace Bull
{
    template <typename T>
    class BULL_CORE_API AssetManager : public Singleton<AssetManager<T>>
    {
    public:

        /*! \brief Create an Asset and register it the AssetManager
         *
         * \param name The name of the Asset to create
         * \param args Arguments to create the Asset
         *
         * \return The Asset
         *
         */
        template <typename... Args>
        T* createAsset(const String& name, Args&&... args)
        {
            return m_assets[name] = std::make_unique<T>(std::forward<Args>(args)...);
        }

        /*! \brief Register an Asset in the AssetManager
         *
         * \param asset    The Asset to register
         * \param name     The name of the Asset to register
         * \param override True to override the existing Asset
         *
         */
        bool registerAsset(T* asset, const String& name, bool override = true)
        {
            if(!has(name) || override)
            {
                return m_assets.insert(std::make_pair(name, asset)).second;
            }

            return false;
        }

        /*! \brief Tell whether an Asset exists in the AssetManager
         *
         * \param name The name of the Asset to get
         *
         * \return True if the Asset exists
         *
         */
        bool has(const String& name)
        {
            return m_assets.find(name) != m_assets.end();
        }

        /*! \brief Get an Asset
         *
         * \param name The name of the Asset to get
         *
         * \return The Asset
         *
         */
        T* getAsset(const String& name) const
        {
            return m_assets[name].get();
        }

        /*! \brief Delete every Asset
         *
         */
        void clear()
        {
            m_assets.clear();
        }

    private:

        std::map<String, std::unique_ptr<T>> m_assets;
    };
}

#endif // BULL_CORE_ASSETS_ASSETMANAGER_HPP
<commit_msg>[Core/AssetLoader] Fix documentation<commit_after>#ifndef BULL_CORE_ASSETS_ASSETMANAGER_HPP
#define BULL_CORE_ASSETS_ASSETMANAGER_HPP

#include <map>

#include <Bull/Core/Memory/String.hpp>
#include <Bull/Core/Pattern/Singleton.hpp>

namespace Bull
{
    template <typename T>
    class BULL_CORE_API AssetManager : public Singleton<AssetManager<T>>
    {
    public:

        /*! \brief Create an Asset and register it the AssetManager
         *
         * \param name The name of the Asset to create
         * \param args Arguments to create the Asset
         *
         * \return The Asset
         *
         */
        template <typename... Args>
        T& createAsset(const String& name, Args&&... args)
        {
            return static_cast<T&>(*(m_assets[name] = std::make_unique<T>(std::forward<Args>(args)...)));
        }

        /*! \brief Register an Asset in the AssetManager
         *
         * \param asset    The Asset to register
         * \param name     The name of the Asset to register
         * \param override True to override the existing Asset
         *
         */
        bool registerAsset(T* asset, const String& name, bool override = true)
        {
            if(!has(name) || override)
            {
                return m_assets.insert(std::make_pair(name, asset)).second;
            }

            return false;
        }

        /*! \brief Remove an Asset from the AssetManager
         *
         * \param name The name of the Asset to remove
         *
         */
        void unregisterAsset(const String& name)
        {
            m_assets.erase(m_assets.find(name));
        }

        /*! \brief Tell whether an Asset exists in the AssetManager
         *
         * \param name The name of the Asset to get
         *
         * \return True if the Asset exists
         *
         */
        bool has(const String& name) const
        {
            return m_assets.find(name) != m_assets.end();
        }

        /*! \brief Get an Asset
         *
         * \param name The name of the Asset to get
         *
         * \return The Asset
         *
         */
        T& getAsset(const String& name)
        {
            if(!has(name))
            {
                return createAsset(name);
            }

            return static_cast<T&>(*m_assets[name]);
        }

        /*! \brief Delete every Asset
         *
         */
        void clear()
        {
            m_assets.clear();
        }

    private:

        std::map<String, std::unique_ptr<T>> m_assets;
    };
}

#endif // BULL_CORE_ASSETS_ASSETMANAGER_HPP
<|endoftext|>


<commit_before>//
// message.hpp
// ***********
//
// Copyright (c) 2019 Sharon W (sharon at aegis dot gg)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//

#pragma once

#include "aegis/config.hpp"
#include "aegis/snowflake.hpp"
#include "aegis/shards/shard.hpp"
#include "aegis/rest/rest_reply.hpp"
#include "aegis/gateway/objects/attachment.hpp"
#include "aegis/gateway/objects/embed.hpp"
#include "aegis/gateway/objects/reaction.hpp"
#include "aegis/gateway/objects/user.hpp"
#include <nlohmann/json.hpp>
#include "aegis/futures.hpp"

namespace aegis
{

struct edit_message_t;

namespace gateway
{

namespace objects
{

class message;

/// \cond TEMPLATES
AEGIS_DECL void from_json(const nlohmann::json& j, objects::message& m);

AEGIS_DECL void to_json(nlohmann::json& j, const objects::message& m);
/// \endcond

/// Type of message
enum message_type
{
    Default = 0,
    RecipientAdd = 1,
    RecipientRemove = 2,
    Call = 3,
    ChannelNameChange = 4,
    ChannelIconChange = 5,
    ChannelPinnedMessage = 6,
    GuildMemberJoin = 7
};

/**\todo Needs documentation
 */
class message
{
public:
    /// Constructor for the message object
    /**
     * @param content String of the message sent
     * @param _channel Pointer of channel object
     * @param _guild Pointer of guild object
     */
    explicit message(const std::string & content, aegis::channel * _channel, aegis::guild * _guild) noexcept
        : _content(content)
        , _channel(_channel)
        , _guild(_guild)
    {
    }

    /// Constructor for the message object
    /**
     * @param _json JSON string of the message object
     * @param bot Pointer of core object
     */
    message(const std::string & _json, aegis::core * _core) noexcept
        : _core(_core)
    {
        from_json(nlohmann::json::parse(_json), *this);
        populate_self();
    }

    /// Constructor for the message object
    /**
     * @param _json JSON object of the message object
     * @param _core Pointer of core object
     */
    message(const nlohmann::json & _json, aegis::core * _core) noexcept
        : _core(_core)
    {
        from_json(_json, *this);
        populate_self();
    }

    /// Constructor for the message object
    /**
     * @param _core Pointer of core object
     */
    message(aegis::core * _core) noexcept
        : _core(_core)
    {
        populate_self();
    }

    /// Set the channel of the message object. This is mostly an internal function
    /// though is left public for lower level use
    /**
     * @param _channel Pointer of the channel to assign the message to
     */
    AEGIS_DECL void set_channel(aegis::channel * _channel)
    {
        this->_channel = _channel;
    }

    /// Set the guild of the message object. This is mostly an internal function
    /// though is left public for lower level use
    /**
     * @param _guild Pointer of the guild to assign the message to
     */
    AEGIS_DECL void set_guild(aegis::guild * _guild)
    {
        this->_guild = _guild;
    }

    message() = default;
    message & operator=(const message &) = default;
    message(const message&) = default;
    message(message && msg) = default;

    /// Comparison of message content
    inline bool operator==(const std::string& rhs)
    {
        return _content == rhs;
    }

    /// Comparison of message content
    inline bool operator!=(const std::string& rhs)
    {
        return !(*this == rhs);
    }

    /// Comparison of message content
    inline bool operator==(const char * rhs)
    {
        return _content == rhs;
    }

    /// Comparison of message content
    inline bool operator!=(const char * rhs)
    {
        return !(*this == rhs);
    }

    std::string timestamp; /**<\todo Needs documentation */
    std::string edited_timestamp; /**<\todo Needs documentation */
    bool tts = false; /**<\todo Needs documentation */
    bool mention_everyone = false; /**<\todo Needs documentation */
    std::vector<snowflake> mentions; /**<\todo Needs documentation */
    std::vector<snowflake> mention_roles; /**<\todo Needs documentation */
    std::vector<objects::attachment> attachments; /**<\todo Needs documentation */
    std::vector<objects::embed> embeds; /**<\todo Needs documentation */
    bool pinned = false; /**<\todo Needs documentation */
    std::vector<objects::reaction> reactions; /**<\todo Needs documentation */
    snowflake nonce; /**<\todo Needs documentation */
    std::string webhook_id; /**<\todo Needs documentation */
    objects::message_type type = Default; /**<\todo Needs documentation */
    user author; /**< author object for this message */

    /// Whether message is a Direct Message
    /**
     * @returns bool
     */
    bool is_dm() const noexcept
    {
        return !!_guild_id;
    }

    /// Whether message is from a bot
    /**
     * @returns bool
     */
    bool is_bot() const noexcept
    {
        return author.is_bot();
    }

    /// Whether message is from a webhook
    /**
     * @returns bool
     */
    bool is_webhook() const noexcept
    {
        return !webhook_id.empty();
    }

    /// Get a reference to the content of the message
    /**
     * @returns const std::string &
     */
    const std::string & get_content() const noexcept
    {
        return _content;
    }

    /// Set the message's content
    /**
     * @param content String of content to set
     */
    void set_content(const std::string & content) noexcept
    {
        _content = content;
    }

    /// Get the ID of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_id() const noexcept
    {
        return _message_id;
    }

    /// Get the Channel ID of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_channel_id() const noexcept
    {
        return _channel_id;
    }

    /// Get the Guild ID of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_guild_id() const noexcept
    {
        return _guild_id;
    }

    /// Get the Member ID of the author of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_author_id() const noexcept
    {
        return _author_id;
    }

    /// Whether the message has a valid guild set. The result of this function
    /// does not determine whether the object was a DM or not
    /// @see is_dm
    /**
     * @returns bool
     */
    bool has_guild() const noexcept
    {
        return _guild != nullptr || _guild_id != 0;
    }

    /// Whether the message has a valid channel set
    /**
     * @returns bool
     */
    bool has_channel() const noexcept
    {
        return _channel != nullptr || _channel_id != 0;
    }

#if !defined(AEGIS_DISABLE_ALL_CACHE)
    /// Whether the message has a valid member set
    /**
     * @returns bool
     */
    bool has_member() const noexcept
    {
        return _user != nullptr || _author_id != 0;
    }
#endif

    /// Get a reference to the guild object this message was sent in
    /**
     * @returns aegis::guild
     */
    AEGIS_DECL aegis::guild & get_guild();

    /// Get a reference to the channel object this message was sent in
    /**
     * @returns aegis::channel
     */
    AEGIS_DECL aegis::channel & get_channel();

#if !defined(AEGIS_DISABLE_ALL_CACHE)
    /// Get a reference to the user object this message was sent by
    /**
     * @returns aegis::user
     */
    AEGIS_DECL aegis::user & get_user();
#endif

    /// Delete this message
    /**
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_message();

    /// Edit this message
    /**
     * @param content String to set the new content to
     * @returns aegis::future<message>
     */
    AEGIS_DECL aegis::future<message> edit(const std::string & content);

    /// Edit this message
    /**
     * @see edit_message_t
     * @param obj Struct of the edit message request
     * @returns aegis::future<message>
     */
    AEGIS_DECL aegis::future<message> edit(edit_message_t & obj);

    /// Add a reaction to this message
    /**
     * @param content String of the emoji to add. Unicode emoji or `emojiname:emoji_id`
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> create_reaction(const std::string & content);

    /// Delete your reaction to this message
    /**
     * @param content String of the emoji to set. Unicode emoji or `emojiname:emoji_id`
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_own_reaction(const std::string & content);

    /// Delete other user reaction to this message (not available for DMs)
    /**
     * @param content String of the emoji to set. Unicode emoji or `emojiname:emoji_id`
     * @param member_id Snowflake of the member to delete the reaction for
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_user_reaction(const std::string & content, const snowflake member_id);

    /// Delete all reactions on this message (not available for DMs)
    /**
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_all_reactions();

    /// Obtain the relevant snowflakes related to this message
    /**
     * Returns { channel_id, guild_id, message_id, author_id }
     * Some may be 0 such as guild for a DM or author for a webhook
     * @returns std::tuple<aegis::snowflake, aegis::snowflake, aegis::snowflake, aegis::snowflake>
     */
    std::tuple<snowflake, snowflake, snowflake, snowflake> get_related_ids() const noexcept
    {
        return std::tuple<snowflake, snowflake, snowflake, snowflake>{ _channel_id, _guild_id, _message_id, _author_id };
    };

private:
    friend AEGIS_DECL void from_json(const nlohmann::json& j, objects::message& m);
    friend AEGIS_DECL void to_json(nlohmann::json& j, const objects::message& m);
    friend class aegis::core;

    AEGIS_DECL void populate_self();

    std::string _content;/**< String of the message contents */
    aegis::channel * _channel = nullptr;/**< Pointer to the channel this message belongs to */
    aegis::guild * _guild = nullptr;/**< Pointer to the guild this message belongs to */
#if !defined(AEGIS_DISABLE_ALL_CACHE)
    aegis::user * _user = nullptr;/**< Pointer to the author of this message */
#endif
    aegis::core * _core = nullptr;
    snowflake _message_id = 0; /**< snowflake of the message */
    snowflake _channel_id = 0; /**< snowflake of the channel this message belongs to */
    snowflake _guild_id = 0; /**< snowflake of the guild this message belongs to */
    snowflake _author_id = 0; /**< snowflake of the author of this message */
};

}

}

}

#if defined(AEGIS_HEADER_ONLY)
#include "aegis/gateway/objects/impl/message.cpp"
#endif
<commit_msg>One too many negations<commit_after>//
// message.hpp
// ***********
//
// Copyright (c) 2019 Sharon W (sharon at aegis dot gg)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//

#pragma once

#include "aegis/config.hpp"
#include "aegis/snowflake.hpp"
#include "aegis/shards/shard.hpp"
#include "aegis/rest/rest_reply.hpp"
#include "aegis/gateway/objects/attachment.hpp"
#include "aegis/gateway/objects/embed.hpp"
#include "aegis/gateway/objects/reaction.hpp"
#include "aegis/gateway/objects/user.hpp"
#include <nlohmann/json.hpp>
#include "aegis/futures.hpp"

namespace aegis
{

struct edit_message_t;

namespace gateway
{

namespace objects
{

class message;

/// \cond TEMPLATES
AEGIS_DECL void from_json(const nlohmann::json& j, objects::message& m);

AEGIS_DECL void to_json(nlohmann::json& j, const objects::message& m);
/// \endcond

/// Type of message
enum message_type
{
    Default = 0,
    RecipientAdd = 1,
    RecipientRemove = 2,
    Call = 3,
    ChannelNameChange = 4,
    ChannelIconChange = 5,
    ChannelPinnedMessage = 6,
    GuildMemberJoin = 7
};

/**\todo Needs documentation
 */
class message
{
public:
    /// Constructor for the message object
    /**
     * @param content String of the message sent
     * @param _channel Pointer of channel object
     * @param _guild Pointer of guild object
     */
    explicit message(const std::string & content, aegis::channel * _channel, aegis::guild * _guild) noexcept
        : _content(content)
        , _channel(_channel)
        , _guild(_guild)
    {
    }

    /// Constructor for the message object
    /**
     * @param _json JSON string of the message object
     * @param bot Pointer of core object
     */
    message(const std::string & _json, aegis::core * _core) noexcept
        : _core(_core)
    {
        from_json(nlohmann::json::parse(_json), *this);
        populate_self();
    }

    /// Constructor for the message object
    /**
     * @param _json JSON object of the message object
     * @param _core Pointer of core object
     */
    message(const nlohmann::json & _json, aegis::core * _core) noexcept
        : _core(_core)
    {
        from_json(_json, *this);
        populate_self();
    }

    /// Constructor for the message object
    /**
     * @param _core Pointer of core object
     */
    message(aegis::core * _core) noexcept
        : _core(_core)
    {
        populate_self();
    }

    /// Set the channel of the message object. This is mostly an internal function
    /// though is left public for lower level use
    /**
     * @param _channel Pointer of the channel to assign the message to
     */
    AEGIS_DECL void set_channel(aegis::channel * _channel)
    {
        this->_channel = _channel;
    }

    /// Set the guild of the message object. This is mostly an internal function
    /// though is left public for lower level use
    /**
     * @param _guild Pointer of the guild to assign the message to
     */
    AEGIS_DECL void set_guild(aegis::guild * _guild)
    {
        this->_guild = _guild;
    }

    message() = default;
    message & operator=(const message &) = default;
    message(const message&) = default;
    message(message && msg) = default;

    /// Comparison of message content
    inline bool operator==(const std::string& rhs)
    {
        return _content == rhs;
    }

    /// Comparison of message content
    inline bool operator!=(const std::string& rhs)
    {
        return !(*this == rhs);
    }

    /// Comparison of message content
    inline bool operator==(const char * rhs)
    {
        return _content == rhs;
    }

    /// Comparison of message content
    inline bool operator!=(const char * rhs)
    {
        return !(*this == rhs);
    }

    std::string timestamp; /**<\todo Needs documentation */
    std::string edited_timestamp; /**<\todo Needs documentation */
    bool tts = false; /**<\todo Needs documentation */
    bool mention_everyone = false; /**<\todo Needs documentation */
    std::vector<snowflake> mentions; /**<\todo Needs documentation */
    std::vector<snowflake> mention_roles; /**<\todo Needs documentation */
    std::vector<objects::attachment> attachments; /**<\todo Needs documentation */
    std::vector<objects::embed> embeds; /**<\todo Needs documentation */
    bool pinned = false; /**<\todo Needs documentation */
    std::vector<objects::reaction> reactions; /**<\todo Needs documentation */
    snowflake nonce; /**<\todo Needs documentation */
    std::string webhook_id; /**<\todo Needs documentation */
    objects::message_type type = Default; /**<\todo Needs documentation */
    user author; /**< author object for this message */

    /// Whether message is a Direct Message
    /**
     * @returns bool
     */
    bool is_dm() const noexcept
    {
        return !_guild_id;
    }

    /// Whether message is from a bot
    /**
     * @returns bool
     */
    bool is_bot() const noexcept
    {
        return author.is_bot();
    }

    /// Whether message is from a webhook
    /**
     * @returns bool
     */
    bool is_webhook() const noexcept
    {
        return !webhook_id.empty();
    }

    /// Get a reference to the content of the message
    /**
     * @returns const std::string &
     */
    const std::string & get_content() const noexcept
    {
        return _content;
    }

    /// Set the message's content
    /**
     * @param content String of content to set
     */
    void set_content(const std::string & content) noexcept
    {
        _content = content;
    }

    /// Get the ID of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_id() const noexcept
    {
        return _message_id;
    }

    /// Get the Channel ID of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_channel_id() const noexcept
    {
        return _channel_id;
    }

    /// Get the Guild ID of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_guild_id() const noexcept
    {
        return _guild_id;
    }

    /// Get the Member ID of the author of the message
    /**
     * @returns aegis::snowflake
     */
    snowflake get_author_id() const noexcept
    {
        return _author_id;
    }

    /// Whether the message has a valid guild set. The result of this function
    /// does not determine whether the object was a DM or not
    /// @see is_dm
    /**
     * @returns bool
     */
    bool has_guild() const noexcept
    {
        return _guild != nullptr || _guild_id != 0;
    }

    /// Whether the message has a valid channel set
    /**
     * @returns bool
     */
    bool has_channel() const noexcept
    {
        return _channel != nullptr || _channel_id != 0;
    }

#if !defined(AEGIS_DISABLE_ALL_CACHE)
    /// Whether the message has a valid member set
    /**
     * @returns bool
     */
    bool has_member() const noexcept
    {
        return _user != nullptr || _author_id != 0;
    }
#endif

    /// Get a reference to the guild object this message was sent in
    /**
     * @returns aegis::guild
     */
    AEGIS_DECL aegis::guild & get_guild();

    /// Get a reference to the channel object this message was sent in
    /**
     * @returns aegis::channel
     */
    AEGIS_DECL aegis::channel & get_channel();

#if !defined(AEGIS_DISABLE_ALL_CACHE)
    /// Get a reference to the user object this message was sent by
    /**
     * @returns aegis::user
     */
    AEGIS_DECL aegis::user & get_user();
#endif

    /// Delete this message
    /**
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_message();

    /// Edit this message
    /**
     * @param content String to set the new content to
     * @returns aegis::future<message>
     */
    AEGIS_DECL aegis::future<message> edit(const std::string & content);

    /// Edit this message
    /**
     * @see edit_message_t
     * @param obj Struct of the edit message request
     * @returns aegis::future<message>
     */
    AEGIS_DECL aegis::future<message> edit(edit_message_t & obj);

    /// Add a reaction to this message
    /**
     * @param content String of the emoji to add. Unicode emoji or `emojiname:emoji_id`
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> create_reaction(const std::string & content);

    /// Delete your reaction to this message
    /**
     * @param content String of the emoji to set. Unicode emoji or `emojiname:emoji_id`
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_own_reaction(const std::string & content);

    /// Delete other user reaction to this message (not available for DMs)
    /**
     * @param content String of the emoji to set. Unicode emoji or `emojiname:emoji_id`
     * @param member_id Snowflake of the member to delete the reaction for
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_user_reaction(const std::string & content, const snowflake member_id);

    /// Delete all reactions on this message (not available for DMs)
    /**
     * @returns aegis::future<rest::rest_reply>
     */
    AEGIS_DECL aegis::future<rest::rest_reply> delete_all_reactions();

    /// Obtain the relevant snowflakes related to this message
    /**
     * Returns { channel_id, guild_id, message_id, author_id }
     * Some may be 0 such as guild for a DM or author for a webhook
     * @returns std::tuple<aegis::snowflake, aegis::snowflake, aegis::snowflake, aegis::snowflake>
     */
    std::tuple<snowflake, snowflake, snowflake, snowflake> get_related_ids() const noexcept
    {
        return std::tuple<snowflake, snowflake, snowflake, snowflake>{ _channel_id, _guild_id, _message_id, _author_id };
    };

private:
    friend AEGIS_DECL void from_json(const nlohmann::json& j, objects::message& m);
    friend AEGIS_DECL void to_json(nlohmann::json& j, const objects::message& m);
    friend class aegis::core;

    AEGIS_DECL void populate_self();

    std::string _content;/**< String of the message contents */
    aegis::channel * _channel = nullptr;/**< Pointer to the channel this message belongs to */
    aegis::guild * _guild = nullptr;/**< Pointer to the guild this message belongs to */
#if !defined(AEGIS_DISABLE_ALL_CACHE)
    aegis::user * _user = nullptr;/**< Pointer to the author of this message */
#endif
    aegis::core * _core = nullptr;
    snowflake _message_id = 0; /**< snowflake of the message */
    snowflake _channel_id = 0; /**< snowflake of the channel this message belongs to */
    snowflake _guild_id = 0; /**< snowflake of the guild this message belongs to */
    snowflake _author_id = 0; /**< snowflake of the author of this message */
};

}

}

}

#if defined(AEGIS_HEADER_ONLY)
#include "aegis/gateway/objects/impl/message.cpp"
#endif
<|endoftext|>


<commit_before>// Copyright (C) 2013-2015 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au

//! \addtogroup arma_rng_cxx11
//! @{

#if defined(ARMA_USE_CXX11)

class arma_rng_cxx11
  {
  public:

  typedef std::mt19937_64::result_type seed_type;

  inline void set_seed(const seed_type val);

  arma_inline int    randi_val();
  arma_inline double randu_val();
  arma_inline double randn_val();

  template<typename eT>
  arma_inline void randn_dual_val(eT& out1, eT& out2);

  template<typename eT>
  inline void randi_fill(eT* mem, const uword N, const int a, const int b);

  inline static int randi_max_val();

  template<typename eT>
  inline void randg_fill(eT* mem, const uword N, const double a, const double b);

  private:

  arma_aligned std::mt19937_64 engine;                           // typedef for std::mersenne_twister_engine with preset parameters

  arma_aligned std::uniform_int_distribution<int>     i_distr;   // by default uses a=0, b=std::numeric_limits<int>::max()

  arma_aligned std::uniform_real_distribution<double> u_distr;   // by default uses [0,1) interval

  arma_aligned std::normal_distribution<double>       n_distr;   // by default uses mean=0.0 and stddev=1.0
  };

inline
void
arma_rng_cxx11::set_seed(const arma_rng_cxx11::seed_type val)
  {
  engine.seed(val);
  }

arma_inline
int
arma_rng_cxx11::randi_val()
  {
  return i_distr(engine);
  }

arma_inline
double
arma_rng_cxx11::randu_val()
  {
  return u_distr(engine);
  }

arma_inline
double
arma_rng_cxx11::randn_val()
  {
  return n_distr(engine);
  }

template<typename eT>
arma_inline
void
arma_rng_cxx11::randn_dual_val(eT& out1, eT& out2)
  {
  out1 = eT( n_distr(engine) );
  out2 = eT( n_distr(engine) );
  }

template<typename eT>
inline
void
arma_rng_cxx11::randi_fill(eT* mem, const uword N, const int a, const int b)
  {
  std::uniform_int_distribution<int> local_i_distr(a, b);

  for(uword i=0; i<N; ++i)
    {
    mem[i] = eT(local_i_distr(engine));
    }
  }

inline
int
arma_rng_cxx11::randi_max_val()
  {
  return std::numeric_limits<int>::max();
  }

template<typename eT>
inline
void
arma_rng_cxx11::randg_fill(eT* mem, const uword N, const double a, const double b)
  {
  std::gamma_distribution<double> g_distr(a,b);

  for(uword i=0; i<N; ++i)
    {
    mem[i] = eT(g_distr(engine));
    }
  }

#endif

//! @}
<commit_msg>workaround for a braindead 'feature' in C++11<commit_after>// Copyright (C) 2013-2016 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by Conrad Sanderson - http://conradsanderson.id.au

//! \addtogroup arma_rng_cxx11
//! @{

#if defined(ARMA_USE_CXX11)

class arma_rng_cxx11
  {
  public:

  typedef std::mt19937_64::result_type seed_type;

  inline void set_seed(const seed_type val);

  arma_inline int    randi_val();
  arma_inline double randu_val();
  arma_inline double randn_val();

  template<typename eT>
  arma_inline void randn_dual_val(eT& out1, eT& out2);

  template<typename eT>
  inline void randi_fill(eT* mem, const uword N, const int a, const int b);

  inline static int randi_max_val();

  template<typename eT>
  inline void randg_fill(eT* mem, const uword N, const double a, const double b);

  private:

  arma_aligned std::mt19937_64 engine;                           // typedef for std::mersenne_twister_engine with preset parameters

  arma_aligned std::uniform_int_distribution<int>     i_distr;   // by default uses a=0, b=std::numeric_limits<int>::max()

  arma_aligned std::uniform_real_distribution<double> u_distr;   // by default uses [0,1) interval

  arma_aligned std::normal_distribution<double>       n_distr;   // by default uses mean=0.0 and stddev=1.0
  };

inline
void
arma_rng_cxx11::set_seed(const arma_rng_cxx11::seed_type val)
  {
  engine.seed(val);

  i_distr.reset();
  u_distr.reset();
  n_distr.reset();
  }

arma_inline
int
arma_rng_cxx11::randi_val()
  {
  return i_distr(engine);
  }

arma_inline
double
arma_rng_cxx11::randu_val()
  {
  return u_distr(engine);
  }

arma_inline
double
arma_rng_cxx11::randn_val()
  {
  return n_distr(engine);
  }

template<typename eT>
arma_inline
void
arma_rng_cxx11::randn_dual_val(eT& out1, eT& out2)
  {
  out1 = eT( n_distr(engine) );
  out2 = eT( n_distr(engine) );
  }

template<typename eT>
inline
void
arma_rng_cxx11::randi_fill(eT* mem, const uword N, const int a, const int b)
  {
  std::uniform_int_distribution<int> local_i_distr(a, b);

  for(uword i=0; i<N; ++i)
    {
    mem[i] = eT(local_i_distr(engine));
    }
  }

inline
int
arma_rng_cxx11::randi_max_val()
  {
  return std::numeric_limits<int>::max();
  }

template<typename eT>
inline
void
arma_rng_cxx11::randg_fill(eT* mem, const uword N, const double a, const double b)
  {
  std::gamma_distribution<double> g_distr(a,b);

  for(uword i=0; i<N; ++i)
    {
    mem[i] = eT(g_distr(engine));
    }
  }

#endif

//! @}
<|endoftext|>


<commit_before>
#include <vector>
#include <map>
#include <iostream>
#include <iomanip>
#include <chrono>
#include <locale>
#include <cassert>
#include <unzip.h>
#include <sstream>

#include "n8igall.h"
#include "utils/DWD_CDC.h"

using namespace std;
using namespace date;

namespace n8igall
{
	struct Sample : public ISample
	{
	private:
		u32 numDimensions;
		double* values;

	public:
		Sample(u32 numDimensions)
			: numDimensions(numDimensions)
			, values(new double[numDimensions])
		{
		}

		virtual ~Sample()
		{
			delete[] values;
		};

		virtual void SetValue(double value, u32 dimension) override
		{
			assert(dimension < numDimensions);
			values[dimension] = value;
		}
	};

	ISample* ISample::Create(u32 numDimensions)
	{
		return new Sample(numDimensions);
	}

	struct GeoTimeSeries : public IGeoTimeSeries
	{
	private:
		double longitude;
		double latitude;
		u32 numDimensions;

		map<day_point, const Sample*> timeSeries;

	public:

		GeoTimeSeries(double longitude, double latitude, u32 numDimensions)
			: longitude(longitude)
			, latitude(latitude)
			, numDimensions(numDimensions)
		{

		}

		virtual ~GeoTimeSeries()
		{
			for (auto sample : timeSeries)
			{
				delete sample.second;
			}
		};

		virtual void AddTimeSample(dayPoint dayPoint, const ISample* sample) override
		{
			timeSeries[dayPoint] = dynamic_cast<const Sample*>(sample);
		}
	};

	IGeoTimeSeries* IGeoTimeSeries::Create(double longitude, double latitude, u32 numDimensions)
	{
		return new GeoTimeSeries(longitude, latitude, numDimensions);
	}

	struct GeoClimateCorrelator : public IGeoClimateCorrelator
	{
	private:
		DWD_CDC dwd_CDC;

	public:
		GeoClimateCorrelator()
		{
		}

		virtual IGeoTimeSeriesClimateCorrelation* DeriveCorrelation(const IGeoTimeSeries* geoTimeSeries) const override
		{
			return NULL;
		}

		virtual ~GeoClimateCorrelator() {}
	};

	IGeoClimateCorrelator* IGeoClimateCorrelator::Create()
	{
		return new GeoClimateCorrelator();
	}
}
<commit_msg>started to prepare station data to shove it into FANN<commit_after>
#include <vector>
#include <map>
#include <iostream>
#include <iomanip>
#include <chrono>
#include <locale>
#include <cassert>
#include <unzip.h>
#include <sstream>

#include "n8igall.h"
#include "utils/DWD_CDC.h"

using namespace std;
using namespace date;

namespace n8igall
{
	struct Sample : public ISample
	{
	protected:
		u32 numDimensions;
		double* values;

		friend struct GeoClimateCorrelator;

	public:
		Sample(u32 numDimensions)
			: numDimensions(numDimensions)
			, values(new double[numDimensions])
		{
		}

		virtual ~Sample()
		{
			delete[] values;
		};

		virtual void SetValue(double value, u32 dimension) override
		{
			assert(dimension < numDimensions);
			values[dimension] = value;
		}
	};

	ISample* ISample::Create(u32 numDimensions)
	{
		return new Sample(numDimensions);
	}

	struct GeoTimeSeries : public IGeoTimeSeries
	{
	protected:
		double longitude;
		double latitude;
		u32 numDimensions;

		map<day_point, const Sample*> timeSeries;

		friend struct GeoClimateCorrelator;

	public:

		GeoTimeSeries(double longitude, double latitude, u32 numDimensions)
			: longitude(longitude)
			, latitude(latitude)
			, numDimensions(numDimensions)
		{

		}

		virtual ~GeoTimeSeries()
		{
			for (auto sample : timeSeries)
			{
				delete sample.second;
			}
		};

		virtual void AddTimeSample(dayPoint dayPoint, const ISample* sample) override
		{
			timeSeries[dayPoint] = dynamic_cast<const Sample*>(sample);
		}
	};

	IGeoTimeSeries* IGeoTimeSeries::Create(double longitude, double latitude, u32 numDimensions)
	{
		return new GeoTimeSeries(longitude, latitude, numDimensions);
	}

	struct GeoClimateCorrelator : public IGeoClimateCorrelator
	{
	private:
		DWD_CDC dwd_CDC;

		const DWD_CDC::Station& FindNearestStation(double lon, double lat) const
		{
			const auto& nearestStation = dwd_CDC.GetStation(0);

			for (size s = 0; s < dwd_CDC.GetNumStations(); s++)
			{
				const auto& station = dwd_CDC.GetStation(s);

				// TODO: check distance
			}

			return nearestStation;
		}

	public:
		GeoClimateCorrelator()
		{
		}

		virtual IGeoTimeSeriesClimateCorrelation* DeriveCorrelation(const IGeoTimeSeries* geoTimeSeries) const override
		{
			const auto* gts = (const GeoTimeSeries*)geoTimeSeries;

			const auto& station = FindNearestStation(gts->longitude, gts->latitude);

			const u32 numDimensions = gts->numDimensions;

			for (const auto& timeSample : gts->timeSeries)
			{
				const auto date = timeSample.first;
				const auto sample = timeSample.second;

				// TODO: collect all needed samples around date and feed them into FANN
				auto stationSample = station.samples.find(date);
				if (stationSample != station.samples.end())
				{
					//sample->values
				}
			}

			return NULL;
		}

		virtual ~GeoClimateCorrelator() {}
	};

	IGeoClimateCorrelator* IGeoClimateCorrelator::Create()
	{
		return new GeoClimateCorrelator();
	}
}
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2016, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * 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.
 *
 */

/* Benchmark gRPC end2end in various configurations */

#include <sstream>

#include <grpc++/channel.h>
#include <grpc++/create_channel.h>
#include <grpc++/impl/grpc_library.h>
#include <grpc++/security/credentials.h>
#include <grpc++/security/server_credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc/support/log.h>

extern "C" {
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/endpoint_pair.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/tcp_posix.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/server.h"
#include "test/core/util/passthru_endpoint.h"
#include "test/core/util/port.h"
}
#include "src/cpp/client/create_channel_internal.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "third_party/google_benchmark/include/benchmark/benchmark.h"

namespace grpc {
namespace testing {

static class InitializeStuff {
 public:
  InitializeStuff() {
    init_lib_.init();
    rq_ = grpc_resource_quota_create("bm");
  }

  grpc_resource_quota* rq() { return rq_; }

 private:
  internal::GrpcLibrary init_lib_;
  grpc_resource_quota* rq_;
} initialize_stuff;

/*******************************************************************************
 * FIXTURES
 */

class FullstackFixture {
 public:
  FullstackFixture(Service* service, const grpc::string& address) {
    ServerBuilder b;
    b.AddListeningPort(address, InsecureServerCredentials());
    cq_ = b.AddCompletionQueue(true);
    b.RegisterService(service);
    server_ = b.BuildAndStart();
    channel_ = CreateChannel(address, InsecureChannelCredentials());
  }

  virtual ~FullstackFixture() {
    server_->Shutdown();
    cq_->Shutdown();
    void* tag;
    bool ok;
    while (cq_->Next(&tag, &ok)) {
    }
  }

  ServerCompletionQueue* cq() { return cq_.get(); }
  std::shared_ptr<Channel> channel() { return channel_; }

 private:
  std::unique_ptr<Server> server_;
  std::unique_ptr<ServerCompletionQueue> cq_;
  std::shared_ptr<Channel> channel_;
};

class TCP : public FullstackFixture {
 public:
  TCP(Service* service) : FullstackFixture(service, MakeAddress()) {}

 private:
  static grpc::string MakeAddress() {
    int port = grpc_pick_unused_port_or_die();
    std::stringstream addr;
    addr << "localhost:" << port;
    return addr.str();
  }
};

class UDS : public FullstackFixture {
 public:
  UDS(Service* service) : FullstackFixture(service, "unix:bm_fullstack") {}
};

class EndpointPairFixture {
 public:
  EndpointPairFixture(Service* service, grpc_endpoint_pair endpoints) {
    ServerBuilder b;
    cq_ = b.AddCompletionQueue(true);
    b.RegisterService(service);
    server_ = b.BuildAndStart();

    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

    /* add server endpoint to server_ */
    {
      const grpc_channel_args* server_args =
          grpc_server_get_channel_args(server_->c_server());
      grpc_transport* transport = grpc_create_chttp2_transport(
          &exec_ctx, server_args, endpoints.server, 0 /* is_client */);

      grpc_pollset** pollsets;
      size_t num_pollsets = 0;
      grpc_server_get_pollsets(server_->c_server(), &pollsets, &num_pollsets);

      for (size_t i = 0; i < num_pollsets; i++) {
        grpc_endpoint_add_to_pollset(&exec_ctx, endpoints.server, pollsets[i]);
      }

      grpc_server_setup_transport(&exec_ctx, server_->c_server(), transport,
                                  NULL, server_args);
      grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL);
    }

    /* create channel */
    {
      ChannelArguments args;
      args.SetString(GRPC_ARG_DEFAULT_AUTHORITY, "test.authority");

      grpc_channel_args c_args = args.c_args();
      grpc_transport* transport =
          grpc_create_chttp2_transport(&exec_ctx, &c_args, endpoints.client, 1);
      GPR_ASSERT(transport);
      grpc_channel* channel = grpc_channel_create(
          &exec_ctx, "target", &c_args, GRPC_CLIENT_DIRECT_CHANNEL, transport);
      grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL);

      channel_ = CreateChannelInternal("", channel);
    }

    grpc_exec_ctx_finish(&exec_ctx);
  }

  virtual ~EndpointPairFixture() {
    server_->Shutdown();
    cq_->Shutdown();
    void* tag;
    bool ok;
    while (cq_->Next(&tag, &ok)) {
    }
  }

  ServerCompletionQueue* cq() { return cq_.get(); }
  std::shared_ptr<Channel> channel() { return channel_; }

 private:
  std::unique_ptr<Server> server_;
  std::unique_ptr<ServerCompletionQueue> cq_;
  std::shared_ptr<Channel> channel_;
};

class SockPair : public EndpointPairFixture {
 public:
  SockPair(Service* service)
      : EndpointPairFixture(service, grpc_iomgr_create_endpoint_pair(
                                         "test", initialize_stuff.rq(), 8192)) {
  }
};

class InProcessCHTTP2 : public EndpointPairFixture {
 public:
  InProcessCHTTP2(Service* service)
      : EndpointPairFixture(service, MakeEndpoints()) {}

 private:
  grpc_endpoint_pair MakeEndpoints() {
    grpc_endpoint_pair p;
    grpc_passthru_endpoint_create(&p.client, &p.server, initialize_stuff.rq());
    return p;
  }
};

/*******************************************************************************
 * BENCHMARKING KERNELS
 */

static void* tag(intptr_t x) { return reinterpret_cast<void*>(x); }

template <class Fixture>
static void BM_UnaryPingPong(benchmark::State& state) {
  EchoTestService::AsyncService service;
  Fixture fixture(&service);
  EchoRequest send_request;
  EchoResponse send_response;
  EchoResponse recv_response;
  Status recv_status;
  struct ServerEnv {
    ServerContext ctx;
    EchoRequest recv_request;
    grpc::ServerAsyncResponseWriter<EchoResponse> response_writer;
    ServerEnv() : response_writer(&ctx) {}
  };
  uint8_t server_env_buffer[2 * sizeof(ServerEnv)];
  ServerEnv* server_env[2] = {
      reinterpret_cast<ServerEnv*>(server_env_buffer),
      reinterpret_cast<ServerEnv*>(server_env_buffer + sizeof(ServerEnv))};
  new (server_env[0]) ServerEnv;
  new (server_env[1]) ServerEnv;
  service.RequestEcho(&server_env[0]->ctx, &server_env[0]->recv_request,
                      &server_env[0]->response_writer, fixture.cq(),
                      fixture.cq(), tag(0));
  service.RequestEcho(&server_env[1]->ctx, &server_env[1]->recv_request,
                      &server_env[1]->response_writer, fixture.cq(),
                      fixture.cq(), tag(1));
  std::unique_ptr<EchoTestService::Stub> stub(
      EchoTestService::NewStub(fixture.channel()));
  while (state.KeepRunning()) {
    ClientContext cli_ctx;
    std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
        stub->AsyncEcho(&cli_ctx, send_request, fixture.cq()));
    void* t;
    bool ok;
    GPR_ASSERT(fixture.cq()->Next(&t, &ok));
    GPR_ASSERT(ok);
    GPR_ASSERT(t == tag(0) || t == tag(1));
    intptr_t slot = reinterpret_cast<intptr_t>(t);
    ServerEnv* senv = server_env[slot];
    senv->response_writer.Finish(send_response, Status::OK, tag(3));
    response_reader->Finish(&recv_response, &recv_status, tag(4));
    for (int i = (1 << 3) | (1 << 4); i != 0;) {
      GPR_ASSERT(fixture.cq()->Next(&t, &ok));
      GPR_ASSERT(ok);
      int tagnum = (int)reinterpret_cast<intptr_t>(t);
      GPR_ASSERT(i & (1 << tagnum));
      i -= 1 << tagnum;
    }
    GPR_ASSERT(recv_status.ok());

    senv->~ServerEnv();
    senv = new (senv) ServerEnv();
    service.RequestEcho(&senv->ctx, &senv->recv_request, &senv->response_writer,
                        fixture.cq(), fixture.cq(), tag(slot));
  }
  server_env[0]->~ServerEnv();
  server_env[1]->~ServerEnv();
}

/*******************************************************************************
 * CONFIGURATIONS
 */

BENCHMARK_TEMPLATE(BM_UnaryPingPong, TCP);
BENCHMARK_TEMPLATE(BM_UnaryPingPong, UDS);
BENCHMARK_TEMPLATE(BM_UnaryPingPong, SockPair);
BENCHMARK_TEMPLATE(BM_UnaryPingPong, InProcessCHTTP2);

}  // namespace testing
}  // namespace grpc

BENCHMARK_MAIN();
<commit_msg>Fix memory corruption<commit_after>/*
 *
 * Copyright 2016, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * 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.
 *
 */

/* Benchmark gRPC end2end in various configurations */

#include <sstream>

#include <grpc++/channel.h>
#include <grpc++/create_channel.h>
#include <grpc++/impl/grpc_library.h>
#include <grpc++/security/credentials.h>
#include <grpc++/security/server_credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc/support/log.h>

extern "C" {
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/endpoint_pair.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/tcp_posix.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/server.h"
#include "test/core/util/passthru_endpoint.h"
#include "test/core/util/port.h"
}
#include "src/cpp/client/create_channel_internal.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "third_party/google_benchmark/include/benchmark/benchmark.h"

namespace grpc {
namespace testing {

static class InitializeStuff {
 public:
  InitializeStuff() {
    init_lib_.init();
    rq_ = grpc_resource_quota_create("bm");
  }

  grpc_resource_quota* rq() { return rq_; }

 private:
  internal::GrpcLibrary init_lib_;
  grpc_resource_quota* rq_;
} initialize_stuff;

/*******************************************************************************
 * FIXTURES
 */

class FullstackFixture {
 public:
  FullstackFixture(Service* service, const grpc::string& address) {
    ServerBuilder b;
    b.AddListeningPort(address, InsecureServerCredentials());
    cq_ = b.AddCompletionQueue(true);
    b.RegisterService(service);
    server_ = b.BuildAndStart();
    channel_ = CreateChannel(address, InsecureChannelCredentials());
  }

  virtual ~FullstackFixture() {
    server_->Shutdown();
    cq_->Shutdown();
    void* tag;
    bool ok;
    while (cq_->Next(&tag, &ok)) {
    }
  }

  ServerCompletionQueue* cq() { return cq_.get(); }
  std::shared_ptr<Channel> channel() { return channel_; }

 private:
  std::unique_ptr<Server> server_;
  std::unique_ptr<ServerCompletionQueue> cq_;
  std::shared_ptr<Channel> channel_;
};

class TCP : public FullstackFixture {
 public:
  TCP(Service* service) : FullstackFixture(service, MakeAddress()) {}

 private:
  static grpc::string MakeAddress() {
    int port = grpc_pick_unused_port_or_die();
    std::stringstream addr;
    addr << "localhost:" << port;
    return addr.str();
  }
};

class UDS : public FullstackFixture {
 public:
  UDS(Service* service) : FullstackFixture(service, "unix:bm_fullstack") {}
};

class EndpointPairFixture {
 public:
  EndpointPairFixture(Service* service, grpc_endpoint_pair endpoints) {
    ServerBuilder b;
    cq_ = b.AddCompletionQueue(true);
    b.RegisterService(service);
    server_ = b.BuildAndStart();

    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

    /* add server endpoint to server_ */
    {
      const grpc_channel_args* server_args =
          grpc_server_get_channel_args(server_->c_server());
      grpc_transport* transport = grpc_create_chttp2_transport(
          &exec_ctx, server_args, endpoints.server, 0 /* is_client */);

      grpc_pollset** pollsets;
      size_t num_pollsets = 0;
      grpc_server_get_pollsets(server_->c_server(), &pollsets, &num_pollsets);

      for (size_t i = 0; i < num_pollsets; i++) {
        grpc_endpoint_add_to_pollset(&exec_ctx, endpoints.server, pollsets[i]);
      }

      grpc_server_setup_transport(&exec_ctx, server_->c_server(), transport,
                                  NULL, server_args);
      grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL);
    }

    /* create channel */
    {
      ChannelArguments args;
      args.SetString(GRPC_ARG_DEFAULT_AUTHORITY, "test.authority");

      grpc_channel_args c_args = args.c_args();
      grpc_transport* transport =
          grpc_create_chttp2_transport(&exec_ctx, &c_args, endpoints.client, 1);
      GPR_ASSERT(transport);
      grpc_channel* channel = grpc_channel_create(
          &exec_ctx, "target", &c_args, GRPC_CLIENT_DIRECT_CHANNEL, transport);
      grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL);

      channel_ = CreateChannelInternal("", channel);
    }

    grpc_exec_ctx_finish(&exec_ctx);
  }

  virtual ~EndpointPairFixture() {
    server_->Shutdown();
    cq_->Shutdown();
    void* tag;
    bool ok;
    while (cq_->Next(&tag, &ok)) {
    }
  }

  ServerCompletionQueue* cq() { return cq_.get(); }
  std::shared_ptr<Channel> channel() { return channel_; }

 private:
  std::unique_ptr<Server> server_;
  std::unique_ptr<ServerCompletionQueue> cq_;
  std::shared_ptr<Channel> channel_;
};

class SockPair : public EndpointPairFixture {
 public:
  SockPair(Service* service)
      : EndpointPairFixture(service, grpc_iomgr_create_endpoint_pair(
                                         "test", initialize_stuff.rq(), 8192)) {
  }
};

class InProcessCHTTP2 : public EndpointPairFixture {
 public:
  InProcessCHTTP2(Service* service)
      : EndpointPairFixture(service, MakeEndpoints()) {}

 private:
  grpc_endpoint_pair MakeEndpoints() {
    grpc_endpoint_pair p;
    grpc_passthru_endpoint_create(&p.client, &p.server, initialize_stuff.rq());
    return p;
  }
};

/*******************************************************************************
 * BENCHMARKING KERNELS
 */

static void* tag(intptr_t x) { return reinterpret_cast<void*>(x); }

template <class Fixture>
static void BM_UnaryPingPong(benchmark::State& state) {
  EchoTestService::AsyncService service;
  std::unique_ptr<Fixture> fixture(new Fixture(&service));
  EchoRequest send_request;
  EchoResponse send_response;
  EchoResponse recv_response;
  Status recv_status;
  struct ServerEnv {
    ServerContext ctx;
    EchoRequest recv_request;
    grpc::ServerAsyncResponseWriter<EchoResponse> response_writer;
    ServerEnv() : response_writer(&ctx) {}
  };
  uint8_t server_env_buffer[2 * sizeof(ServerEnv)];
  ServerEnv* server_env[2] = {
      reinterpret_cast<ServerEnv*>(server_env_buffer),
      reinterpret_cast<ServerEnv*>(server_env_buffer + sizeof(ServerEnv))};
  new (server_env[0]) ServerEnv;
  new (server_env[1]) ServerEnv;
  service.RequestEcho(&server_env[0]->ctx, &server_env[0]->recv_request,
                      &server_env[0]->response_writer, fixture->cq(),
                      fixture->cq(), tag(0));
  service.RequestEcho(&server_env[1]->ctx, &server_env[1]->recv_request,
                      &server_env[1]->response_writer, fixture->cq(),
                      fixture->cq(), tag(1));
  std::unique_ptr<EchoTestService::Stub> stub(
      EchoTestService::NewStub(fixture->channel()));
  while (state.KeepRunning()) {
    ClientContext cli_ctx;
    std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
        stub->AsyncEcho(&cli_ctx, send_request, fixture->cq()));
    void* t;
    bool ok;
    GPR_ASSERT(fixture->cq()->Next(&t, &ok));
    GPR_ASSERT(ok);
    GPR_ASSERT(t == tag(0) || t == tag(1));
    intptr_t slot = reinterpret_cast<intptr_t>(t);
    ServerEnv* senv = server_env[slot];
    senv->response_writer.Finish(send_response, Status::OK, tag(3));
    response_reader->Finish(&recv_response, &recv_status, tag(4));
    for (int i = (1 << 3) | (1 << 4); i != 0;) {
      GPR_ASSERT(fixture->cq()->Next(&t, &ok));
      GPR_ASSERT(ok);
      int tagnum = (int)reinterpret_cast<intptr_t>(t);
      GPR_ASSERT(i & (1 << tagnum));
      i -= 1 << tagnum;
    }
    GPR_ASSERT(recv_status.ok());

    senv->~ServerEnv();
    senv = new (senv) ServerEnv();
    service.RequestEcho(&senv->ctx, &senv->recv_request, &senv->response_writer,
                        fixture->cq(), fixture->cq(), tag(slot));
  }
  fixture.reset();
  server_env[0]->~ServerEnv();
  server_env[1]->~ServerEnv();
}

/*******************************************************************************
 * CONFIGURATIONS
 */

BENCHMARK_TEMPLATE(BM_UnaryPingPong, TCP);
BENCHMARK_TEMPLATE(BM_UnaryPingPong, UDS);
BENCHMARK_TEMPLATE(BM_UnaryPingPong, SockPair);
BENCHMARK_TEMPLATE(BM_UnaryPingPong, InProcessCHTTP2);

}  // namespace testing
}  // namespace grpc

BENCHMARK_MAIN();
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#ifndef FLUSSPFERD_NATIVE_OBJECT_BASE_HPP
#define FLUSSPFERD_NATIVE_OBJECT_BASE_HPP

#include "object.hpp"
#include "convert.hpp"
#include "function_adapter.hpp"
#include <boost/scoped_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/is_member_function_pointer.hpp>
#include <boost/any.hpp>
#include <memory>
#include <functional>

namespace flusspferd {

#ifndef IN_DOXYGEN
struct call_context;
class tracer;

namespace detail {
  object create_native_object(object const &proto);
  object create_native_enumerable_object(object const &proto);
}
#endif

/**
 * Native object base.
 *
 * @ingroup classes
 */
class native_object_base : public object, private boost::noncopyable {
public:
  /// Destructor.
  virtual ~native_object_base() = 0;

  /**
   * Explicitly return the associated object.
   *
   * @return The associated object.
   */
  object get_object() {
    return *static_cast<object*>(this);
  }

  /**
   * Get the native object associated with a Javascript object.
   *
   * @return A reference to the object.
   */
  static native_object_base &get_native(object const &o);

public:
  /**
   * Associate with an object if there is no association yet.
   *
   * Do not use directly.
   *
   * @param o The object to associate with.
   */
  void load_into(object const &o);

protected:
  /**
   * Constructor.
   *
   * Immediately associates with object @p o.
   *
   * Do not use with arbitrary objects.
   *
   * @param o The object to associate with.
   */
  native_object_base(object const &o);

protected:
  /**
   * Virtual method invoked whenever the object is called as if it were a
   * function.
   *
   * Default implementation: throw an exception.
   *
   * @param x The call context.
   */
  virtual void self_call(call_context &x);

  /**
   * Virtual method invoked whenever the object has to be traced.
   *
   * Default implementation: stub.
   *
   * For each value that is an otherwise unreachable member of the object and
   * that should be protected from garbage collection, call @c trc(x).
   *
   * @param trc The tracer to be used.
   *
   * @see @ref gc
   */
  virtual void trace(tracer &trc);

protected:
  /**
   * Possible property access methods. Can be combined by bitwise or.
   */
  enum property_access {
    /**
     * The property access uses the @c . or @c [] operator:
     * @c obj.id or @c obj[id], not @c id.
     */
    property_qualified = 1,

    /**
     * The property appears on the left-hand side of an assignment.
     */
    property_assigning = 2,

    /**
     * The property is being used in code like "if (o.p) ...",
     * or a similar idiom where the apparent purpose of the property access is
     * to detect whether the property exists.
     */
    property_detecting = 4,

    /**
     * The property is being declared in a var, const, or function declaration.
     */
    property_declaring = 8,

    /**
     * class name used when constructing. (???)
     */
    property_classname = 16
  };

  /**
   * Virtual method invoked when a property is not found on an object.
   *
   * Default implementation: stub that returns @c false.
   *
   * It can be used to implement lazy properties.
   *
   * If possible, @p id will be an integer, or a string otherwise.
   *
   * @param id The property name / index.
   * @param access Information about the kind of property access. A combination
   *           of #property_access values.
   */
  virtual bool property_resolve(value const &id, unsigned access);

  /**
   * Virtual method invoked to start enumerating properties.
   *
   * Will be called only if class_info::custom_enumerate is activated.
   *
   * Default implementation: return boost::any().
   *
   * @param[out] num_properties The number of properties, if that can be
   *                computed in advance. Otherwise should be set to zero.
   *                Pre-initialized to zero.
   * @return An opaque iterator for use by #enumerate_next.
   */
  virtual boost::any enumerate_start(int &num_properties);

  /**
   * Virtual method invoked to advance the enumeration and pull out the next
   * property name / index.
   *
   * Default implementation: return @c value().
   *
   * Should return @c value() (@c undefined) to stop the enumeration.
   *
   * @param[in,out] iter The opaque iterator.
   * @return The next property name / index.
   */
  virtual value enumerate_next(boost::any &iter);

  /**
   * Possible modes for native_object_base::property_op.
   */
  enum property_mode {
    /**
     * Used just before a new property is added to an object.
     */
    property_add = 0,

    /**
     * Used during most property deletions, even when the object has no property
     * with the given name / index.
     *
     * Will not be used for permanent properties.
     */
    property_delete = -1,

    /**
     * Used as the default getter for new properties or for non-existing
     * properties.
     */
    property_get = 1,

    /**
     * Used as the default setter for new properties.
     */
    property_set = 2
  };

  /**
   * Virtual method invoked for property addition, deletion, read access and
   * write access.
   *
   * Default implementation: stub.
   *
   * @param mode The reason for invocation.
   * @param id The property name / index.
   * @param[in,out] data The old/new value of the property.
   *
   * @see property_mode
   */
  virtual void property_op(property_mode mode, value const &id, value &data);

private:
#ifndef IN_DOXYGEN
  static object do_create_object(object const &proto);
  static object do_create_enumerable_object(object const &proto);

  friend object detail::create_native_object(object const &proto);
  friend object detail::create_native_enumerable_object(object const &proto);

private:
  class impl;
  boost::scoped_ptr<impl> p;

  friend class impl;
#endif
};

template<typename T>
T &cast_to_derived(native_object_base &o) {
  T *ptr = dynamic_cast<T*>(&o);
  if (!ptr)
    throw exception("Could not convert native object to derived type");
  return *ptr;
}

template<typename T>
T &get_native(object const &o) {
  return cast_to_derived<T>(native_object_base::get_native(o));
}

template<typename T>
bool is_derived(native_object_base &o) {
  return dynamic_cast<T*>(&o);
}

/**
 * Checks if @p o is a @p T.
 *
 * @param o object to check
 * @see get_native
 * @ingroup classes
 */
template<typename T>
bool is_native(object const &o) {
  return is_derived<T>(native_object_base::get_native(o));
}

template<typename T>
struct detail::convert_ptr<T, native_object_base> {
  struct to_value {
    value perform(T *ptr) {
      if (!ptr)
        return object();
      return *static_cast<object const *>(ptr);
    }
  };

  struct from_value {
    T *perform(value const &v) {
      if (!v.is_object())
        throw exception("Value is no object");
      return &native_object_base::get_native(v.get_object());
    }
  };
};

namespace detail {

template<typename T, typename O>
struct convert_ptr<
  T, O,
  typename boost::enable_if<
    typename boost::is_base_of<native_object_base, O>::type
  >::type
>
{
  typedef typename convert_ptr<T, native_object_base>::to_value to_value;

  struct from_value {
    typename convert_ptr<native_object_base>::from_value base;

    T *perform(value const &v) {
      return &dynamic_cast<T&>(*base.perform(v));
    }
  };
};

}

}

#endif
<commit_msg>doc: add example for native_object_base::trace<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#ifndef FLUSSPFERD_NATIVE_OBJECT_BASE_HPP
#define FLUSSPFERD_NATIVE_OBJECT_BASE_HPP

#include "object.hpp"
#include "convert.hpp"
#include "function_adapter.hpp"
#include <boost/scoped_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/is_member_function_pointer.hpp>
#include <boost/any.hpp>
#include <memory>
#include <functional>

namespace flusspferd {

#ifndef IN_DOXYGEN
struct call_context;
class tracer;

namespace detail {
  object create_native_object(object const &proto);
  object create_native_enumerable_object(object const &proto);
}
#endif

/**
 * Native object base.
 *
 * @ingroup classes
 */
class native_object_base : public object, private boost::noncopyable {
public:
  /// Destructor.
  virtual ~native_object_base() = 0;

  /**
   * Explicitly return the associated object.
   *
   * @return The associated object.
   */
  object get_object() {
    return *static_cast<object*>(this);
  }

  /**
   * Get the native object associated with a Javascript object.
   *
   * @return A reference to the object.
   */
  static native_object_base &get_native(object const &o);

public:
  /**
   * Associate with an object if there is no association yet.
   *
   * Do not use directly.
   *
   * @param o The object to associate with.
   */
  void load_into(object const &o);

protected:
  /**
   * Constructor.
   *
   * Immediately associates with object @p o.
   *
   * Do not use with arbitrary objects.
   *
   * @param o The object to associate with.
   */
  native_object_base(object const &o);

protected:
  /**
   * Virtual method invoked whenever the object is called as if it were a
   * function.
   *
   * Default implementation: throw an exception.
   *
   * @param x The call context.
   */
  virtual void self_call(call_context &x);

  /**
   * Virtual method invoked whenever the object has to be traced.
   *
   * Default implementation: stub.
   *
   * For each value that is an otherwise unreachable member of the object and
   * that should be protected from garbage collection, call @c trc("x", x).
   * The string "x" does not need to be unique, it's used for debugging
   * purposes only.
   *
   * @code
flusspferd::value v;

...

void trace(flusspferd::tracer &trc) {
    trc("v", v);
}
   @endcode
   *
   * @param trc The tracer to be used.
   *
   * @see @ref gc
   */
  virtual void trace(tracer &trc);

protected:
  /**
   * Possible property access methods. Can be combined by bitwise or.
   */
  enum property_access {
    /**
     * The property access uses the @c . or @c [] operator:
     * @c obj.id or @c obj[id], not @c id.
     */
    property_qualified = 1,

    /**
     * The property appears on the left-hand side of an assignment.
     */
    property_assigning = 2,

    /**
     * The property is being used in code like "if (o.p) ...",
     * or a similar idiom where the apparent purpose of the property access is
     * to detect whether the property exists.
     */
    property_detecting = 4,

    /**
     * The property is being declared in a var, const, or function declaration.
     */
    property_declaring = 8,

    /**
     * class name used when constructing. (???)
     */
    property_classname = 16
  };

  /**
   * Virtual method invoked when a property is not found on an object.
   *
   * Default implementation: stub that returns @c false.
   *
   * It can be used to implement lazy properties.
   *
   * If possible, @p id will be an integer, or a string otherwise.
   *
   * @param id The property name / index.
   * @param access Information about the kind of property access. A combination
   *           of #property_access values.
   */
  virtual bool property_resolve(value const &id, unsigned access);

  /**
   * Virtual method invoked to start enumerating properties.
   *
   * Will be called only if class_info::custom_enumerate is activated.
   *
   * Default implementation: return boost::any().
   *
   * @param[out] num_properties The number of properties, if that can be
   *                computed in advance. Otherwise should be set to zero.
   *                Pre-initialized to zero.
   * @return An opaque iterator for use by #enumerate_next.
   */
  virtual boost::any enumerate_start(int &num_properties);

  /**
   * Virtual method invoked to advance the enumeration and pull out the next
   * property name / index.
   *
   * Default implementation: return @c value().
   *
   * Should return @c value() (@c undefined) to stop the enumeration.
   *
   * @param[in,out] iter The opaque iterator.
   * @return The next property name / index.
   */
  virtual value enumerate_next(boost::any &iter);

  /**
   * Possible modes for native_object_base::property_op.
   */
  enum property_mode {
    /**
     * Used just before a new property is added to an object.
     */
    property_add = 0,

    /**
     * Used during most property deletions, even when the object has no property
     * with the given name / index.
     *
     * Will not be used for permanent properties.
     */
    property_delete = -1,

    /**
     * Used as the default getter for new properties or for non-existing
     * properties.
     */
    property_get = 1,

    /**
     * Used as the default setter for new properties.
     */
    property_set = 2
  };

  /**
   * Virtual method invoked for property addition, deletion, read access and
   * write access.
   *
   * Default implementation: stub.
   *
   * @param mode The reason for invocation.
   * @param id The property name / index.
   * @param[in,out] data The old/new value of the property.
   *
   * @see property_mode
   */
  virtual void property_op(property_mode mode, value const &id, value &data);

private:
#ifndef IN_DOXYGEN
  static object do_create_object(object const &proto);
  static object do_create_enumerable_object(object const &proto);

  friend object detail::create_native_object(object const &proto);
  friend object detail::create_native_enumerable_object(object const &proto);

private:
  class impl;
  boost::scoped_ptr<impl> p;

  friend class impl;
#endif
};

template<typename T>
T &cast_to_derived(native_object_base &o) {
  T *ptr = dynamic_cast<T*>(&o);
  if (!ptr)
    throw exception("Could not convert native object to derived type");
  return *ptr;
}

template<typename T>
T &get_native(object const &o) {
  return cast_to_derived<T>(native_object_base::get_native(o));
}

template<typename T>
bool is_derived(native_object_base &o) {
  return dynamic_cast<T*>(&o);
}

/**
 * Checks if @p o is a @p T.
 *
 * @param o object to check
 * @see get_native
 * @ingroup classes
 */
template<typename T>
bool is_native(object const &o) {
  return is_derived<T>(native_object_base::get_native(o));
}

template<typename T>
struct detail::convert_ptr<T, native_object_base> {
  struct to_value {
    value perform(T *ptr) {
      if (!ptr)
        return object();
      return *static_cast<object const *>(ptr);
    }
  };

  struct from_value {
    T *perform(value const &v) {
      if (!v.is_object())
        throw exception("Value is no object");
      return &native_object_base::get_native(v.get_object());
    }
  };
};

namespace detail {

template<typename T, typename O>
struct convert_ptr<
  T, O,
  typename boost::enable_if<
    typename boost::is_base_of<native_object_base, O>::type
  >::type
>
{
  typedef typename convert_ptr<T, native_object_base>::to_value to_value;

  struct from_value {
    typename convert_ptr<native_object_base>::from_value base;

    T *perform(value const &v) {
      return &dynamic_cast<T&>(*base.perform(v));
    }
  };
};

}

}

#endif
<|endoftext|>