text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef KAGOME_CHAIN_SPEC_IMPL_HPP
#define KAGOME_CHAIN_SPEC_IMPL_HPP

#include "application/chain_spec.hpp"

#include <boost/property_tree/ptree.hpp>

#include "log/logger.hpp"
#include "primitives/code_substitutes.hpp"

namespace kagome::application {

  class ChainSpecImpl : public ChainSpec {
   public:
    enum class Error {
      MISSING_ENTRY = 1,
      MISSING_PEER_ID,
      PARSER_ERROR,
      NOT_IMPLEMENTED
    };

    static outcome::result<std::shared_ptr<ChainSpecImpl>> loadFrom(
        const std::string &config_path);

    ~ChainSpecImpl() override = default;

    const std::string &name() const override {
      return name_;
    }

    const std::string &id() const override {
      return id_;
    }

    const std::string &chainType() const override {
      return chain_type_;
    }

    const std::vector<libp2p::multi::Multiaddress> &bootNodes() const override {
      return boot_nodes_;
    }

    const std::vector<std::pair<std::string, size_t>> &telemetryEndpoints()
        const override {
      return telemetry_endpoints_;
    }

    const std::string &protocolId() const override {
      return protocol_id_;
    }

    const std::map<std::string, std::string> &properties() const override {
      return properties_;
    }

    std::optional<std::reference_wrapper<const std::string>> getProperty(
        const std::string &property) const override {
      auto it = properties_.find(property);
      if (it != properties_.end()) {
        return {{it->second}};
      }
      return std::nullopt;
    }

    const std::set<primitives::BlockHash> &forkBlocks() const override {
      return fork_blocks_;
    }

    const std::set<primitives::BlockHash> &badBlocks() const override {
      return bad_blocks_;
    }

    std::optional<std::string> consensusEngine() const override {
      return consensus_engine_;
    }

    std::shared_ptr<const primitives::CodeSubstituteHashes> codeSubstitutes()
        const override {
      return known_code_substitutes_;
    }

    GenesisRawData getGenesis() const override {
      return genesis_;
    }

    outcome::result<common::Buffer> fetchCodeSubstituteByHash(
        const common::Hash256 &hash) const override;

   private:
    outcome::result<void> loadFromJson(const std::string &file_path);
    outcome::result<void> loadFields(const boost::property_tree::ptree &tree);
    outcome::result<void> loadGenesis(const boost::property_tree::ptree &tree);
    outcome::result<void> loadBootNodes(
        const boost::property_tree::ptree &tree);

    template <typename T>
    outcome::result<std::decay_t<T>> ensure(std::string_view entry_name,
                                            boost::optional<T> opt_entry) {
      if (not opt_entry) {
        log_->error("Required '{}' entry not found in the chain spec",
                    entry_name);
        return Error::MISSING_ENTRY;
      }
      return opt_entry.value();
    }

    ChainSpecImpl() = default;

    std::string name_;
    std::string id_;
    std::string chain_type_;
    std::string config_path_;
    std::vector<libp2p::multi::Multiaddress> boot_nodes_;
    std::vector<std::pair<std::string, size_t>> telemetry_endpoints_;
    std::string protocol_id_{"sup"};
    std::map<std::string, std::string> properties_;
    std::set<primitives::BlockHash> fork_blocks_;
    std::set<primitives::BlockHash> bad_blocks_;
    std::optional<std::string> consensus_engine_;
    std::shared_ptr<primitives::CodeSubstituteHashes> known_code_substitutes_;
    GenesisRawData genesis_;
    log::Logger log_ = log::createLogger("chain_spec", "kagome");
  };

}  // namespace kagome::application

OUTCOME_HPP_DECLARE_ERROR(kagome::application, ChainSpecImpl::Error)

#endif  // KAGOME_CHAIN_SPEC_IMPL_HPP


text:
// Copyright (C) 2014-2018 Internet Systems Consortium, Inc. ("ISC")
//
// 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/.

/// @file d2_upd_unittest.cc Unit tests for D2ClientMgr UDP communications.
/// Note these tests are not intended to verify the actual send and receive
/// across UDP sockets.  This level of testing is done in libdhcp-ddns.

#include <config.h>
#include <asiolink/asio_wrapper.h>
#include <asiolink/io_service.h>
#include <dhcp/iface_mgr.h>
#include <dhcpsrv/d2_client_mgr.h>
#include <exceptions/exceptions.h>

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <gtest/gtest.h>

#include <sys/select.h>

using namespace std;
using namespace isc::dhcp;
using namespace isc;

namespace {

/// @brief Test fixture for exercising D2ClientMgr send management
/// services.  It inherits from D2ClientMgr to allow overriding various
/// methods and accessing otherwise restricted member.  In particular it
/// overrides the NameChangeSender completion completion callback, allowing
/// the injection of send errors.
class D2ClientMgrTest : public D2ClientMgr, public ::testing::Test {
public:
    /// @brief If true simulates a send which completed with a failed status.
    bool simulate_send_failure_;
    /// @brief If true causes an exception throw in the client error handler.
    bool error_handler_throw_;
    /// @brief Tracks the number times the completion handler is called.
    int callback_count_;
    /// @brief Tracks the number of times the client error handler was called.
    int error_handler_count_;

    /// @brief Constructor
    D2ClientMgrTest() : simulate_send_failure_(false),
                       error_handler_throw_(false),
                       callback_count_(0), error_handler_count_(0) {
    }

    /// @brief virtual Destructor
    virtual ~D2ClientMgrTest(){
    }

    /// @brief Updates the D2ClientMgr's configuration to DDNS enabled.
    ///
    /// @param server_address IP address of kea-dhcp-ddns.
    /// @param server_port IP port number of kea-dhcp-ddns.
    /// @param protocol NCR protocol to use. (Currently only UDP is
    /// supported).
    void enableDdns(const std::string& server_address,
                    const size_t server_port,
                    const dhcp_ddns::NameChangeProtocol protocol) {
        // Update the configuration with one that is enabled.
        D2ClientConfigPtr new_cfg;

        isc::asiolink::IOAddress server_ip(server_address);
        isc::asiolink::IOAddress sender_ip(server_ip.isV4() ?
                                           D2ClientConfig::DFT_V4_SENDER_IP :
                                           D2ClientConfig::DFT_V6_SENDER_IP);

        ASSERT_NO_THROW(new_cfg.reset(new D2ClientConfig(true,
                                  server_ip, server_port,
                                  sender_ip, D2ClientConfig::DFT_SENDER_PORT,
                                  D2ClientConfig::DFT_MAX_QUEUE_SIZE,
                                  protocol, dhcp_ddns::FMT_JSON,
                                  true, true, true, D2ClientConfig::RCM_WHEN_PRESENT,
                                  "myhost", ".example.com.", "", "")));

        ASSERT_NO_THROW(setD2ClientConfig(new_cfg));
        ASSERT_TRUE(ddnsEnabled());
    }

    /// @brief Checks sender's select-fd against an expected state of readiness.
    ///
    /// Uses select() to determine if the sender's select_fd is marked as
    /// ready to read, and compares this against the expected state.  The
    /// select function is called with a timeout of 0.0 (non blocking).
    ///
    /// @param expect_ready Expected state of readiness (True if expecting
    /// a ready to ready result,  false if expecting otherwise).
    void selectCheck(bool expect_ready) {
        fd_set read_fds;
        int maxfd = 0;

        FD_ZERO(&read_fds);

        // cppcheck-suppress redundantAssignment
        int select_fd = -1;
        ASSERT_NO_THROW(
            // cppcheck-suppress redundantAssignment
            select_fd = getSelectFd()
        );

        FD_SET(select_fd,  &read_fds);
        maxfd = select_fd;

        struct timeval select_timeout;
        select_timeout.tv_sec = 0;
        select_timeout.tv_usec = 0;

        int result = (select(maxfd + 1, &read_fds, NULL, NULL,
                      &select_timeout));

        if (result < 0) {
            const char *errstr = strerror(errno);
            FAIL() << "select failed :" << errstr;
        }

        if (expect_ready) {
            ASSERT_TRUE(result > 0);
        } else {
            ASSERT_TRUE(result == 0);
        }
    }

    /// @brief Overrides base class completion callback.
    ///
    /// This method will be invoked each time a send completes. It allows
    /// intervention prior to calling the production implementation in the
    /// base.  If simulate_send_failure_ is true, the base call impl will
    /// be called with an error status, otherwise it will be called with
    /// the result parameter given.
    ///
    /// @param result Result code of the send operation.
    /// @param ncr NameChangeRequest which failed to send.
    virtual void operator()(const dhcp_ddns::NameChangeSender::Result result,
                            dhcp_ddns::NameChangeRequestPtr& ncr) {
        ++callback_count_;
        if (simulate_send_failure_) {
            simulate_send_failure_ = false;
            D2ClientMgr::operator()(dhcp_ddns::NameChangeSender::ERROR, ncr);
        } else {
            D2ClientMgr::operator()(result, ncr);
        }
    }

    /// @brief Serves as the "application level" client error handler.
    ///
    /// This method is passed into calls to startSender as the client error
    /// handler.  It should be invoked whenever the completion callback is
    /// passed a result other than SUCCESS.  If error_handler_throw_
    /// is true it will throw an exception.
    ///
    /// @param result unused - Result code of the send operation.
    /// @param ncr unused -NameChangeRequest which failed to send.
    void error_handler(const dhcp_ddns::NameChangeSender::Result /*result*/,
                       dhcp_ddns::NameChangeRequestPtr& /*ncr*/) {
        if (error_handler_throw_) {
            error_handler_throw_ = false;
            isc_throw(isc::InvalidOperation, "Simulated client handler throw");
        }

        ++error_handler_count_;
    }

    /// @brief Returns D2ClientErroHandler bound to this::error_handler_.
    D2ClientErrorHandler getErrorHandler() {
        return (boost::bind(&D2ClientMgrTest::error_handler, this, _1, _2));
    }

    /// @brief Constructs a NameChangeRequest message from a fixed JSON string.
    dhcp_ddns::NameChangeRequestPtr buildTestNcr() {
        // Build an NCR from json string.
        const char* ncr_str =
            "{"
            " \"change-type\" : 0 , "
            " \"forward-change\" : true , "
            " \"reverse-change\" : false , "
            " \"fqdn\" : \"myhost.example.com.\" , "
            " \"ip-address\" : \"192.168.2.1\" , "
            " \"dhcid\" : \"010203040A7F8E3D\" , "
            " \"lease-expires-on\" : \"20140121132405\" , "
            " \"lease-length\" : 1300 "
            "}";

        return (dhcp_ddns::NameChangeRequest::fromJSON(ncr_str));
    }

    /// Expose restricted members.
    using D2ClientMgr::getSelectFd;
};

/// @brief Checks that D2ClientMgr disable and enable a UDP sender.
TEST_F(D2ClientMgrTest, udpSenderEnableDisable) {
    // Verify DDNS is disabled by default.
    ASSERT_FALSE(ddnsEnabled());

    // Verify we are not in send mode.
    ASSERT_FALSE(amSending());

    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    enableDdns("127.0.0.1", 530001, dhcp_ddns::NCR_UDP);
    ASSERT_FALSE(amSending());

    ASSERT_NO_THROW(startSender(getErrorHandler()));
    ASSERT_TRUE(amSending());

    // Verify that we take sender out of send mode.
    ASSERT_NO_THROW(stopSender());
    ASSERT_FALSE(amSending());
}

/// @brief Checks D2ClientMgr queuing methods with a UDP sender.
TEST_F(D2ClientMgrTest, udpSenderQueing) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    enableDdns("127.0.0.1", 530001, dhcp_ddns::NCR_UDP);
    ASSERT_FALSE(amSending());

    // Queue should be empty.
    EXPECT_EQ(0, getQueueSize());

    // Trying to peek past the end of the queue should throw.
    EXPECT_THROW(peekAt(1), dhcp_ddns::NcrSenderError);

    // Trying to send a NCR when not in send mode should fail.
    dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
    EXPECT_THROW(sendRequest(ncr), D2ClientError);

    // Place sender in send mode.
    ASSERT_NO_THROW(startSender(getErrorHandler()));
    ASSERT_TRUE(amSending());

    // Send should succeed now.
    ASSERT_NO_THROW(sendRequest(ncr));

    // Queue should have 1 entry.
    EXPECT_EQ(1, getQueueSize());

    // Attempt to fetch the entry we just queued.
    dhcp_ddns::NameChangeRequestPtr ncr2;
    ASSERT_NO_THROW(ncr2 = peekAt(0));

    // Verify what we queued matches what we fetched.
    EXPECT_TRUE(*ncr == *ncr2);

    // Clearing the queue while in send mode should fail.
    ASSERT_THROW(clearQueue(), dhcp_ddns::NcrSenderError);

    // We should still have 1 in the queue.
    EXPECT_EQ(1, getQueueSize());

    // Get out of send mode.
    ASSERT_NO_THROW(stopSender());
    ASSERT_FALSE(amSending());

    // Clear queue should succeed now.
    ASSERT_NO_THROW(clearQueue());
    EXPECT_EQ(0, getQueueSize());
}

/// @brief Checks that D2ClientMgr can send with a UDP sender and
/// a private IOService.
TEST_F(D2ClientMgrTest, udpSend) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    enableDdns("127.0.0.1", 530001, dhcp_ddns::NCR_UDP);

    // Trying to fetch the select-fd when not sending should fail.
    ASSERT_THROW(getSelectFd(), D2ClientError);

    // Place sender in send mode.
    ASSERT_NO_THROW(startSender(getErrorHandler()));

    // select_fd should evaluate to NOT ready to read.
    selectCheck(false);

    // Build a test request and send it.
    dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
    ASSERT_NO_THROW(sendRequest(ncr));

    // select_fd should evaluate to ready to read.
    selectCheck(true);

    // Call service handler.
    runReadyIO();

    // select_fd should evaluate to not ready to read.
    selectCheck(false);
}

/// @brief Checks that D2ClientMgr can send with a UDP sender and
/// an external IOService.
TEST_F(D2ClientMgrTest, udpSendExternalIOService) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    enableDdns("127.0.0.1", 53001, dhcp_ddns::NCR_UDP);

    // Place sender in send mode using an external IO service.
    asiolink::IOService io_service;
    ASSERT_NO_THROW(startSender(getErrorHandler(), io_service));

    // select_fd should evaluate to NOT ready to read.
    selectCheck(false);

    // Build a test request and send it.
    dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
    ASSERT_NO_THROW(sendRequest(ncr));

    // select_fd should evaluate to ready to read.
    selectCheck(true);

    // Call service handler.
    runReadyIO();

    // select_fd should evaluate to not ready to read.
    selectCheck(false);

    // Explicitly stop the sender. This ensures the sender's
    // ASIO socket is closed prior to the local io_service
    // instance goes out of scope.
    ASSERT_NO_THROW(stopSender());
}

/// @brief Checks that D2ClientMgr can send with a UDP sender and
/// an external IOService.
TEST_F(D2ClientMgrTest, udpSendExternalIOService6) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    enableDdns("::1", 53001, dhcp_ddns::NCR_UDP);

    // Place sender in send mode using an external IO service.
    asiolink::IOService io_service;
    ASSERT_NO_THROW(startSender(getErrorHandler(), io_service));

    // select_fd should evaluate to NOT ready to read.
    selectCheck(false);

    // Build a test request and send it.
    dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
    ASSERT_NO_THROW(sendRequest(ncr));

    // select_fd should evaluate to ready to read.
    selectCheck(true);

    // Call service handler.
    runReadyIO();

    // select_fd should evaluate to not ready to read.
    selectCheck(false);

    // Explicitly stop the sender. This ensures the sender's
    // ASIO socket is closed prior to the local io_service
    // instance goes out of scope.
    ASSERT_NO_THROW(stopSender());
}

/// @brief Checks that D2ClientMgr invokes the client error handler
/// when send errors occur.
TEST_F(D2ClientMgrTest, udpSendErrorHandler) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    // Place sender in send mode.
    enableDdns("127.0.0.1", 530001, dhcp_ddns::NCR_UDP);
    ASSERT_NO_THROW(startSender(getErrorHandler()));

    // Simulate a failed response in the send call back. This should
    // cause the error handler to get invoked.
    simulate_send_failure_ = true;

    // Verify error count is zero.
    ASSERT_EQ(0, error_handler_count_);

    // Send a test request.
    dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
    ASSERT_NO_THROW(sendRequest(ncr));

    // Call the ready handler. This should complete the message with an error.
    ASSERT_NO_THROW(runReadyIO());

    // If we executed error handler properly, the error count should one.
    ASSERT_EQ(1, error_handler_count_);
}

/// @brief Checks that client error handler exceptions are handled gracefully.
TEST_F(D2ClientMgrTest, udpSendErrorHandlerThrow) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    // Place sender in send mode.
    enableDdns("127.0.0.1", 530001, dhcp_ddns::NCR_UDP);
    ASSERT_NO_THROW(startSender(getErrorHandler()));

    // Simulate a failed response in the send call back and
    // force a throw in the error handler.
    simulate_send_failure_ = true;
    error_handler_throw_ = true;

    // Verify error count is zero.
    ASSERT_EQ(0, error_handler_count_);

    // Send a test request.
    dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
    ASSERT_NO_THROW(sendRequest(ncr));

    // Call the ready handler. This should complete the message with an error.
    // The handler should throw but the exception should not escape.
    ASSERT_NO_THROW(runReadyIO());

    // If throw flag is false, then we were in the error handler should
    // have thrown.
    ASSERT_FALSE(error_handler_throw_);

    // If error count is still zero, then we did throw.
    ASSERT_EQ(0, error_handler_count_);
}

/// @brief Tests that D2ClientMgr registers and unregisters with IfaceMgr.
TEST_F(D2ClientMgrTest, ifaceRegister) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    enableDdns("127.0.0.1", 530001, dhcp_ddns::NCR_UDP);

    // Place sender in send mode.
    ASSERT_NO_THROW(startSender(getErrorHandler()));

    // Queue three messages.
    for (unsigned i = 0; i < 3; ++i) {
        dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
        ASSERT_NO_THROW(sendRequest(ncr));
    }

    // Make sure queue count is correct.
    EXPECT_EQ(3, getQueueSize());

    // select_fd should evaluate to ready to read.
    selectCheck(true);

    // Calling receive should complete the first message and start the second.
    IfaceMgr::instance().receive4(0, 0);

    // Verify the callback hander was invoked, no errors counted.
    EXPECT_EQ(2, getQueueSize());
    ASSERT_EQ(1, callback_count_);
    ASSERT_EQ(0, error_handler_count_);

    // Stop the sender.  This should complete the second message but leave
    // the third in the queue.
    ASSERT_NO_THROW(stopSender());
    EXPECT_EQ(1, getQueueSize());
    ASSERT_EQ(2, callback_count_);
    ASSERT_EQ(0, error_handler_count_);

    // Calling receive again should have no affect.
    IfaceMgr::instance().receive4(0, 0);
    EXPECT_EQ(1, getQueueSize());
    ASSERT_EQ(2, callback_count_);
    ASSERT_EQ(0, error_handler_count_);
}

/// @brief Checks that D2ClientMgr suspendUpdates works properly.
TEST_F(D2ClientMgrTest, udpSuspendUpdates) {
    // Enable DDNS with server at 127.0.0.1/prot 53001 via UDP.
    // Place sender in send mode.
    enableDdns("127.0.0.1", 530001, dhcp_ddns::NCR_UDP);
    ASSERT_NO_THROW(startSender(getErrorHandler()));

    // Send a test request.
    for (unsigned i = 0; i < 3; ++i) {
        dhcp_ddns::NameChangeRequestPtr ncr = buildTestNcr();
        ASSERT_NO_THROW(sendRequest(ncr));
    }
    ASSERT_EQ(3, getQueueSize());

    // Call the ready handler. This should complete the first message
    // and initiate sending the second message.
    ASSERT_NO_THROW(runReadyIO());

    // Queue count should have gone down by 1.
    ASSERT_EQ(2, getQueueSize());

    // Suspend updates. This should disable updates and stop the sender.
    ASSERT_NO_THROW(suspendUpdates());

    EXPECT_FALSE(ddnsEnabled());
    EXPECT_FALSE(amSending());

    // Stopping the sender should have completed the second message's
    // in-progress send, so queue size should be 1.
    ASSERT_EQ(1, getQueueSize());
}

/// @brief Tests that invokeErrorHandler does not fail if there is no handler.
TEST_F(D2ClientMgrTest, missingErrorHandler) {
    // Ensure we aren't in send mode.
    ASSERT_FALSE(ddnsEnabled());
    ASSERT_FALSE(amSending());

    // There is no error handler at this point, so invoking should not throw.
    dhcp_ddns::NameChangeRequestPtr ncr;
    ASSERT_NO_THROW(invokeClientErrorHandler(dhcp_ddns::NameChangeSender::ERROR,
                                             ncr));

    // Verify we didn't invoke the error handler, error count is zero.
    ASSERT_EQ(0, error_handler_count_);
}

} // end of anonymous namespace

ext: cc

max_stars_repo_name: kraj/kea

max_issues_repo_name: kraj/kea

max_forks_repo_name: kraj/kea


text:
/*
 * Copyright (C) 2016-2017, Egor Pugin
 *
 * 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 "sqlite_database.h"

#include "lock.h"

#include <boost/algorithm/string.hpp>
#include <sqlite3.h>

#include <algorithm>

#include <primitives/log.h>
DECLARE_STATIC_LOGGER(logger, "sqlite_db");

#define MAX_ERROR_SQL_LENGTH 200

/*
** This function is used to load the contents of a database file on disk
** into the "main" database of open database connection pInMemory, or
** to save the current contents of the database opened by pInMemory into
** a database file on disk. pInMemory is probably an in-memory database,
** but this function will also work fine if it is not.
**
** Parameter zFilename points to a nul-terminated string containing the
** name of the database file on disk to load from or save to. If parameter
** isSave is non-zero, then the contents of the file zFilename are
** overwritten with the contents of the database opened by pInMemory. If
** parameter isSave is zero, then the contents of the database opened by
** pInMemory are replaced by data loaded from the file zFilename.
**
** If the operation is successful, SQLITE_OK is returned. Otherwise, if
** an error occurs, an SQLite error code is returned.
*/
int loadOrSaveDb(sqlite3 *pInMemory, const char *zFilename, int isSave)
{
    int rc;                  /* Function return code */
    sqlite3 *pFile;          /* SqliteDatabase connection opened on zFilename */
    sqlite3_backup *pBackup; /* Backup object used to copy data */
    sqlite3 *pTo;            /* SqliteDatabase to copy to (pFile or pInMemory) */
    sqlite3 *pFrom;          /* SqliteDatabase to copy from (pFile or pInMemory) */

    /* Open the database file identified by zFilename. Exit early if this fails
                              ** for any reason. */
    if (!isSave)
        rc = sqlite3_open_v2(zFilename, &pFile, SQLITE_OPEN_READONLY, nullptr);
    else
        rc = sqlite3_open(zFilename, &pFile);
    if (rc == SQLITE_OK)
    {

        /* If this is a 'load' operation (isSave==0), then data is copied
        ** from the database file just opened to database pInMemory.
        ** Otherwise, if this is a 'save' operation (isSave==1), then data
        ** is copied from pInMemory to pFile.  Set the variables pFrom and
        ** pTo accordingly. */
        pFrom = (isSave ? pInMemory : pFile);
        pTo = (isSave ? pFile : pInMemory);

        /* Set up the backup procedure to copy from the "main" database of
        ** connection pFile to the main database of connection pInMemory.
        ** If something goes wrong, pBackup will be set to NULL and an error
        ** code and  message left in connection pTo.
        **
        ** If the backup object is successfully created, call backup_step()
        ** to copy data from pFile to pInMemory. Then call backup_finish()
        ** to release resources associated with the pBackup object.  If an
        ** error occurred, then  an error code and message will be left in
        ** connection pTo. If no error occurred, then the error code belonging
        ** to pTo is set to SQLITE_OK.
        */
        pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
        if (pBackup)
        {
            (void)sqlite3_backup_step(pBackup, -1);
            (void)sqlite3_backup_finish(pBackup);
        }
        rc = sqlite3_errcode(pTo);
    }

    /* Close the database connection opened on database file zFilename
    ** and return the result of this function. */
    (void)sqlite3_close(pFile);
    return rc;
}

sqlite3 *load_from_file(const path &fn, bool read_only)
{
    sqlite3 *db = nullptr;
    bool ok = true;
    int flags = 0;
    if (sqlite3_threadsafe())
        flags |= SQLITE_OPEN_NOMUTEX;// SQLITE_OPEN_FULLMUTEX;
    if (read_only)
        flags |= SQLITE_OPEN_READONLY;
    else
        flags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    sqlite3_enable_shared_cache(1);
    ok = sqlite3_open_v2(fn.string().c_str(), &db, flags, nullptr) == SQLITE_OK;
    if (!ok)
    {
        String error = "Can't open database file: " + fn.string() + " error: " + sqlite3_errmsg(db);
        sqlite3_close(db);
        throw std::runtime_error(error);
    }
    return db;
}

sqlite3 *open_in_memory()
{
    sqlite3 *db = nullptr;
    if (sqlite3_open(":memory:", &db))
    {
        String error = "Can't open in memory database, error: ";
        error += sqlite3_errmsg(db);
        sqlite3_close(db);
        throw std::runtime_error(error);
    }
    return db;
}

sqlite3 *load_from_file_to_memory(const path &fn)
{
    sqlite3 *db = open_in_memory();
    auto ret = loadOrSaveDb(db, fn.string().c_str(), 0);
    if (ret != SQLITE_OK)
    {
        String error = "Can't load database: " + fn.string() + " error: " + sqlite3_errstr(ret);
        sqlite3_close(db);
        throw std::runtime_error(error);
    }
    return db;
}

void save_from_memory_to_file(const path &fn, sqlite3 *db)
{
    auto ret = loadOrSaveDb(db, fn.string().c_str(), 1);
    if (ret != SQLITE_OK)
    {
        String error = "Can't save database: " + fn.string() + " error: " + sqlite3_errstr(ret);
        sqlite3_close(db);
        throw std::runtime_error(error);
    }
}

SqliteDatabase::SqliteDatabase()
{
    db = open_in_memory();
}

SqliteDatabase::SqliteDatabase(sqlite3 *db)
    : db(db)
{
}

SqliteDatabase::SqliteDatabase(const path &dbname, bool ro)
    : read_only(ro)
{
    LOG_TRACE(logger, "Initializing database: " << dbname << (read_only ? ", in-memory mode" : ""));

    // TODO: remove when memory db is turned on
    read_only = false;

    loadDatabase(dbname);
}

SqliteDatabase::~SqliteDatabase()
{
    close();
}

void SqliteDatabase::close()
{
    if (!isLoaded())
        return;

    // turn on only for memory db
    //save(fullName);

    sqlite3_close(db);
    db = nullptr;
}

void SqliteDatabase::loadDatabase(const path &dbname)
{
    if (isLoaded())
        return;

    close();

    LOG_TRACE(logger, "Opening database: " << dbname);

    if (read_only)
        db = load_from_file_to_memory(dbname);
    else
        db = load_from_file(dbname, read_only);

    fullName = dbname;
}

void SqliteDatabase::save(const path &fn) const
{
    if (!isLoaded())
        return;
    save_from_memory_to_file(fn, db);
}

bool SqliteDatabase::isLoaded() const
{
    return db != nullptr;
}

bool SqliteDatabase::execute(String sql, void *object, Sqlite3Callback callback, bool nothrow, String *err) const
{
    if (!isLoaded())
        throw std::runtime_error("db is not loaded");

    boost::trim(sql);

    // TODO: remove later when sqlite won't be crashing
    static std::mutex m;
    std::unique_lock<std::mutex> lk(m);

    // lock always for now
    ScopedFileLock lock(get_lock(fullName), std::defer_lock);
    if (!read_only)
        lock.lock();

    LOG_TRACE(logger, "Executing sql statement: " << sql);
    char *errmsg;
    String error;
    sqlite3_exec(db, sql.c_str(), callback, object, &errmsg);
    if (errmsg)
    {
        auto s = sql.substr(0, MAX_ERROR_SQL_LENGTH);
        if (sql.size() > MAX_ERROR_SQL_LENGTH)
            s += "...";
        error = "Error executing sql statement:\n" + s + "\nError: " + errmsg;
        sqlite3_free(errmsg);
        if (nothrow)
        {
            if (errmsg && err)
                *err = error;
        }
        else
            throw std::runtime_error(error);
    }
    return error.empty();
}

bool SqliteDatabase::execute(String sql, DatabaseCallback callback, bool nothrow, String *err) const
{
    if (!isLoaded())
        throw std::runtime_error("db is not loaded");

    boost::trim(sql);

    // TODO: remove later when sqlite won't be crashing
    static std::mutex m;
    std::unique_lock<std::mutex> lk(m);

    // lock always for now
    ScopedFileLock lock(get_lock(fullName), std::defer_lock);
    if (!read_only)
        lock.lock();

    //
    LOG_TRACE(logger, "Executing sql statement: " << sql);
    char *errmsg;
    String error;
    auto cb = [](void *o, int ncols, char **cols, char **names)
    {
        auto f = (DatabaseCallback *)o;
        if (*f)
            return (*f)(ncols, cols, names);
        return 0;
    };
    int rc = sqlite3_exec(db, sql.c_str(), cb, &callback, &errmsg);
    if (errmsg)
    {
        auto s = sql.substr(0, MAX_ERROR_SQL_LENGTH);
        if (sql.size() > MAX_ERROR_SQL_LENGTH)
            s += "...";
        error = "Error executing sql statement:\n" + s + "\nError: " + errmsg;
        sqlite3_free(errmsg);
        if (nothrow)
        {
            if (errmsg && err)
                *err = error;
        }
        else
            throw std::runtime_error(error);
    }
    else if (rc != SQLITE_OK)
    {
        auto s = sql.substr(0, MAX_ERROR_SQL_LENGTH);
        if (sql.size() > MAX_ERROR_SQL_LENGTH)
            s += "...";
        error = "Error executing sql statement:\n" + s;
        if (nothrow)
        {
            if (errmsg && err)
                *err = error;
        }
        else
            throw std::runtime_error(error);
    }
    return error.empty();
}

path SqliteDatabase::getFullName() const
{
    return fullName;
}

sqlite3 *SqliteDatabase::getDb() const
{
    return db;
}

int SqliteDatabase::getNumberOfColumns(const String &table) const
{
    int n = 0;
    execute("pragma table_info(" + table + ");", [&n](SQLITE_CALLBACK_ARGS)
    {
        n++;
        return 0;
    });
    return n;
}

int SqliteDatabase::getNumberOfTables() const
{
    int n = 0;
    execute("select count(*) from sqlite_master as tables where type='table';", [&n](SQLITE_CALLBACK_ARGS)
    {
        n = std::stoi(cols[0]);
        return 0;
    });
    return n;
}

void SqliteDatabase::dropTable(const String &table) const
{
    execute("drop table " + table + ";");
}

int64_t SqliteDatabase::getLastRowId() const
{
    return sqlite3_last_insert_rowid(db);
}

ext: cpp

max_stars_repo_name: linquize/cppan

max_issues_repo_name: linquize/cppan

max_forks_repo_name: linquize/cppan


text:
// Copyright David Abrahams 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef CV_CATEGORY_DWA200222_HPP
#define CV_CATEGORY_DWA200222_HPP
#include <boost/python/detail/type_traits.hpp>

namespace boost {
namespace python {
namespace detail {

template <bool is_const_, bool is_volatile_> struct cv_tag {
  BOOST_STATIC_CONSTANT(bool, is_const = is_const_);
  BOOST_STATIC_CONSTANT(bool, is_volatile = is_volatile_);
};

typedef cv_tag<false, false> cv_unqualified;
typedef cv_tag<true, false> const_;
typedef cv_tag<false, true> volatile_;
typedef cv_tag<true, true> const_volatile_;

template <class T> struct cv_category {
  //    BOOST_STATIC_CONSTANT(bool, c = is_const<T>::value);
  //    BOOST_STATIC_CONSTANT(bool, v = is_volatile<T>::value);
  typedef cv_tag<is_const<T>::value, is_volatile<T>::value> type;
};

} // namespace detail
} // namespace python
} // namespace boost

#endif // CV_CATEGORY_DWA200222_HPP

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MAP_TRANSFORMER_HPP
#define BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MAP_TRANSFORMER_HPP

#include <cstddef>

#include <boost/geometry/strategies/transform/matrix_transformers.hpp>

namespace boost { namespace geometry
{

// Silence warning C4127: conditional expression is constant
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127)
#endif

namespace strategy { namespace transform
{

/*!
\brief Transformation strategy to map from one to another Cartesian coordinate system
\ingroup strategies
\tparam Mirror if true map is mirrored upside-down (in most cases pixels
    are from top to bottom, while map is from bottom to top)
 */
template
<
    typename CalculationType,
    std::size_t Dimension1,
    std::size_t Dimension2,
    bool Mirror = false,
    bool SameScale = true
>
class map_transformer
    : public ublas_transformer<CalculationType, Dimension1, Dimension2>
{
    typedef boost::numeric::ublas::matrix<CalculationType> M;

public :
    template <typename B, typename D>
    explicit inline map_transformer(B const& box, D const& width, D const& height)
    {
        set_transformation(
                get<min_corner, 0>(box), get<min_corner, 1>(box),
                get<max_corner, 0>(box), get<max_corner, 1>(box),
                width, height);
    }

    template <typename W, typename D>
    explicit inline map_transformer(W const& wx1, W const& wy1, W const& wx2, W const& wy2,
                        D const& width, D const& height)
    {
        set_transformation(wx1, wy1, wx2, wy2, width, height);
    }

private :
    template <typename W, typename P, typename S>
    inline void set_transformation_point(W const& wx, W const& wy,
        P const& px, P const& py,
        S const& scalex, S const& scaley)
    {

        // Translate to a coordinate system centered on world coordinates (-wx, -wy)
        M t1(3,3);
        t1(0,0) = 1;   t1(0,1) = 0;   t1(0,2) = -wx;
        t1(1,0) = 0;   t1(1,1) = 1;   t1(1,2) = -wy;
        t1(2,0) = 0;   t1(2,1) = 0;   t1(2,2) = 1;

        // Scale the map
        M s(3,3);
        s(0,0) = scalex;   s(0,1) = 0;   s(0,2) = 0;
        s(1,0) = 0;    s(1,1) = scaley;  s(1,2) = 0;
        s(2,0) = 0;    s(2,1) = 0;      s(2,2) = 1;

        // Translate to a coordinate system centered on the specified pixels (+px, +py)
        M t2(3, 3);
        t2(0,0) = 1;   t2(0,1) = 0;   t2(0,2) = px;
        t2(1,0) = 0;   t2(1,1) = 1;   t2(1,2) = py;
        t2(2,0) = 0;   t2(2,1) = 0;   t2(2,2) = 1;

        // Calculate combination matrix in two steps
        this->m_matrix = boost::numeric::ublas::prod(s, t1);
        this->m_matrix = boost::numeric::ublas::prod(t2, this->m_matrix);
    }

    template <typename W, typename D>
    void set_transformation(W const& wx1, W const& wy1, W const& wx2, W const& wy2,
                    D const& width, D const& height)
    {
        D px1 = 0;
        D py1 = 0;
        D px2 = width;
        D py2 = height;

        // Get the same type, but at least a double
        typedef typename select_most_precise<D, double>::type type;

        // Calculate appropriate scale, take min because whole box must fit
        // Scale is in PIXELS/MAPUNITS (meters)
        W wdx = wx2 - wx1;
        W wdy = wy2 - wy1;
        type sx = (px2 - px1) / boost::numeric_cast<type>(wdx);
        type sy = (py2 - py1) / boost::numeric_cast<type>(wdy);

        if (SameScale)
        {
            type scale = (std::min)(sx, sy);
            sx = scale;
            sy = scale;
        }

        // Calculate centerpoints
        W wtx = wx1 + wx2;
        W wty = wy1 + wy2;
        W two = 2;
        W wmx = wtx / two;
        W wmy = wty / two;
        type pmx = (px1 + px2) / 2.0;
        type pmy = (py1 + py2) / 2.0;

        set_transformation_point(wmx, wmy, pmx, pmy, sx, sy);

        if (Mirror)
        {
            // Mirror in y-direction
            M m(3,3);
            m(0,0) = 1;   m(0,1) = 0;   m(0,2) = 0;
            m(1,0) = 0;   m(1,1) = -1;  m(1,2) = 0;
            m(2,0) = 0;   m(2,1) = 0;   m(2,2) = 1;

            // Translate in y-direction such that it fits again
            M y(3, 3);
            y(0,0) = 1;   y(0,1) = 0;   y(0,2) = 0;
            y(1,0) = 0;   y(1,1) = 1;   y(1,2) = height;
            y(2,0) = 0;   y(2,1) = 0;   y(2,2) = 1;

            // Calculate combination matrix in two steps
            this->m_matrix = boost::numeric::ublas::prod(m, this->m_matrix);
            this->m_matrix = boost::numeric::ublas::prod(y, this->m_matrix);
        }
    }
};

}} // namespace strategy::transform

#if defined(_MSC_VER)
#pragma warning(pop)
#endif

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MAP_TRANSFORMER_HPP

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
/*
 * MIT License
 *
 * Copyright (c) 2022 Szymon Milewski
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Utility.h"
#include "KeyboardResponsiveTextEdit.h"

#include <QString>
#include <QMessageBox>
#include <QLabel>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow) {
    ui->setupUi(this);
    ui->inputTextEdit->setPlaceholderText("Type here");
    ui->chatTextWidget->setReadOnly(true);

    animatedLabelFactory = new AnimatedLabel{this};
    animatedLabelFactory->createAnimation(ui->animatedLabel);

    setupAppearance();

    Utility::setButtonIcon(ui->emojiButton, ":/img/img/emoji.png", 1.5);
    Utility::setButtonIcon(ui->attachmentsButton, ":/img/img/clip.png", 1.5);
    Utility::setButtonIcon(ui->sendButton, ":/img/img/arrow.png", 1.1);

    client = std::make_unique<Client>();
    server = std::make_unique<Server>();

    connect(client.get(), &Client::messageReceived, this, &MainWindow::onMessageReceived, Qt::BlockingQueuedConnection);
    connect(client.get(), &Client::errorOccured, this, &MainWindow::onErrorOccured, Qt::BlockingQueuedConnection);
    connect(client.get(), &Client::connected, this, &MainWindow::onConnected, Qt::BlockingQueuedConnection);
    connect(client.get(), &Client::badConnect, this, &MainWindow::onBadConnect, Qt::BlockingQueuedConnection);
    connect(client.get(), &Client::serverMessageReceived, this, &MainWindow::onServerMessageReceived, Qt::BlockingQueuedConnection);

    connect(ui->inputTextEdit, &KeyboardResponsiveTextEdit::enterPressed, this, &MainWindow::onEnterPressed);
}

MainWindow::~MainWindow() {
    if (hosted)
        server->stop();

    if (connected)
        client->disconnect();

    delete ui;
}

void MainWindow::on_connectButton_clicked() {
    ui->stackedWidget_2->setCurrentIndex(1);
}

void MainWindow::on_hostButton_clicked() {
    ui->stackedWidget_2->setCurrentIndex(2);
}

void MainWindow::on_exitButton_clicked() {
    QApplication::exit();
}

void MainWindow::on_backButton_2_clicked() {
    ui->stackedWidget_2->setCurrentIndex(0);
}

void MainWindow::on_connectButton_2_clicked() {
    ui->connection_status_label->setText("Connecting to " + ui->ip_address_le->text() + "...");
    auto const ip_address_raw{ui->ip_address_le->text().toStdString()};
    auto const port{ui->port_le->text().toShort()};

    system::error_code bad_address;
    auto const ip_address{ boost::asio::ip::address::from_string(ip_address_raw, bad_address) };

    if (!bad_address)
        client->connect(ip_address, port, Utility::Usertype::USER);
}

void MainWindow::on_exitButton_2_clicked() {
    QApplication::exit();
}

void MainWindow::on_backButton_3_clicked() {
    ui->stackedWidget_2->setCurrentIndex(0);
}

void MainWindow::on_startButton_clicked() {
    auto const port{ui->server_port_le->text().toShort()};
    auto const address_raw{ui->ip_address_le_2->text().toStdString()};
    auto const room_name{ui->room_name_le->text().toStdString()};

    system::error_code bad_address;
    auto const address{asio::ip::address::from_string(address_raw, bad_address)};

    if (!bad_address) {
        try {
            server->start(address, port);
            server->setRoomName(room_name);

            hosted = true;
            ui->username_le->setText(ui->host_username_le->text());

            client->connect(server->address(), port, Utility::Usertype::ADMIN);
        }
        catch(system::system_error const& error) {
            auto errorMsgBox{new QMessageBox{this}};
            errorMsgBox->setText("Couldn't start server: " + QString::fromStdString(error.what()));

            errorMsgBox->exec();
        }
    }
    else
        ui->bad_ip_address_label->setText("Bad ip address!");
}

void MainWindow::on_exitButton_3_clicked() {
    QApplication::exit();
}

void MainWindow::on_sendButton_clicked() {
    sendMessage();
}

void MainWindow::onMessageReceived(std::vector<std::string>& message_set) {
    auto const room_name{ message_set[1] };
    auto const user_list{ message_set[2] };
    auto const user_name{ message_set[3] };
    auto const user_type{ message_set[4] };
    auto const message{ message_set[5] };

    updateRoomName(room_name);
    updateUserlist(strToVectorUserlist(user_list));

    ui->chatTextWidget->appendPlainText(QString::fromStdString(user_name + "(" + user_type + "): " + message));
}

void MainWindow::onErrorOccured(system::error_code const& ec) {
    auto errorMsgBox{new QMessageBox{this}};
    errorMsgBox->setText("Error occured: " + QString::fromStdString(ec.message()) + "\nError code: " + QString::number(ec.value()));

    errorMsgBox->exec();
}

void MainWindow::onEnterPressed() {
    sendMessage();
}

void MainWindow::sendMessage() {
    if (!ui->inputTextEdit->toPlainText().isEmpty()) {
        auto const message{ui->inputTextEdit->toPlainText().toStdString()};

        client->sendMessage(message);
        ui->inputTextEdit->clear();
    }
}

void MainWindow::updateUserlist(std::vector<std::string> const& user_list) {
    ui->userlistWidget->clear();
    for (auto const& user : user_list)
        ui->userlistWidget->addItem(QString::fromStdString(user));
}

void MainWindow::onConnected() {
    client->setClientUsername(ui->username_le->text().toStdString());
    client->communicate();

    connected = true;
    ui->username_label->setText(ui->username_le->text());
    ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::onBadConnect(system::error_code const& ec) {
    QString reason;
    switch(ec.value()) {
        case 10049:
            reason = "Bad ip address"; break;
        case 10051:
            reason = "Server unreachable"; break;
        case 10060:
            reason = "Connection timed out"; break;
        case 10061:
            reason = "Connection refused"; break;
        default:
            reason = QString::fromStdString(ec.message()) + "\nError code: " + QString::number(ec.value()); break;
    }
    ui->connection_status_label->setText("Could not connect to the server: " + reason);
}

void MainWindow::setupAppearance() {
    setStyleSheet("color: #f0f0f0; background-color: qlineargradient( x1:0 y1:0, x2:1 y2:0, stop:0 #272929, stop:1 #797687);} ");
}

void MainWindow::onServerMessageReceived(std::vector<std::string>& message_set) {
    auto const room_name{message_set[1]};
    auto const userlist{message_set[2]};
    auto const username{QString::fromStdString(message_set[3])};

    updateRoomName(room_name);
    updateUserlist(strToVectorUserlist(userlist));

    if (MessageTypeConvertions::strToMessageType(message_set[0]) == MessageType::USER_CONNECTED)
        ui->chatTextWidget->appendPlainText(username + " has connected to the server!");

    else
        ui->chatTextWidget->appendPlainText(username + " has left the server. ");
}

void MainWindow::on_exitLobbyButton_clicked() {
    QApplication::exit();
}

void MainWindow::on_leaveLobbyButton_clicked() {
    if (hosted) {
        server->stop();
        hosted = false;
    }

    if (connected) {
        client->disconnect();
        connected = false;
    }

    clearWidgets();

    ui->stackedWidget->setCurrentIndex(0);
    ui->stackedWidget_2->setCurrentIndex(0);
}

void MainWindow::clearWidgets() {
    clearInputs();

    ui->userlistWidget->clear();
    ui->chatTextWidget->clear();
}

void MainWindow::clearInputs() {
    ui->username_le->clear();
    ui->ip_address_le->clear();
    ui->port_le->clear();
    ui->connection_status_label->clear();

    ui->bad_ip_address_label->clear();
    ui->room_name_le->clear();
    ui->host_username_le->clear();
    ui->ip_address_le_2->clear();
    ui->server_port_le->clear();
}

std::vector<std::string> MainWindow::strToVectorUserlist(std::string_view user_list_str) {
    std::vector<std::string> user_list;
    boost::split(user_list, user_list_str, boost::is_any_of(","));
    return user_list;
}

void MainWindow::updateRoomName(std::string_view room_name) {
    ui->roomname_label->setText(QString::fromStdString(room_name.data()));
}

max_stars_repo_name: Cyberah/Text-Messenger

max_issues_repo_name: Cyberah/Text-Messenger

max_forks_repo_name: Cyberah/Text-Messenger


text:
//
// strand_service.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_DETAIL_STRAND_SERVICE_HPP
#define BOOST_ASIO_DETAIL_STRAND_SERVICE_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/push_options.hpp>

#include <boost/asio/detail/push_options.hpp>
#include <boost/functional/hash.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/asio/detail/pop_options.hpp>

#include <boost/asio/io_service.hpp>
#include <boost/asio/detail/call_stack.hpp>
#include <boost/asio/detail/completion_handler.hpp>
#include <boost/asio/detail/fenced_block.hpp>
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <boost/asio/detail/mutex.hpp>
#include <boost/asio/detail/op_queue.hpp>
#include <boost/asio/detail/operation.hpp>
#include <boost/asio/detail/service_base.hpp>

namespace boost {
namespace asio {
namespace detail {

// Default service implementation for a strand.
class strand_service
  : public boost::asio::detail::service_base<strand_service>
{
private:
  struct on_do_complete_exit;
  struct on_dispatch_exit;

public:

  // The underlying implementation of a strand.
  class strand_impl
    : public operation
  {
  public:
    strand_impl()
      : operation(&strand_service::do_complete),
        count_(0)
    {
    }

  private:
    // Only this service will have access to the internal values.
    friend class strand_service;
    friend struct on_do_complete_exit;
    friend struct on_dispatch_exit;

    // Mutex to protect access to internal data.
    boost::asio::detail::mutex mutex_;

    // The count of handlers in the strand, including the upcall (if any).
    std::size_t count_;

    // The handlers waiting on the strand.
    op_queue<operation> queue_;
  };

  typedef strand_impl* implementation_type;

  // Construct a new strand service for the specified io_service.
  explicit strand_service(boost::asio::io_service& io_service)
    : boost::asio::detail::service_base<strand_service>(io_service),
      io_service_(boost::asio::use_service<io_service_impl>(io_service)),
      mutex_(),
      salt_(0)
  {
  }

  // Destroy all user-defined handler objects owned by the service.
  void shutdown_service()
  {
    op_queue<operation> ops;

    boost::asio::detail::mutex::scoped_lock lock(mutex_);

    for (std::size_t i = 0; i < num_implementations; ++i)
      if (strand_impl* impl = implementations_[i].get())
        ops.push(impl->queue_);
  }

  // Construct a new strand implementation.
  void construct(implementation_type& impl)
  {
    std::size_t index = boost::hash_value(&impl);
    boost::hash_combine(index, salt_++);
    index = index % num_implementations;

    boost::asio::detail::mutex::scoped_lock lock(mutex_);

    if (!implementations_[index])
      implementations_[index].reset(new strand_impl);
    impl = implementations_[index].get();
  }

  // Destroy a strand implementation.
  void destroy(implementation_type& impl)
  {
    impl = 0;
  }

  // Request the io_service to invoke the given handler.
  template <typename Handler>
  void dispatch(implementation_type& impl, Handler handler)
  {
    // If we are already in the strand then the handler can run immediately.
    if (call_stack<strand_impl>::contains(impl))
    {
      boost::asio::detail::fenced_block b;
      boost_asio_handler_invoke_helpers::invoke(handler, handler);
      return;
    }

    // Allocate and construct an object to wrap the handler.
    typedef completion_handler<Handler> value_type;
    typedef handler_alloc_traits<Handler, value_type> alloc_traits;
    raw_handler_ptr<alloc_traits> raw_ptr(handler);
    handler_ptr<alloc_traits> ptr(raw_ptr, handler);

    // If we are running inside the io_service, and no other handler is queued
    // or running, then the handler can run immediately.
    bool can_dispatch = call_stack<io_service_impl>::contains(&io_service_);
    impl->mutex_.lock();
    bool first = (++impl->count_ == 1);
    if (can_dispatch && first)
    {
      // Immediate invocation is allowed.
      impl->mutex_.unlock();

      // Memory must be releaesed before any upcall is made.
      ptr.reset();

      // Indicate that this strand is executing on the current thread.
      call_stack<strand_impl>::context ctx(impl);

      // Ensure the next handler, if any, is scheduled on block exit.
      on_dispatch_exit on_exit = { &io_service_, impl };
      (void)on_exit;

      boost::asio::detail::fenced_block b;
      boost_asio_handler_invoke_helpers::invoke(handler, handler);
      return;
    }

    // Immediate invocation is not allowed, so enqueue for later.
    impl->queue_.push(ptr.get());
    impl->mutex_.unlock();
    ptr.release();

    // The first handler to be enqueued is responsible for scheduling the
    // strand.
    if (first)
      io_service_.post_immediate_completion(impl);
  }

  // Request the io_service to invoke the given handler and return immediately.
  template <typename Handler>
  void post(implementation_type& impl, Handler handler)
  {
    // Allocate and construct an object to wrap the handler.
    typedef completion_handler<Handler> value_type;
    typedef handler_alloc_traits<Handler, value_type> alloc_traits;
    raw_handler_ptr<alloc_traits> raw_ptr(handler);
    handler_ptr<alloc_traits> ptr(raw_ptr, handler);

    // Add the handler to the queue.
    impl->mutex_.lock();
    bool first = (++impl->count_ == 1);
    impl->queue_.push(ptr.get());
    impl->mutex_.unlock();
    ptr.release();

    // The first handler to be enqueue is responsible for scheduling the strand.
    if (first)
      io_service_.post_immediate_completion(impl);
  }

private:
  static void do_complete(io_service_impl* owner, operation* base,
      boost::system::error_code /*ec*/, std::size_t /*bytes_transferred*/)
  {
    if (owner)
    {
      strand_impl* impl = static_cast<strand_impl*>(base);

      // Get the next handler to be executed.
      impl->mutex_.lock();
      operation* o = impl->queue_.front();
      impl->queue_.pop();
      impl->mutex_.unlock();

      // Indicate that this strand is executing on the current thread.
      call_stack<strand_impl>::context ctx(impl);

      // Ensure the next handler, if any, is scheduled on block exit.
      on_do_complete_exit on_exit = { owner, impl };
      (void)on_exit;

      o->complete(*owner);
    }
  }

  // Helper class to re-post the strand on exit.
  struct on_do_complete_exit
  {
    io_service_impl* owner_;
    strand_impl* impl_;

    ~on_do_complete_exit()
    {
      impl_->mutex_.lock();
      bool more_handlers = (--impl_->count_ > 0);
      impl_->mutex_.unlock();

      if (more_handlers)
        owner_->post_immediate_completion(impl_);
    }
  };

  // Helper class to re-post the strand on exit.
  struct on_dispatch_exit
  {
    io_service_impl* io_service_;
    strand_impl* impl_;

    ~on_dispatch_exit()
    {
      impl_->mutex_.lock();
      bool more_handlers = (--impl_->count_ > 0);
      impl_->mutex_.unlock();

      if (more_handlers)
        io_service_->post_immediate_completion(impl_);
    }
  };

  // The io_service implementation used to post completions.
  io_service_impl& io_service_;

  // Mutex to protect access to the array of implementations.
  boost::asio::detail::mutex mutex_;

  // Number of implementations shared between all strand objects.
  enum { num_implementations = 193 };

  // The head of a linked list of all implementations.
  boost::scoped_ptr<strand_impl> implementations_[num_implementations];

  // Extra value used when hashing to prevent recycled memory locations from
  // getting the same strand implementation.
  std::size_t salt_;
};

} // namespace detail
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_STRAND_SERVICE_HPP

max_stars_repo_name: jonstewart/boost-svn

max_issues_repo_name: jonstewart/boost-svn

max_forks_repo_name: jonstewart/boost-svn


text:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <boost/algorithm/string.hpp>
#include <iostream>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
	std::string comando;
	std::vector<std::string> list;
	std::string tmp = ui->lineEdit->text ().toStdString ();

	if (ui->mp3->isChecked() == true){
		comando = "youtube-dl -x --audio-format mp3 -o '~/Music/%(title)s.%(ext)s' ";
	}else if (ui->ogg->isChecked() == true){
		comando = "youtube-dl -x --audio-format vorbis -o '~/Music/%(title)s.%(ext)s' ";
	}else if (ui->mp4->isChecked() == true){
		comando = "youtube-dl --recode-video mp4 -o '~/Music/%(title)s.%(ext)s' ";
	}
	boost::split (list, tmp, [](char c){return c == ' ';});
	for (std::string url : list){
		comando+= url;
		comando+= " ";
	}
	std::cout << comando << std::endl;
	ui->pushButton->setEnabled (false);
	ui->statusBar->showMessage (tr("Wait a minute, your download is in progress"));
	system(comando.c_str());
	ui->statusBar->showMessage (tr("Completed"));
	ui->pushButton->setEnabled (true);
}


text:
// Copyright 2016 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"

#include "Generic/common/InternalInconsistencyException.h"
#include "Generic/common/UTF8OutputStream.h"
#include "Generic/common/ParamReader.h"
#include "Generic/common/OutputUtil.h"
#include "Generic/results/MSANamesResultCollector.h"
#include "Generic/theories/DocTheory.h"
#include "Generic/theories/SentenceTheory.h"
#include "Generic/theories/NameTheory.h"
#include "Generic/theories/NameSpan.h"

#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>

MSANamesResultCollector::MSANamesResultCollector() { }

void MSANamesResultCollector::loadDocTheory(DocTheory* theory) {
	_docTheory = theory;
}

std::wstring MSANamesResultCollector::produceOutputHelper() {
	std::wstringstream wss;
	wss << L"<MSANAMESXML>\n";

	for (int i = 0; i < _docTheory->getNSentences(); i++) {
		const SentenceTheory *st = _docTheory->getSentenceTheory(i);
		NameTheory *nt = st->getNameTheory();
		for (int j = 0; j < nt->getNNameSpans(); j++) {
			NameSpan *ns = nt->getNameSpan(j);
			wss << L"<name type=\"" << ns->type.getName() << "\">" << OutputUtil::escapeXML(nt->getNameString(j)) << "</name>\n";
		}
	}

	wss << L"</MSANAMESXML>\n";
	return wss.str();

}

void MSANamesResultCollector::produceOutput(const wchar_t *output_dir,
									   const wchar_t *doc_filename)
{
	// File name
	std::wstring output_file = std::wstring(output_dir) + LSERIF_PATH_SEP + std::wstring(doc_filename);
	if (!boost::algorithm::ends_with(output_file, L".txt")) {
		output_file += L".msa.names.xml";
	} else {
		output_file = boost::algorithm::replace_last_copy(output_file, ".txt", ".msa.names.xml");
	}

	// Open output stream
	UTF8OutputStream stream;
	stream.open(output_file.c_str());

	std::wstring results = produceOutputHelper();

	// Write out
	stream << results;

	stream.close();
}

void MSANamesResultCollector::produceOutput(std::wstring *results) { *results = produceOutputHelper(); }

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
#include "SPlisHSPlasH/Common.h"
#include <Eigen/Dense>
#include "extern/cxxopts/cxxopts.hpp"
#include "Utilities/Timing.h"
#include "Utilities/OBJLoader.h"
#include "WindingNumbers.h"
#include "Utilities/PartioReaderWriter.h"
#include "Utilities/Version.h"

using namespace SPH;
using namespace Eigen;
using namespace std;
using namespace Utilities;

INIT_TIMING
INIT_LOGGING

// Enable memory leak detection
#ifdef _DEBUG
#ifndef EIGEN_ALIGN
#define new DEBUG_NEW
#endif
#endif

void sampleObject(TriangleMesh &mesh);
void loadObj(const std::string &filename, TriangleMesh &mesh, const Vector3r &scale);
void partioExport();

struct Region
{
public:
	typedef Real value_type;

	Region() {}
	Region(Real minx, Real miny, Real minz,
		Real maxx, Real maxy, Real maxz)
	{
		m_min = Vector3r(minx, miny, minz);
		m_max = Vector3r(maxx, maxy, maxz);
	}

	Vector3r m_min;
	Vector3r m_max;
};

string exePath;
string inputFile = "";
string outputFile = "";
Real radius = 0.05f;
Real scale = 1.0;
Real diameter = radius*2.0;
int mode = 0;
Region region;
bool useRegion = false;
std::vector<Vector3r> particles;

std::istream& operator >> (std::istream& istream, Region& r)
{
	return istream >> std::skipws >> r.m_min[0] >> r.m_min[1] >> r.m_min[2] >> r.m_max[0] >> r.m_max[1] >> r.m_max[2];
}

std::ostream& operator << (std::ostream& out, const Region& r)
{
	out << r.m_min[0] << ", " << r.m_min[1] << ", " << r.m_min[2] << ", " << r.m_max[0] << ", " << r.m_max[1] << ", " << r.m_max[2];
	return out;
}

// main
int main(int argc, char **argv)
{
	REPORT_MEMORY_LEAKS;

	std::cout << "Git refspec: " << GIT_REFSPEC << std::endl;
	std::cout << "Git SHA1: " << GIT_SHA1 << std::endl;
	std::cout << "Git status: " << GIT_LOCAL_STATUS << std::endl;

	Timing::m_dontPrintTimes = true;

	exePath = string(argv[0]);
	const size_t npos = exePath.rfind("\\");
	if (npos != string::npos)
		exePath = exePath.substr(0, exePath.rfind("\\") + 1);
	else
		exePath = ".";

	try
	{
		cxxopts::Options options(argv[0], "VolumeSampling - Sample a volumetric geometry given by an OBJ file.");

		options.add_options()
			("h,help", "Print help")
			("i,input", "Input file (obj)", cxxopts::value<std::string>())
			("o,output", "Output file (bgeo)", cxxopts::value<std::string>())
			("r,radius", "Particle radius", cxxopts::value<Real>()->default_value("0.025"))
			("s,scale", "Scaling of input geometry", cxxopts::value<Real>()->default_value("1.0"))
			("m,mode", "Mode (regular=0, almost dense=1, dense=2)", cxxopts::value<int>()->default_value("0"))
			("region", "Region to fill with particles (e.g. --region \"0 0 0 1 1 1\"", cxxopts::value<Region>())
			;

		options.parse(argc, argv);

		if (options.count("help"))
		{
			std::cout << options.help({ "", "Group" }) << std::endl;
			exit(0);
		}

		if (options.count("input") && options.count("output"))
		{
			inputFile = options["input"].as<std::string>();
			std::cout << "Input = " << inputFile << std::endl;
			outputFile = options["output"].as<std::string>();
			std::cout << "Output = " << outputFile << std::endl;
		}
		else
		{
			std::cout << "Input or output missing!" << std::endl;
			std::cout << options.help({ "", "Group" }) << std::endl;
			exit(1);
		}

		if (options.count("radius"))
			radius = options["radius"].as<Real>();
		cout << "Radius: " << radius << endl;

		if (options.count("scale"))
			scale = options["scale"].as<Real>();
		cout << "Scale: " << scale << endl;

		if (options.count("mode"))
			mode = options["mode"].as<int>();
		cout << "Mode: " << mode << endl;

		if (options.count("region"))
		{
			region = options["region"].as<Region>();
			useRegion = true;
			cout << "Region: " << region << endl;
		}
	}
	catch (const cxxopts::OptionException& e)
	{
		std::cout << "error parsing options: " << e.what() << std::endl;
		exit(1);
	}

	diameter = 2.0 * radius;
	TriangleMesh mesh;
	loadObj(inputFile, mesh, scale*Vector3r::Ones());
 	sampleObject(mesh);
	PartioReaderWriter::writeParticles(outputFile, (unsigned int)particles.size(), particles.data(), NULL, radius);

	std::cout << "Generated particles: " << particles.size() << std::endl;

	Timing::printAverageTimes();

	return 0;
}

void loadObj(const std::string &filename, TriangleMesh &mesh, const Vector3r &scale)
{
	std::vector<OBJLoader::Vec3f> x;
	std::vector<OBJLoader::Vec3f> normals;
	std::vector<MeshFaceIndices> faces;
	OBJLoader::Vec3f s = { (float)scale[0], (float)scale[1], (float)scale[2] };
	OBJLoader::loadObj(filename, &x, &faces, &normals, nullptr, s);

	mesh.release();
	const unsigned int nPoints = (unsigned int)x.size();
	const unsigned int nFaces = (unsigned int)faces.size();
	mesh.initMesh(nPoints, nFaces);
	for (unsigned int i = 0; i < nPoints; i++)
	{
		mesh.addVertex(Vector3r(x[i][0], x[i][1], x[i][2]));
	}
	for (unsigned int i = 0; i < nFaces; i++)
	{
		// Reduce the indices by one
		int posIndices[3];
		for (int j = 0; j < 3; j++)
		{
			posIndices[j] = faces[i].posIndices[j] - 1;
		}

		mesh.addFace(&posIndices[0]);
	}

	LOG_INFO << "Number of triangles: " << nFaces;
	LOG_INFO << "Number of vertices: " << nPoints;
}

 void sampleObject(TriangleMesh &mesh)
 {
	 Vector3r *v = mesh.getVertices().data();

 	// compute bounding box
 	Vector3r min, max;
 	min = v[0];
 	max = min;
 	for (unsigned int i = 1; i < mesh.numVertices(); ++i)
 	{
 		const Vector3r& p = v[i];
 		for (unsigned int j = 0; j < 3; ++j) {
 			min[j] = std::min(min[j], p[j]);
 			max[j] = std::max(max[j], p[j]);
 		}
 	}

	if (useRegion)
 	{
		for (unsigned int i=0; i < 3; i++)
		{
			min[i] = std::max(scale * region.m_min[i], min[i]);
			max[i] = std::min(scale * region.m_max[i], max[i]);
		}
 	}

 	// sample object
 	const unsigned int numberOfSamplePoints = (((unsigned int)((1.0f / diameter) * (max[2] - min[2]))) + 1) *
 		(((unsigned int)((1.0f / diameter) * (max[1] - min[1]))) + 1) *
 		(((unsigned int)((1.0f / diameter) * (max[0] - min[0]))) + 1);
 	unsigned int currentSample = 0;
 	Real currentPercent = 0.01;
 	int counter_x = 0;
 	int counter_y = 0;
 	Real xshift = diameter;
 	Real yshift = diameter;

 	if (mode == 1)
 		yshift = sqrt(3.0) * radius;
 	else if (mode == 2)
 	{
 		xshift = sqrt(3.0) * radius;
 		yshift = sqrt(6.0) * diameter / 3.0;
 	}
 	for (Real z = min[2]; z <= max[2]; z += diameter)
 	{
 		for (Real y = min[1]; y <= max[1]; y += yshift)
 		{
 			for (Real x = min[0]; x <= max[0]; x += xshift)
 			{
 				Vector3r particlePosition;
 				if (mode == 1)
 				{
 					if (counter_y % 2 == 0)
 						particlePosition = Vector3r(x, y + radius, z + radius);
 					else
 						particlePosition = Vector3r(x + radius, y + radius, z);
 				}
 				else if (mode == 2)
 				{
 					particlePosition = Vector3r(x, y + radius, z + radius);

 					Vector3r shift_vec(0, 0, 0);
 					if (counter_x % 2)
 					{
 						shift_vec[2] += diameter / (2.0 * (counter_y % 2 ? -1 : 1));
 					}
 					if (counter_y % 2)
 					{
 						shift_vec[0] += xshift / 2.0;
 						shift_vec[2] += diameter / 2.0;
 					}
 					particlePosition += shift_vec;
 				}
 				else
 				{
 					// Use center of voxel
 					particlePosition = Vector3r(x + radius, y + radius, z + radius);
 				}

 				const Real w_p = WindingNumbers::computeGeneralizedWindingNumber(particlePosition, mesh);
 				if (w_p > 0.5f)
 					particles.push_back(particlePosition);
 				currentSample++;

 				if ((Real)currentSample / (Real)numberOfSamplePoints > currentPercent)
 				{
 					std::cout << currentPercent * 100.0 << "%\n";
 					currentPercent += 0.01;
 				}
 				counter_x++;
 			}
 			counter_x = 0;
 			counter_y++;
 		}
 		counter_y = 0;
 	}
 	std::cout << "100%\n";
}

max_stars_repo_name: NCCA/SPlisHSPlasH

max_issues_repo_name: eshafeeqe/SPlisHSPlasH

max_forks_repo_name: eshafeeqe/SPlisHSPlasH