text:
/*
 * Copyright 2015 David A. Boyuka II
 *
 * 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.
 */

/*
 * test-region-ridconv.cpp
 *
 *  Created on: Jun 3, 2014
 *      Author: David A. Boyuka II
 */

#include <cstdlib>
#include <cstdint>
#include <cassert>
#include <vector>
#include <boost/smart_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/timer/timer.hpp>

#include "pique/region/region-encoding.hpp"
#include "pique/region/ii/ii.hpp"
#include "pique/region/ii/ii-encode.hpp"
#include "pique/region/cii/cii.hpp"
#include "pique/region/cii/cii-encode.hpp"
#include "pique/region/cblq/cblq.hpp"
#include "pique/region/cblq/cblq-encode.hpp"
#include "pique/region/wah/wah.hpp"
#include "pique/region/wah/wah-encode.hpp"

using boost::timer::cpu_timer;
using boost::timer::cpu_times;
static double walltime(const cpu_timer &timer) { return (double)timer.elapsed().wall * 1e-9; }

static const uint64_t region_size = 16;
static const uint64_t region_counts[] = {3, 4, 1, 3, 4, 1, 0, 0};
static const std::vector<uint32_t> expected_rids = {0, 1, 2, 7, 11, 12, 13, 14};

static const uint64_t RANDOM_REGION_SIZE = 1ULL<<12;
static const double RANDOM_REGION_PROB = 0.1;

template<typename RegionEncoderT>
static boost::shared_ptr< typename RegionEncoderT::RegionEncodingOutT >
make_region(typename RegionEncoderT::RegionEncoderConfig conf, uint64_t region_size, const uint64_t region_counts[]) {
    RegionEncoderT builder(conf, region_size);

    // Repeat until 2 consecutive 0's are encountered (the sentinel value)
    for (int i = 0; region_counts[i] || region_counts[i + 1]; i += 2) {
    	builder.push_bits(region_counts[i], true);
    	builder.push_bits(region_counts[i + 1], false);
    }
    builder.finalize();

   return builder.to_region_encoding();
}

template<typename RegionEncoderT>
static boost::shared_ptr< typename RegionEncoderT::RegionEncodingOutT >
make_random_region(typename RegionEncoderT::RegionEncoderConfig conf, uint64_t region_size, double prob, std::vector<uint32_t> &expected) {
    RegionEncoderT builder(conf, region_size);

    // Repeat until 2 consecutive 0's are encountered (the sentinel value)
    for (uint64_t i = 0; i < region_size; i++) {
    	bool present = ((double)std::rand() / RAND_MAX) < prob;
    	builder.push_bits(1, present);

    	if (present)
    		expected.push_back(i);
    }
    builder.finalize();

   return builder.to_region_encoding();
}

template<typename RegionEncodingT>
static void test_ridconv(std::string testname, boost::shared_ptr< RegionEncodingT > region, std::vector< uint32_t > expected_rids) {

	std::vector<uint32_t> rids;

	cpu_timer elemcount_timer;
	uint64_t elemcount = region->get_element_count();
	elemcount_timer.stop();
	assert(elemcount == expected_rids.size());

	cpu_timer unsorted_timer;
	region->convert_to_rids(rids, false, true);
	unsorted_timer.stop();
	std::sort(rids.begin(), rids.end());
	assert(rids == expected_rids);

	cpu_timer sorted_timer;
	region->convert_to_rids(rids, true, true);
	sorted_timer.stop();
	assert(rids == expected_rids);

	region->convert_to_rids(rids, true, false);
	assert(rids == expected_rids);

#ifdef VERBOSE_TESTS
	printf("Test %s passed! Sorted/unsorted time: %lf/%lf, elemcount time: %lf\n", testname.c_str(), walltime(sorted_timer), walltime(unsorted_timer), walltime(elemcount_timer));
#endif
}

template<typename RegionEncoderT>
static void test_ridconv(std::string testname, typename RegionEncoderT::RegionEncoderConfig conf) {
	typedef typename RegionEncoderT::RegionEncodingOutT RegionEncodingT;

	boost::shared_ptr< RegionEncodingT > region = make_region<RegionEncoderT>(conf, region_size, region_counts);

	std::vector<uint32_t> random_expected_rids;
	boost::shared_ptr< RegionEncodingT > random_region = make_random_region<RegionEncoderT>(conf, RANDOM_REGION_SIZE, RANDOM_REGION_PROB, random_expected_rids);

	std::vector<uint32_t> inv_random_expected_rids;
	boost::shared_ptr< RegionEncodingT > inv_random_region = make_random_region<RegionEncoderT>(conf, RANDOM_REGION_SIZE, 1 - RANDOM_REGION_PROB, inv_random_expected_rids);

	test_ridconv(testname + "-small", region, expected_rids);
	test_ridconv(testname + "-big-sparse", random_region, random_expected_rids);
	test_ridconv(testname + "-big-dense", inv_random_region, inv_random_expected_rids);

#ifdef VERBOSE_TESTS
	printf("Test %s passed!\n", testname.c_str());
#endif
}

int main(int argc, char **argv) {
	test_ridconv< IIRegionEncoder >("ii", IIRegionEncoderConfig());
	test_ridconv< CIIRegionEncoder >("cii", CIIRegionEncoderConfig());
	test_ridconv< CBLQRegionEncoder<2> >("cblq2d", CBLQRegionEncoderConfig(false));
	test_ridconv< CBLQRegionEncoder<2> >("cblq2d-dense", CBLQRegionEncoderConfig(true));
	test_ridconv< CBLQRegionEncoder<3> >("cblq3d", CBLQRegionEncoderConfig(false));
	test_ridconv< CBLQRegionEncoder<3> >("cblq3d-dense", CBLQRegionEncoderConfig(true));
	test_ridconv< WAHRegionEncoder >("wah", WAHRegionEncoderConfig());
}

max_stars_repo_name: daboyuka/PIQUE

max_issues_repo_name: daboyuka/PIQUE

max_forks_repo_name: daboyuka/PIQUE


text:
#ifndef RPCZ_CONNECTION_MANAGER_PTR_H
#define RPCZ_CONNECTION_MANAGER_PTR_H

#include <boost/shared_ptr.hpp>

namespace rpcz {
class manager;
typedef boost::shared_ptr<manager> manager_ptr;
}  // namespace rpcz

#endif  // RPCZ_CONNECTION_MANAGER_PTR_H

ext: hpp


text:
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/db/catalog/drop_indexes.h"

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

#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/collection_uuid_mismatch.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/client.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/curop.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index_builds_coordinator.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl_set_member_in_standalone_mode.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/database_sharding_state.h"
#include "mongo/db/s/shard_key_index_util.h"
#include "mongo/db/service_context.h"
#include "mongo/logv2/log.h"
#include "mongo/util/visit_helper.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand

namespace mongo {
namespace {

MONGO_FAIL_POINT_DEFINE(hangAfterAbortingIndexes);

// Field name in dropIndexes command for indexes to drop.
constexpr auto kIndexFieldName = "index"_sd;

Status checkView(OperationContext* opCtx,
                 const NamespaceString& nss,
                 const CollectionPtr& collection) {
    if (!collection) {
        if (CollectionCatalog::get(opCtx)->lookupView(opCtx, nss)) {
            return Status(ErrorCodes::CommandNotSupportedOnView,
                          str::stream() << "Cannot drop indexes on view " << nss);
        }
        return Status(ErrorCodes::NamespaceNotFound, str::stream() << "ns not found " << nss);
    }
    return Status::OK();
}

Status checkReplState(OperationContext* opCtx,
                      NamespaceStringOrUUID dbAndUUID,
                      const CollectionPtr& collection) {
    auto replCoord = repl::ReplicationCoordinator::get(opCtx);
    auto canAcceptWrites = replCoord->canAcceptWritesFor(opCtx, dbAndUUID);
    bool writesAreReplicatedAndNotPrimary = opCtx->writesAreReplicated() && !canAcceptWrites;

    if (writesAreReplicatedAndNotPrimary) {
        return Status(ErrorCodes::NotWritablePrimary,
                      str::stream() << "Not primary while dropping indexes on database "
                                    << dbAndUUID.db() << " with collection " << dbAndUUID.uuid());
    }

    // Disallow index drops on drop-pending namespaces (system.drop.*) if we are primary.
    auto isPrimary = replCoord->getSettings().usingReplSets() && canAcceptWrites;
    const auto& nss = collection->ns();
    if (isPrimary && nss.isDropPendingNamespace()) {
        return Status(ErrorCodes::NamespaceNotFound,
                      str::stream() << "Cannot drop indexes on drop-pending namespace " << nss
                                    << " in database " << dbAndUUID.db() << " with uuid "
                                    << dbAndUUID.uuid());
    }

    return Status::OK();
}

/**
 * Validates the key pattern passed through the command.
 */
StatusWith<const IndexDescriptor*> getDescriptorByKeyPattern(OperationContext* opCtx,
                                                             const IndexCatalog* indexCatalog,
                                                             const BSONObj& keyPattern) {
    const bool includeUnfinished = true;
    std::vector<const IndexDescriptor*> indexes;
    indexCatalog->findIndexesByKeyPattern(opCtx, keyPattern, includeUnfinished, &indexes);
    if (indexes.empty()) {
        return Status(ErrorCodes::IndexNotFound,
                      str::stream() << "can't find index with key: " << keyPattern);
    } else if (indexes.size() > 1) {
        return Status(ErrorCodes::AmbiguousIndexKeyPattern,
                      str::stream() << indexes.size() << " indexes found for key: " << keyPattern
                                    << ", identify by name instead."
                                    << " Conflicting indexes: " << indexes[0]->infoObj() << ", "
                                    << indexes[1]->infoObj());
    }

    const IndexDescriptor* desc = indexes[0];
    if (desc->isIdIndex()) {
        return Status(ErrorCodes::InvalidOptions, "cannot drop _id index");
    }

    if (desc->indexName() == "*") {
        // Dropping an index named '*' results in an drop-index oplog entry with a name of '*',
        // which in 3.6 and later is interpreted by replication as meaning "drop all indexes on
        // this collection".
        return Status(ErrorCodes::InvalidOptions,
                      "cannot drop an index named '*' by key pattern.  You must drop the "
                      "entire collection, drop all indexes on the collection by using an index "
                      "name of '*', or downgrade to 3.4 to drop only this index.");
    }

    return desc;
}

/**
 * It is illegal to drop a collection's clusteredIndex.
 *
 * Returns true if 'index' is or contains the clusteredIndex.
 */
bool containsClusteredIndex(const CollectionPtr& collection, const IndexArgument& index) {
    invariant(collection && collection->isClustered());

    auto clusteredIndexSpec = collection->getClusteredInfo()->getIndexSpec();
    return stdx::visit(
        visit_helper::Overloaded{[&](const std::string& indexName) -> bool {
                                     // While the clusteredIndex's name is optional during user
                                     // creation, it should always be filled in by default on the
                                     // collection object.
                                     auto clusteredIndexName = clusteredIndexSpec.getName();
                                     invariant(clusteredIndexName.is_initialized());

                                     return clusteredIndexName.get() == indexName;
                                 },
                                 [&](const std::vector<std::string>& indexNames) -> bool {
                                     // While the clusteredIndex's name is optional during user
                                     // creation, it should always be filled in by default on the
                                     // collection object.
                                     auto clusteredIndexName = clusteredIndexSpec.getName();
                                     invariant(clusteredIndexName.is_initialized());

                                     return std::find(indexNames.begin(),
                                                      indexNames.end(),
                                                      clusteredIndexName.get()) != indexNames.end();
                                 },
                                 [&](const BSONObj& indexKey) -> bool {
                                     return clusteredIndexSpec.getKey().woCompare(indexKey) == 0;
                                 }},
        index);
}

/**
 * Returns a list of index names that the caller requested to abort/drop. Requires a collection lock
 * to be held to look up the index name from the key pattern.
 */
StatusWith<std::vector<std::string>> getIndexNames(OperationContext* opCtx,
                                                   const CollectionPtr& collection,
                                                   const IndexArgument& index) {
    invariant(opCtx->lockState()->isCollectionLockedForMode(collection->ns(), MODE_IX));

    return stdx::visit(
        visit_helper::Overloaded{
            [](const std::string& arg) -> StatusWith<std::vector<std::string>> { return {{arg}}; },
            [](const std::vector<std::string>& arg) -> StatusWith<std::vector<std::string>> {
                return arg;
            },
            [&](const BSONObj& arg) -> StatusWith<std::vector<std::string>> {
                auto swDescriptor =
                    getDescriptorByKeyPattern(opCtx, collection->getIndexCatalog(), arg);
                if (!swDescriptor.isOK()) {
                    return swDescriptor.getStatus();
                }
                return {{swDescriptor.getValue()->indexName()}};
            }},
        index);
}

/**
 * Attempts to abort a single index builder that is responsible for all the index names passed in.
 */
std::vector<UUID> abortIndexBuildByIndexNames(OperationContext* opCtx,
                                              UUID collectionUUID,
                                              std::vector<std::string> indexNames) {

    boost::optional<UUID> buildUUID =
        IndexBuildsCoordinator::get(opCtx)->abortIndexBuildByIndexNames(
            opCtx, collectionUUID, indexNames, std::string("dropIndexes command"));
    if (buildUUID) {
        return {*buildUUID};
    }
    return {};
}

/**
 * Drops single index given a descriptor.
 */
Status dropIndexByDescriptor(OperationContext* opCtx,
                             Collection* collection,
                             IndexCatalog* indexCatalog,
                             const IndexDescriptor* desc) {
    if (desc->isIdIndex()) {
        return Status(ErrorCodes::InvalidOptions, "cannot drop _id index");
    }

    // Support dropping unfinished indexes, but only if the index is 'frozen'. These indexes only
    // exist in standalone mode.
    auto entry = indexCatalog->getEntry(desc);
    if (entry->isFrozen()) {
        invariant(!entry->isReady(opCtx));
        invariant(getReplSetMemberInStandaloneMode(opCtx->getServiceContext()));
        // Return here. No need to fall through to op observer on standalone.
        return indexCatalog->dropUnfinishedIndex(opCtx, collection, desc);
    }

    // Do not allow dropping unfinished indexes that are not frozen.
    if (!entry->isReady(opCtx)) {
        return Status(ErrorCodes::IndexNotFound,
                      str::stream()
                          << "can't drop unfinished index with name: " << desc->indexName());
    }

    // Log the operation first, which reserves an optime in the oplog and sets the timestamp for
    // future writes. This guarantees the durable catalog's metadata change to share the same
    // timestamp when dropping the index below.
    opCtx->getServiceContext()->getOpObserver()->onDropIndex(
        opCtx, collection->ns(), collection->uuid(), desc->indexName(), desc->infoObj());

    auto s = indexCatalog->dropIndex(opCtx, collection, desc);
    if (!s.isOK()) {
        return s;
    }

    return Status::OK();
}

/**
 * Aborts all the index builders on the collection if the first element in 'indexesToAbort' is "*",
 * otherwise this attempts to abort a single index builder building the given index names.
 */
std::vector<UUID> abortActiveIndexBuilders(OperationContext* opCtx,
                                           const NamespaceString& collectionNs,
                                           const UUID& collectionUUID,
                                           const std::vector<std::string>& indexNames) {
    if (indexNames.empty()) {
        return {};
    }

    if (indexNames.front() == "*") {
        return IndexBuildsCoordinator::get(opCtx)->abortCollectionIndexBuilds(
            opCtx, collectionNs, collectionUUID, "dropIndexes command");
    }

    return abortIndexBuildByIndexNames(opCtx, collectionUUID, indexNames);
}

void dropReadyIndexes(OperationContext* opCtx,
                      Collection* collection,
                      const std::vector<std::string>& indexNames,
                      DropIndexesReply* reply,
                      bool forceDropShardKeyIndex) {
    invariant(opCtx->lockState()->isCollectionLockedForMode(collection->ns(), MODE_X));

    if (indexNames.empty()) {
        return;
    }

    IndexCatalog* indexCatalog = collection->getIndexCatalog();
    auto collDescription =
        CollectionShardingState::get(opCtx, collection->ns())->getCollectionDescription(opCtx);

    if (indexNames.front() == "*") {
        if (collDescription.isSharded() && !forceDropShardKeyIndex) {
            indexCatalog->dropIndexes(
                opCtx,
                collection,
                [&](const IndexDescriptor* desc) {
                    if (desc->isIdIndex()) {
                        return false;
                    }

                    if (isCompatibleWithShardKey(opCtx,
                                                 CollectionPtr(collection),
                                                 desc->getEntry(),
                                                 collDescription.getKeyPattern(),
                                                 false /* requiresSingleKey */)) {
                        return false;
                    }

                    return true;
                },
                [opCtx, collection](const IndexDescriptor* desc) {
                    opCtx->getServiceContext()->getOpObserver()->onDropIndex(opCtx,
                                                                             collection->ns(),
                                                                             collection->uuid(),
                                                                             desc->indexName(),
                                                                             desc->infoObj());
                });

            reply->setMsg("non-_id indexes and non-shard key indexes dropped for collection"_sd);
        } else {
            indexCatalog->dropAllIndexes(
                opCtx, collection, false, [opCtx, collection](const IndexDescriptor* desc) {
                    opCtx->getServiceContext()->getOpObserver()->onDropIndex(opCtx,
                                                                             collection->ns(),
                                                                             collection->uuid(),
                                                                             desc->indexName(),
                                                                             desc->infoObj());
                });

            reply->setMsg("non-_id indexes dropped for collection"_sd);
        }
        return;
    }

    bool includeUnfinished = true;
    for (const auto& indexName : indexNames) {
        if (collDescription.isSharded()) {
            uassert(
                ErrorCodes::CannotDropShardKeyIndex,
                "Cannot drop the only compatible index for this collection's shard key",
                !isLastShardKeyIndex(
                    opCtx, collection, indexCatalog, indexName, collDescription.getKeyPattern()));
        }

        auto desc = indexCatalog->findIndexByName(opCtx, indexName, includeUnfinished);
        if (!desc) {
            uasserted(ErrorCodes::IndexNotFound,
                      str::stream() << "index not found with name [" << indexName << "]");
        }
        uassertStatusOK(dropIndexByDescriptor(opCtx, collection, indexCatalog, desc));
    }
}

void assertMovePrimaryInProgress(OperationContext* opCtx, const NamespaceString& ns) {
    auto dss = DatabaseShardingState::get(opCtx, ns.db());
    auto dssLock = DatabaseShardingState::DSSLock::lockShared(opCtx, dss);

    try {
        const auto collDesc =
            CollectionShardingState::get(opCtx, ns)->getCollectionDescription(opCtx);
        if (!collDesc.isSharded()) {
            auto mpsm = dss->getMovePrimarySourceManager(dssLock);

            if (mpsm) {
                LOGV2(4976500, "assertMovePrimaryInProgress", "namespace"_attr = ns.toString());

                uasserted(ErrorCodes::MovePrimaryInProgress,
                          "movePrimary is in progress for namespace " + ns.toString());
            }
        }
    } catch (const DBException& ex) {
        if (ex.toStatus() != ErrorCodes::MovePrimaryInProgress) {
            LOGV2(4976501, "Error when getting collection description", "what"_attr = ex.what());
            return;
        }
        throw;
    }
}

}  // namespace

DropIndexesReply dropIndexes(OperationContext* opCtx,
                             const NamespaceString& nss,
                             const boost::optional<UUID>& expectedUUID,
                             const IndexArgument& index) {
    // We only need to hold an intent lock to send abort signals to the active index builder(s) we
    // intend to abort.
    boost::optional<AutoGetCollection> collection;
    collection.emplace(opCtx, nss, MODE_IX);

    checkCollectionUUIDMismatch(opCtx, nss, collection->getCollection(), expectedUUID);
    uassertStatusOK(checkView(opCtx, nss, collection->getCollection()));

    const UUID collectionUUID = (*collection)->uuid();
    const NamespaceStringOrUUID dbAndUUID = {nss.db().toString(), collectionUUID};
    uassertStatusOK(checkReplState(opCtx, dbAndUUID, collection->getCollection()));
    if (!serverGlobalParams.quiet.load()) {
        LOGV2(51806,
              "CMD: dropIndexes",
              "namespace"_attr = nss,
              "uuid"_attr = collectionUUID,
              "indexes"_attr = stdx::visit(
                  visit_helper::Overloaded{[](const std::string& arg) { return arg; },
                                           [](const std::vector<std::string>& arg) {
                                               return boost::algorithm::join(arg, ",");
                                           },
                                           [](const BSONObj& arg) { return arg.toString(); }},
                  index));
    }

    if ((*collection)->isClustered() &&
        containsClusteredIndex(collection->getCollection(), index)) {
        uasserted(5979800, "It is illegal to drop the clusteredIndex");
    }

    DropIndexesReply reply;
    reply.setNIndexesWas((*collection)->getIndexCatalog()->numIndexesTotal(opCtx));

    const bool isWildcard =
        stdx::holds_alternative<std::string>(index) && stdx::get<std::string>(index) == "*";

    IndexBuildsCoordinator* indexBuildsCoord = IndexBuildsCoordinator::get(opCtx);

    // When releasing the collection lock to send the abort signal to the index builders, it's
    // possible for new index builds to start. Keep aborting in-progress index builds if they
    // satisfy the caller's input.
    std::vector<UUID> abortedIndexBuilders;
    std::vector<std::string> indexNames;
    while (true) {
        indexNames = uassertStatusOK(getIndexNames(opCtx, collection->getCollection(), index));

        // Copy the namespace and UUID before dropping locks.
        auto collUUID = (*collection)->uuid();
        auto collNs = (*collection)->ns();

        // Release locks before aborting index builds. The helper will acquire locks on our
        // behalf.
        collection = boost::none;

        // Send the abort signal to any index builders that match the users request. Waits until
        // all aborted builders complete.
        auto justAborted = abortActiveIndexBuilders(opCtx, collNs, collUUID, indexNames);
        abortedIndexBuilders.insert(
            abortedIndexBuilders.end(), justAborted.begin(), justAborted.end());

        if (MONGO_unlikely(hangAfterAbortingIndexes.shouldFail())) {
            LOGV2(4731900, "Hanging on hangAfterAbortingIndexes fail point");
            hangAfterAbortingIndexes.pauseWhileSet();
        }

        // Abandon the snapshot as the index catalog will compare the in-memory state to the
        // disk state, which may have changed when we released the lock temporarily.
        opCtx->recoveryUnit()->abandonSnapshot();

        // Take an exclusive lock on the collection now to be able to perform index catalog
        // writes when removing ready indexes from disk.
        collection.emplace(opCtx, dbAndUUID, MODE_X);

        if (!*collection) {
            uasserted(ErrorCodes::NamespaceNotFound,
                      str::stream() << "Collection '" << nss << "' with UUID " << dbAndUUID.uuid()
                                    << " in database " << dbAndUUID.db() << " does not exist.");
        }

        // The collection could have been renamed when we dropped locks.
        collNs = (*collection)->ns();

        uassertStatusOK(checkReplState(opCtx, dbAndUUID, collection->getCollection()));

        // Check to see if a new index build was started that the caller requested to be
        // aborted.
        bool abortAgain = false;
        if (isWildcard) {
            abortAgain = indexBuildsCoord->inProgForCollection(collectionUUID);
        } else {
            abortAgain = indexBuildsCoord->hasIndexBuilder(opCtx, collectionUUID, indexNames);
        }

        if (!abortAgain) {
            assertMovePrimaryInProgress(opCtx, collNs);
            CollectionShardingState::get(opCtx, collNs)
                ->getCollectionDescription(opCtx)
                .throwIfReshardingInProgress(collNs);
            break;
        }
    }

    // Drop any ready indexes that were created while we yielded our locks while aborting using
    // similar index specs.
    if (!isWildcard && !abortedIndexBuilders.empty()) {
        // The index catalog requires that no active index builders are running when dropping ready
        // indexes.
        IndexBuildsCoordinator::get(opCtx)->assertNoIndexBuildInProgForCollection(collectionUUID);
        writeConflictRetry(opCtx, "dropIndexes", dbAndUUID.toString(), [&] {
            WriteUnitOfWork wuow(opCtx);

            // This is necessary to check shard version.
            OldClientContext ctx(opCtx, (*collection)->ns().ns());

            // Iterate through all the aborted indexes and drop any indexes that are ready in
            // the index catalog. This would indicate that while we yielded our locks during the
            // abort phase, a new identical index was created.
            auto indexCatalog = collection->getWritableCollection(opCtx)->getIndexCatalog();
            const bool includeUnfinished = false;
            for (const auto& indexName : indexNames) {
                auto collDescription =
                    CollectionShardingState::get(opCtx, nss)->getCollectionDescription(opCtx);

                if (collDescription.isSharded()) {
                    uassert(ErrorCodes::CannotDropShardKeyIndex,
                            "Cannot drop the only compatible index for this collection's shard key",
                            !isLastShardKeyIndex(opCtx,
                                                 collection->getCollection(),
                                                 indexCatalog,
                                                 indexName,
                                                 collDescription.getKeyPattern()));
                }

                auto desc = indexCatalog->findIndexByName(opCtx, indexName, includeUnfinished);
                if (!desc) {
                    // A similar index wasn't created while we yielded the locks during abort.
                    continue;
                }

                uassertStatusOK(dropIndexByDescriptor(
                    opCtx, collection->getWritableCollection(opCtx), indexCatalog, desc));
            }

            wuow.commit();
        });

        return reply;
    }

    if (!abortedIndexBuilders.empty()) {
        // All the index builders were sent the abort signal, remove all the remaining indexes
        // in the index catalog.
        invariant(isWildcard);
        invariant(indexNames.size() == 1);
        invariant(indexNames.front() == "*");
        invariant((*collection)->getIndexCatalog()->numIndexesInProgress(opCtx) == 0);
    }

    // TODO(SERVER-61481): Remove this block once kLastLTS is 6.0. As of 5.2, dropping an index
    // while having a separate index build on the same collection is permitted.
    if (serverGlobalParams.featureCompatibility.isLessThan(
            multiversion::FeatureCompatibilityVersion::kVersion_5_2)) {
        // The index catalog requires that no active index builders are running when dropping ready
        // indexes.
        IndexBuildsCoordinator::get(opCtx)->assertNoIndexBuildInProgForCollection(collectionUUID);
    }

    writeConflictRetry(
        opCtx, "dropIndexes", dbAndUUID.toString(), [opCtx, &collection, &indexNames, &reply] {
            WriteUnitOfWork wunit(opCtx);

            // This is necessary to check shard version.
            OldClientContext ctx(opCtx, (*collection)->ns().ns());
            dropReadyIndexes(
                opCtx, collection->getWritableCollection(opCtx), indexNames, &reply, false);
            wunit.commit();
        });

    return reply;
}

Status dropIndexesForApplyOps(OperationContext* opCtx,
                              const NamespaceString& nss,
                              const BSONObj& cmdObj) try {
    BSONObjBuilder bob(cmdObj);
    bob.append("$db", nss.db());
    auto cmdObjWithDb = bob.obj();
    auto parsed = DropIndexes::parse({"dropIndexes"}, cmdObjWithDb);

    return writeConflictRetry(opCtx, "dropIndexes", nss.db(), [opCtx, &nss, &cmdObj, &parsed] {
        AutoGetCollection collection(opCtx, nss, MODE_X);

        // If db/collection does not exist, short circuit and return.
        Status status = checkView(opCtx, nss, collection.getCollection());
        if (!status.isOK()) {
            return status;
        }

        if (!serverGlobalParams.quiet.load()) {
            LOGV2(20344,
                  "CMD: dropIndexes",
                  "namespace"_attr = nss,
                  "indexes"_attr = cmdObj[kIndexFieldName].toString(false));
        }

        // TODO(SERVER-61481): Remove this block once kLastLTS is 6.0. As of 5.2, dropping an index
        // while having a separate index build on the same collection is permitted.
        if (serverGlobalParams.featureCompatibility.isLessThan(
                multiversion::FeatureCompatibilityVersion::kVersion_5_2)) {
            IndexBuildsCoordinator::get(opCtx)->assertNoIndexBuildInProgForCollection(
                collection->uuid());
        }

        auto swIndexNames = getIndexNames(opCtx, collection.getCollection(), parsed.getIndex());
        if (!swIndexNames.isOK()) {
            return swIndexNames.getStatus();
        }

        WriteUnitOfWork wunit(opCtx);

        // This is necessary to check shard version.
        OldClientContext ctx(opCtx, nss.ns());

        DropIndexesReply ignoredReply;
        dropReadyIndexes(opCtx,
                         collection.getWritableCollection(opCtx),
                         swIndexNames.getValue(),
                         &ignoredReply,
                         true);

        wunit.commit();
        return Status::OK();
    });
} catch (const DBException& exc) {
    return exc.toStatus();
}

}  // namespace mongo

ext: cpp

max_stars_repo_name: benety/mongo

max_issues_repo_name: benety/mongo

max_forks_repo_name: benety/mongo


text:
//
// Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail 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)
//
// Official repository: https://github.com/LeonineKing1199/foxy
//

#ifndef FOXY_UTILITY_HPP_
#define FOXY_UTILITY_HPP_

#include <boost/asio/ssl/context.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/ssl/error.hpp>

#include <boost/utility/string_view.hpp>

#include <boost/throw_exception.hpp>

#include <boost/system/error_code.hpp>

#include <openssl/x509_vfy.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#include <string>

namespace foxy
{
// this namespace is a port of the up-and-coming library Boost.Certify:
// https://github.com/djarek/certify/tree/b5d8b2ed67fd12437e8b2f104477b2d06c3d6803
//
// written by Damian Jarek, distributed under the Boost Software License found here in the source:
// https://github.com/djarek/certify/blob/b5d8b2ed67fd12437e8b2f104477b2d06c3d6803/LICENSE_1_0.txt
//
// without their tireless research, Foxy wouldn't be nearly as secure or useful as it is
//
namespace certify
{
extern "C" int
verify_server_certificates(::X509_STORE_CTX* ctx, void*) noexcept;

auto
enable_https_verification(boost::asio::ssl::context& ssl_ctx) -> void;

auto
set_server_hostname(::SSL*                     ssl,
                    boost::string_view         hostname,
                    unsigned int               flags,
                    boost::system::error_code& ec) -> void;

auto
set_server_hostname(::SSL* ssl, boost::string_view hostname, unsigned int flags = 0) -> void;

template <class AsyncSSLStream>
void
set_sni_hostname(AsyncSSLStream& stream, std::string const& hostname, boost::system::error_code& ec)
{
  if (!SSL_set_tlsext_host_name(stream.native_handle(), hostname.c_str())) {
    ec = {static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};
    return;
  }

  ec = {};
}

template <class AsyncSSLStream>
void
set_sni_hostname(AsyncSSLStream& stream, std::string const& hostname)
{
  auto ec = boost::system::error_code();

  if (!SSL_set_tlsext_host_name(stream.native_handle(), hostname.c_str())) {
    ec = {static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};
  } else {
    ec = {};
  }

  if (ec) { boost::throw_exception(boost::system::system_error(ec)); }
}
} // namespace certify

template <class... Args>
auto
make_ssl_ctx(Args&&... args) -> boost::asio::ssl::context
{
  auto ctx = boost::asio::ssl::context(std::forward<Args>(args)...);

  foxy::certify::enable_https_verification(ctx);
  ctx.set_verify_mode(boost::asio::ssl::context::verify_peer |
                      boost::asio::ssl::context::verify_fail_if_no_peer_cert);

  return ctx;
}

} // namespace foxy

#endif // FOXY_UTILITY_HPP_

max_stars_repo_name: Olipro/foxy

max_issues_repo_name: Olipro/foxy

max_forks_repo_name: Olipro/foxy


text:
#pragma once

#include "gazebo/physics/physics.hh"
#include "gazebo/transport/TransportTypes.hh"
#include "gazebo/msgs/MessageTypes.hh"

#include "gazebo/common/Time.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/common/Events.hh"

#include "gazebo/rendering/DynamicLines.hh"
#include "gazebo/rendering/RenderTypes.hh"
#include "gazebo/rendering/Visual.hh"
#include "gazebo/rendering/Scene.hh"

#include <ros/callback_queue.h>
#include <ros/advertise_options.h>
#include <ros/ros.h>

#include <geometry_msgs/Point.h>
// if you want some positions of the model use this....
#include <gazebo_msgs/ModelStates.h>

#include <boost/thread.hpp>
#include <boost/bind.hpp>

namespace gazebo
{
    namespace rendering
    {
        class DarkRoomVisualPlugin : public VisualPlugin
        {
        public:
            /// \brief Constructor
            DarkRoomVisualPlugin();

            /// \brief Destructor
            virtual ~DarkRoomVisualPlugin();

            /// \brief Load the visual force plugin tags
            /// \param node XML config node
            void Load( VisualPtr _parent, sdf::ElementPtr _sdf );

        protected:
            /// \brief Update the visual plugin
            virtual void UpdateChild();

        private:
            /// \brief pointer to ros node
            ros::NodeHandlePtr nh;

            /// \brief store model name
            std::string model_name_;

            /// \brief topic name
            std::string topic_name_;

            // /// \brief The visual pointer used to visualize the force.
            VisualPtr visual_;

            // /// \brief The scene pointer.
            ScenePtr scene_;

            /// \brief For example a line to visualize the force
            DynamicLines *line;

            /// \brief for setting ROS name space
            std::string visual_namespace_;

            /// \Subscribe to some force
            ros::Subscriber force_sub_;

            /// \brief Visualize the force
            void VisualizeForceOnLink(const geometry_msgs::PointConstPtr &force_ms);

            // Pointer to the update event connection
            event::ConnectionPtr update_connection_;
        };
    }
}


text:
#ifndef MPC_H_INCLUDED
#define MPC_H_INCLUDED

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <limits>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Dense>
#include "osqp.h"
#include "other/st_to_cc.hpp"

typedef Eigen::MatrixXd matXd;

class MPC {
 private:
  double dt, mass, mu, T_gait, h_ref;
  int n_steps, cpt_ML, cpt_P;

  Eigen::Matrix<double, 3, 3> gI;
  Eigen::Matrix<double, 6, 1> q;
  Eigen::Matrix<double, 6, 1> v = Eigen::Matrix<double, 6, 1>::Zero();
  Eigen::Matrix<double, 3, 4> footholds = Eigen::Matrix<double, 3, 4>::Zero();
  Eigen::Matrix<double, 1, 12> footholds_tmp = Eigen::Matrix<double, 12, 1>::Zero();
  Eigen::Matrix<double, 3, 4> lever_arms = Eigen::Matrix<double, 3, 4>::Zero();
  Eigen::Matrix<int, Eigen::Dynamic, 4> gait;
  Eigen::Matrix<int, Eigen::Dynamic, 4> inv_gait;
  Eigen::Matrix<double, 12, 1> g = Eigen::Matrix<double, 12, 1>::Zero();
  Eigen::Matrix<double, 3, 1> offset_CoM = Eigen::Matrix<double, 3, 1>::Zero();

  Eigen::Matrix<double, 12, 12> A = Eigen::Matrix<double, 12, 12>::Identity();
  Eigen::Matrix<double, 12, 12> B = Eigen::Matrix<double, 12, 12>::Zero();
  Eigen::Matrix<double, 12, 1> x0 = Eigen::Matrix<double, 12, 1>::Zero();
  double x_next[12] = {};
  Eigen::MatrixXd x_f_applied;

  // Matrix ML
  const static int size_nz_ML = 5000;
  // int r_ML [size_nz_ML] = {}; // row indexes of non-zero values in matrix ML
  // int c_ML [size_nz_ML] = {}; // col indexes of non-zero values in matrix ML
  // double v_ML [size_nz_ML] = {};  // non-zero values in matrix ML
  // csc* ML_triplet; // Compressed Sparse Column matrix (triplet format)
  csc *ML;  // Compressed Sparse Column matrix
  inline void add_to_ML(int i, int j, double v, int *r_ML, int *c_ML,
                        double *v_ML);                                            // function to fill the triplet r/c/v
  inline void add_to_P(int i, int j, double v, int *r_P, int *c_P, double *v_P);  // function to fill the triplet r/c/v

  // Indices that are used to udpate ML
  int i_x_B[12 * 4] = {};
  int i_y_B[12 * 4] = {};
  int i_update_B[12 * 4] = {};
  // TODO FOR S ????

  // Matrix NK
  const static int size_nz_NK = 5000;
  double v_NK_up[size_nz_NK] = {};   // maxtrix NK (upper bound)
  double v_NK_low[size_nz_NK] = {};  // maxtrix NK (lower bound)
  double v_warmxf[size_nz_NK] = {};  // maxtrix NK (lower bound)

  // Matrix P
  const static int size_nz_P = 5000;
  // c_int r_P [size_nz_P] = {}; // row indexes of non-zero values in matrix ML
  // c_int c_P [size_nz_P] = {}; // col indexes of non-zero values in matrix ML
  // c_float v_P [size_nz_P] = {};  // non-zero values in matrix ML
  csc *P;  // Compressed Sparse Column matrix

  // Matrix Q
  const static int size_nz_Q = 5000;
  double Q[size_nz_Q] = {};  // Q is full of zeros

  // OSQP solver variables
  OSQPWorkspace *workspce = new OSQPWorkspace();
  OSQPData *data;
  OSQPSettings *settings = (OSQPSettings *)c_malloc(sizeof(OSQPSettings));

  // Matrices whose size depends on the arguments sent to the constructor function
  Eigen::Matrix<double, 12, Eigen::Dynamic> xref;
  Eigen::Matrix<double, Eigen::Dynamic, 1> x;
  Eigen::Matrix<int, Eigen::Dynamic, 1> S_gait;
  Eigen::Matrix<double, Eigen::Dynamic, 1> warmxf;
  Eigen::Matrix<double, Eigen::Dynamic, 1> NK_up;
  Eigen::Matrix<double, Eigen::Dynamic, 1> NK_low;
  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> D;
  Eigen::Matrix<int, Eigen::Dynamic, 1> i_off;

 public:
  MPC();
  MPC(double dt_in, int n_steps_in, double T_gait_in, int N_gait);

  int create_matrices();
  int create_ML();
  int create_NK();
  int create_weight_matrices();
  int update_matrices(Eigen::MatrixXd fsteps);
  int update_ML(Eigen::MatrixXd fsteps);
  int update_NK();
  int call_solver(int);
  int retrieve_result();
  double *get_x_next();
  int run(int num_iter, const Eigen::MatrixXd &xref_in, const Eigen::MatrixXd &fsteps_in);

  Eigen::Matrix<double, 3, 3> getSkew(Eigen::Matrix<double, 3, 1> v);
  int construct_S();
  int construct_gait(Eigen::MatrixXd fsteps_in);

  // Getters
  Eigen::MatrixXd get_latest_result();
  Eigen::MatrixXd get_gait();
  Eigen::MatrixXd get_Sgait();

  // Utils
  double gethref() { return h_ref; }
  void my_print_csc_matrix(csc *M, const char *name);
  void save_csc_matrix(csc *M, std::string filename);
  void save_dns_matrix(double *M, int size, std::string filename);

  // Bindings
  void run_python(const matXd &xref_py, const matXd &fsteps_py);

  // Eigen::Matrix<double, 12, 12> getA() { return A; }
  // Eigen::MatrixXf getML() { return ML; }
  /*void setDate(int year, int month, int day);
  int getYear();
  int getMonth();
  int getDay();*/
};

#endif  // MPC_H_INCLUDED

max_stars_repo_name: paLeziart/quadruped-reactive-walking

max_issues_repo_name: paLeziart/quadruped-reactive-walking

max_forks_repo_name: paLeziart/quadruped-reactive-walking


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////

#include "State.h"
#include "Agent.h"

#include <velocypack/Buffer.h>
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>

#include <chrono>
#include <iomanip>
#include <sstream>
#include <thread>

#include "Aql/Query.h"
#include "Aql/QueryRegistry.h"
#include "Basics/StaticStrings.h"
#include "Basics/VelocyPackHelper.h"
#include "RestServer/QueryRegistryFeature.h"
#include "Utils/OperationOptions.h"
#include "Utils/OperationResult.h"
#include "Utils/SingleCollectionTransaction.h"
#include "Utils/StandaloneTransactionContext.h"
#include "VocBase/LogicalCollection.h"
#include "VocBase/vocbase.h"

#include <boost/uuid/uuid.hpp>             // uuid class
#include <boost/uuid/uuid_generators.hpp>  // generators
#include <boost/uuid/uuid_io.hpp>          // streaming operators etc.

using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::aql;
using namespace arangodb::consensus;
using namespace arangodb::velocypack;
using namespace arangodb::rest;

/// Construct with endpoint
State::State(std::string const& endpoint)
    : _agent(nullptr),
      _vocbase(nullptr),
      _endpoint(endpoint),
      _collectionsChecked(false),
      _collectionsLoaded(false),
      _queryRegistry(nullptr),
      _cur(0) {}

/// Default dtor
State::~State() {}

inline std::string stringify(arangodb::consensus::index_t index) {
  std::ostringstream i_str;
  i_str << std::setw(20) << std::setfill('0') << index;
  return i_str.str();
}

/// Persist one entry
bool State::persist(arangodb::consensus::index_t index, term_t term,
                    arangodb::velocypack::Slice const& entry) {
  Builder body;
  body.add(VPackValue(VPackValueType::Object));
  body.add("_key", Value(stringify(index)));
  body.add("term", Value(term));
  body.add("request", entry);
  body.close();

  TRI_ASSERT(_vocbase != nullptr);
  auto transactionContext =
      std::make_shared<StandaloneTransactionContext>(_vocbase);
  SingleCollectionTransaction trx(transactionContext, "log",
                                  TRI_TRANSACTION_WRITE);

  int res = trx.begin();
  if (res != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION(res);
  }
  OperationResult result;
  try {
    result = trx.insert("log", body.slice(), _options);
  } catch (std::exception const& e) {
    LOG_TOPIC(ERR, Logger::AGENCY) << "Failed to persist log entry:"
                                   << e.what();
  }
  res = trx.finish(result.code);

  return (res == TRI_ERROR_NO_ERROR);
}

/// Log transaction (leader)
std::vector<arangodb::consensus::index_t> State::log(
    query_t const& transaction, std::vector<bool> const& appl, term_t term) {
  std::vector<arangodb::consensus::index_t> idx(appl.size());
  std::vector<bool> good = appl;
  size_t j = 0;
  auto const& slice = transaction->slice();

  if (!slice.isArray()) {
    THROW_ARANGO_EXCEPTION_MESSAGE(30000,
                                   "Agency request syntax is [[<queries>]]");
  }

  if (slice.length() != good.size()) {
    THROW_ARANGO_EXCEPTION_MESSAGE(30000,
                                   "Agency request syntax is [[<queries>]]");
  }

  MUTEX_LOCKER(mutexLocker, _logLock);  // log entries must stay in order
  for (auto const& i : VPackArrayIterator(slice)) {
    TRI_ASSERT(i.isArray());
    if (good[j]) {
      std::shared_ptr<Buffer<uint8_t>> buf =
          std::make_shared<Buffer<uint8_t>>();
      buf->append((char const*)i[0].begin(), i[0].byteSize());
      idx[j] = _log.back().index + 1;
      _log.push_back(log_t(idx[j], term, buf));  // log to RAM
      persist(idx[j], term, i[0]);               // log to disk
      ++j;
    }
  }

  return idx;
}

/// Log transactions (follower)
arangodb::consensus::index_t State::log(query_t const& transactions,
                                        size_t ndups) {
  VPackSlice slices = transactions->slice();

  TRI_ASSERT(slices.isArray());

  size_t nqs = slices.length();

  TRI_ASSERT(nqs > ndups);

  MUTEX_LOCKER(mutexLocker, _logLock);  // log entries must stay in order

  for (size_t i = ndups; i < nqs; ++i) {
    VPackSlice slice = slices[i];

    try {
      auto idx = slice.get("index").getUInt();
      auto trm = slice.get("term").getUInt();
      auto buf = std::make_shared<Buffer<uint8_t>>();

      buf->append((char const*)slice.get("query").begin(),
                  slice.get("query").byteSize());
      // to RAM
      _log.push_back(log_t(idx, trm, buf));
      // to disk
      persist(idx, trm, slice.get("query"));
    } catch (std::exception const& e) {
      LOG_TOPIC(ERR, Logger::AGENCY) << e.what() << " " << __FILE__ << __LINE__;
    }
  }

  TRI_ASSERT(!_log.empty());
  return _log.back().index;
}

size_t State::removeConflicts(query_t const& transactions) {
  VPackSlice slices = transactions->slice();
  TRI_ASSERT(slices.isArray());
  size_t ndups = 0;

  if (slices.length() > 0) {
    auto bindVars = std::make_shared<VPackBuilder>();
    bindVars->openObject();
    bindVars->close();

    try {
      auto idx = slices[0].get("index").getUInt();
      auto pos = idx - _cur;

      if (pos < _log.size()) {
        for (auto const& slice : VPackArrayIterator(slices)) {
          auto trm = slice.get("term").getUInt();
          idx = slice.get("index").getUInt();
          pos = idx - _cur;

          if (pos < _log.size()) {
            if (idx == _log.at(pos).index && trm != _log.at(pos).term) {
              LOG_TOPIC(DEBUG, Logger::AGENCY)
                  << "Removing " << _log.size() - pos
                  << " entries from log starting with " << idx
                  << "==" << _log.at(pos).index << " and " << trm << "="
                  << _log.at(pos).term;

              // persisted logs
              std::string const aql(std::string("FOR l IN log FILTER l._key >= '") +
                                    stringify(idx) + "' REMOVE l IN log");

              arangodb::aql::Query query(
                false, _vocbase, aql.c_str(), aql.size(), bindVars, nullptr,
                arangodb::aql::PART_MAIN);

              auto queryResult = query.execute(_queryRegistry);

              if (queryResult.code != TRI_ERROR_NO_ERROR) {
                THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code,
                                               queryResult.details);
              }

              queryResult.result->slice();

              // volatile logs
              {
                MUTEX_LOCKER(mutexLocker, _logLock);
                _log.erase(_log.begin() + pos, _log.end());
              }

              break;

            } else {
              ++ndups;
            }
          }
        }
      }
    } catch (std::exception const& e) {
      LOG_TOPIC(DEBUG, Logger::AGENCY) << e.what() << " " << __FILE__
                                       << __LINE__;
    }
  }

  return ndups;
}

/// Get log entries from indices "start" to "end"
std::vector<log_t> State::get(arangodb::consensus::index_t start,
                              arangodb::consensus::index_t end) const {
  std::vector<log_t> entries;
  MUTEX_LOCKER(mutexLocker, _logLock);

  if (_log.empty()) {
    return entries;
  }

  if (end == (std::numeric_limits<uint64_t>::max)() || end > _log.size() - 1) {
    end = _log.size() - 1;
  }

  if (start < _log[0].index) {
    start = _log[0].index;
  }

  for (size_t i = start - _cur; i <= end; ++i) {
    entries.push_back(_log[i]);
  }

  return entries;
}

/// Get vector of past transaction from 'start' to 'end'
std::vector<VPackSlice> State::slices(arangodb::consensus::index_t start,
                                      arangodb::consensus::index_t end) const {
  std::vector<VPackSlice> slices;
  MUTEX_LOCKER(mutexLocker, _logLock);

  if (_log.empty()) {
    return slices;
  }

  if (start < _log.front().index) {  // no start specified
    start = _log.front().index;
  }

  if (start > _log.back().index) {  // no end specified
    return slices;
  }

  if (end == (std::numeric_limits<uint64_t>::max)() ||
      end > _log.back().index) {
    end = _log.back().index;
  }

  for (size_t i = start - _cur; i <= end - _cur; ++i) {
    try {
      slices.push_back(VPackSlice(_log.at(i).entry->data()));
    } catch (std::exception const&) {
      break;
    }
  }

  return slices;
}

/// Get log entry by log index
log_t const& State::operator[](arangodb::consensus::index_t index) const {
  MUTEX_LOCKER(mutexLocker, _logLock);
  TRI_ASSERT(index - _cur < _log.size());
  return _log.at(index - _cur);
}

/// Get last log entry
log_t const& State::lastLog() const {
  MUTEX_LOCKER(mutexLocker, _logLock);
  TRI_ASSERT(!_log.empty());
  return _log.back();
}

/// Configure with agent
bool State::configure(Agent* agent) {
  _agent = agent;
  _endpoint = agent->endpoint();
  _collectionsChecked = false;
  return true;
}

/// Check if collections exist otherwise create them
bool State::checkCollections() {
  if (!_collectionsChecked) {
    _collectionsChecked = checkCollection("log") && checkCollection("election");
  }
  return _collectionsChecked;
}

/// Create agency collections
bool State::createCollections() {
  if (!_collectionsChecked) {
    return (createCollection("log") && createCollection("election") &&
            createCollection("compact"));
  }
  return _collectionsChecked;
}

/// Check collection by name
bool State::checkCollection(std::string const& name) {
  if (!_collectionsChecked) {
    return (_vocbase->lookupCollection(name) != nullptr);
  }
  return true;
}

/// Create collection by name
bool State::createCollection(std::string const& name) {
  Builder body;
  body.add(VPackValue(VPackValueType::Object));
  body.add("type", VPackValue(static_cast<int>(TRI_COL_TYPE_DOCUMENT)));
  body.add("name", VPackValue(name));
  body.add("isSystem", VPackValue(LogicalCollection::IsSystemName(name)));
  body.close();

  TRI_voc_cid_t cid = 0;
  arangodb::LogicalCollection const* collection =
      _vocbase->createCollection(body.slice(), cid, true);

  if (collection == nullptr) {
    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_errno(), "cannot create collection");
  }

  return true;
}

template <class T>
std::ostream& operator<<(std::ostream& o, std::deque<T> const& d) {
  for (auto const& i : d) {
    o << i;
  }
  return o;
}

/// Load collections
bool State::loadCollections(TRI_vocbase_t* vocbase,
                            QueryRegistry* queryRegistry, bool waitForSync) {
  _vocbase = vocbase;
  _queryRegistry = queryRegistry;

  TRI_ASSERT(_vocbase != nullptr);

  _options.waitForSync = waitForSync;
  _options.silent = true;

  if (loadPersisted()) {
    if (_log.empty()) {
      std::shared_ptr<Buffer<uint8_t>> buf =
          std::make_shared<Buffer<uint8_t>>();
      VPackSlice value = arangodb::basics::VelocyPackHelper::EmptyObjectValue();
      buf->append(value.startAs<char const>(), value.byteSize());
      _log.push_back(log_t(arangodb::consensus::index_t(0), term_t(0), buf));
      persist(0, 0, value);
    }
    return true;
  }

  return false;
}

/// Load actually persisted collections
bool State::loadPersisted() {
  TRI_ASSERT(_vocbase != nullptr);

  if (!checkCollection("configuration")) {
    createCollection("configuration");
  }

  loadOrPersistConfiguration();

  if (checkCollection("log") && checkCollection("compact")) {
    return (loadCompacted() && loadRemaining());
  }

  LOG_TOPIC(DEBUG, Logger::AGENCY) << "Couldn't find persisted log";
  createCollections();

  return true;
}

/// Load compaction collection
bool State::loadCompacted() {
  auto bindVars = std::make_shared<VPackBuilder>();
  bindVars->openObject();
  bindVars->close();

  std::string const aql(
      std::string("FOR c IN compact SORT c._key DESC LIMIT 1 RETURN c"));

  arangodb::aql::Query query(false, _vocbase, aql.c_str(), aql.size(), bindVars,
                             nullptr, arangodb::aql::PART_MAIN);

  auto queryResult = query.execute(QueryRegistryFeature::QUERY_REGISTRY);

  if (queryResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
  }

  VPackSlice result = queryResult.result->slice();

  if (result.isArray() && result.length()) {
    for (auto const& i : VPackArrayIterator(result)) {
      buffer_t tmp = std::make_shared<arangodb::velocypack::Buffer<uint8_t>>();
      (*_agent) = i;
      try {
        _cur = std::stoul(i.get("_key").copyString());
      } catch (std::exception const& e) {
        LOG_TOPIC(ERR, Logger::AGENCY) << e.what() << " " << __FILE__
                                       << __LINE__;
      }
    }
  }

  return true;
}

/// Load persisted configuration
bool State::loadOrPersistConfiguration() {
  auto bindVars = std::make_shared<VPackBuilder>();
  bindVars->openObject();
  bindVars->close();

  std::string const aql(
      std::string("FOR c in configuration FILTER c._key==\"0\" RETURN c.cfg"));

  arangodb::aql::Query query(false, _vocbase, aql.c_str(), aql.size(), bindVars,
                             nullptr, arangodb::aql::PART_MAIN);

  auto queryResult = query.execute(QueryRegistryFeature::QUERY_REGISTRY);

  if (queryResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
  }

  VPackSlice result = queryResult.result->slice();

  if (result.isArray() &&
      result.length()) {  // We already have a persisted conf

    try {
      LOG_TOPIC(DEBUG, Logger::AGENCY) << "Merging configuration " << result[0].toJson();
      _agent->mergeConfiguration(result[0]);
    } catch (std::exception const& e) {
      LOG_TOPIC(ERR, Logger::AGENCY)
          << "Failed to merge persisted configuration into runtime "
             "configuration: "
          << e.what();
      FATAL_ERROR_EXIT();
    }

  } else {  // Fresh start

    LOG_TOPIC(DEBUG, Logger::AGENCY) << "New agency!";

    TRI_ASSERT(_agent != nullptr);
    _agent->id(to_string(boost::uuids::random_generator()()));

    auto transactionContext =
        std::make_shared<StandaloneTransactionContext>(_vocbase);
    SingleCollectionTransaction trx(transactionContext, "configuration",
                                    TRI_TRANSACTION_WRITE);

    int res = trx.begin();
    OperationResult result;

    if (res != TRI_ERROR_NO_ERROR) {
      THROW_ARANGO_EXCEPTION(res);
    }

    Builder doc;
    doc.openObject();
    doc.add("_key", VPackValue("0"));
    doc.add("cfg", _agent->config().toBuilder()->slice());
    doc.close();
    try {
      result = trx.insert("configuration", doc.slice(), _options);
    } catch (std::exception const& e) {
      LOG_TOPIC(ERR, Logger::AGENCY) << "Failed to persist configuration entry:"
                                     << e.what();
      FATAL_ERROR_EXIT();
    }

    res = trx.finish(result.code);

    return (res == TRI_ERROR_NO_ERROR);
  }

  return true;
}

/// Load beyond last compaction
bool State::loadRemaining() {
  auto bindVars = std::make_shared<VPackBuilder>();
  bindVars->openObject();
  bindVars->close();

  std::string const aql(std::string("FOR l IN log SORT l._key RETURN l"));
  arangodb::aql::Query query(false, _vocbase, aql.c_str(), aql.size(), bindVars,
                             nullptr, arangodb::aql::PART_MAIN);

  auto queryResult = query.execute(QueryRegistryFeature::QUERY_REGISTRY);

  if (queryResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
  }

  auto result = queryResult.result->slice();

  if (result.isArray()) {
    _log.clear();
    for (auto const& i : VPackArrayIterator(result)) {
      buffer_t tmp = std::make_shared<arangodb::velocypack::Buffer<uint8_t>>();
      auto req = i.get("request");
      tmp->append(req.startAs<char const>(), req.byteSize());
      try {
        _log.push_back(
            log_t(std::stoi(i.get(StaticStrings::KeyString).copyString()),
                  static_cast<term_t>(i.get("term").getUInt()), tmp));
      } catch (std::exception const& e) {
        LOG_TOPIC(ERR, Logger::AGENCY)
            << "Failed to convert " +
                   i.get(StaticStrings::KeyString).copyString() +
                   " to integer via std::stoi."
            << e.what();
      }
    }
  }

  _agent->rebuildDBs();
  _agent->lastCommitted(_log.back().index);

  return true;
}

/// Find entry by index and term
bool State::find(arangodb::consensus::index_t prevIndex, term_t prevTerm) {
  MUTEX_LOCKER(mutexLocker, _logLock);
  if (prevIndex > _log.size()) {
    return false;
  }
  return _log.at(prevIndex).term == prevTerm;
}

/// Log compaction
bool State::compact(arangodb::consensus::index_t cind) {
  bool saved = persistReadDB(cind);

  if (saved) {
    compactVolatile(cind);

    try {
      compactPersisted(cind);
      removeObsolete(cind);
    } catch (std::exception const& e) {
      LOG_TOPIC(ERR, Logger::AGENCY) << "Failed to compact persisted store.";
      LOG_TOPIC(ERR, Logger::AGENCY) << e.what();
    }
    return true;
  } else {
    return false;
  }
}

/// Compact volatile state
bool State::compactVolatile(arangodb::consensus::index_t cind) {
  if (!_log.empty() && cind > _cur && cind - _cur < _log.size()) {
    MUTEX_LOCKER(mutexLocker, _logLock);
    _log.erase(_log.begin(), _log.begin() + (cind - _cur));
    _cur = _log.begin()->index;
  }
  return true;
}

/// Compact persisted state
bool State::compactPersisted(arangodb::consensus::index_t cind) {
  auto bindVars = std::make_shared<VPackBuilder>();
  bindVars->openObject();
  bindVars->close();

  std::stringstream i_str;
  i_str << std::setw(20) << std::setfill('0') << cind;

  std::string const aql(std::string("FOR l IN log FILTER l._key < \"") +
                        i_str.str() + "\" REMOVE l IN log");

  arangodb::aql::Query query(false, _vocbase, aql.c_str(), aql.size(), bindVars,
                             nullptr, arangodb::aql::PART_MAIN);

  auto queryResult = query.execute(QueryRegistryFeature::QUERY_REGISTRY);

  if (queryResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
  }

  if (queryResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
  }

  return true;
}

/// Remove outdate compactions
bool State::removeObsolete(arangodb::consensus::index_t cind) {
  if (cind > 3 * _agent->config().compactionStepSize()) {
    auto bindVars = std::make_shared<VPackBuilder>();
    bindVars->openObject();
    bindVars->close();

    std::stringstream i_str;
    i_str << std::setw(20) << std::setfill('0')
          << -3 * _agent->config().compactionStepSize() + cind;

    std::string const aql(std::string("FOR c IN compact FILTER c._key < \"") +
                          i_str.str() + "\" REMOVE c IN compact");

    arangodb::aql::Query query(false, _vocbase, aql.c_str(), aql.size(),
                               bindVars, nullptr, arangodb::aql::PART_MAIN);

    auto queryResult = query.execute(QueryRegistryFeature::QUERY_REGISTRY);
    if (queryResult.code != TRI_ERROR_NO_ERROR) {
      THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
    }
  }
  return true;
}

/// Persist the globally commited truth
bool State::persistReadDB(arangodb::consensus::index_t cind) {
  if (checkCollection("compact")) {
    Builder store;
    store.openObject();
    store.add("readDB", VPackValue(VPackValueType::Array));
    _agent->readDB().dumpToBuilder(store);
    store.close();
    std::stringstream i_str;
    i_str << std::setw(20) << std::setfill('0') << cind;
    store.add("_key", VPackValue(i_str.str()));
    store.close();

    TRI_ASSERT(_vocbase != nullptr);
    auto transactionContext =
        std::make_shared<StandaloneTransactionContext>(_vocbase);
    SingleCollectionTransaction trx(transactionContext, "compact",
                                    TRI_TRANSACTION_WRITE);

    int res = trx.begin();

    if (res != TRI_ERROR_NO_ERROR) {
      THROW_ARANGO_EXCEPTION(res);
    }

    auto result = trx.insert("compact", store.slice(), _options);
    res = trx.finish(result.code);

    return (res == TRI_ERROR_NO_ERROR);
  }

  LOG_TOPIC(ERR, Logger::AGENCY) << "Failed to persist read DB for compaction!";
  return false;
}

bool State::persistActiveAgents(query_t const& active, query_t const& pool) {
  auto bindVars = std::make_shared<VPackBuilder>();
  bindVars->openObject();
  bindVars->close();

  std::stringstream aql;
  aql << "FOR c IN configuration UPDATE {_key:c._key} WITH {cfg:{active:";
  aql << active->slice().toJson();
  aql << ", pool:";
  aql << pool->slice().toJson();
  aql << "}} IN configuration";
  std::string aqlStr = aql.str();

  arangodb::aql::Query query(false, _vocbase, aqlStr.c_str(), aqlStr.size(),
                             bindVars, nullptr, arangodb::aql::PART_MAIN);

  auto queryResult = query.execute(QueryRegistryFeature::QUERY_REGISTRY);
  if (queryResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
  }

  return true;
}

query_t State::allLogs() const {
  MUTEX_LOCKER(mutexLocker, _logLock);

  auto bindVars = std::make_shared<VPackBuilder>();
  bindVars->openObject();
  bindVars->close();

  std::string const comp("FOR c IN compact SORT c._key RETURN c");
  std::string const logs("FOR l IN log SORT l._key RETURN l");

  arangodb::aql::Query compq(false, _vocbase, comp.c_str(), comp.size(),
                             bindVars, nullptr, arangodb::aql::PART_MAIN);
  arangodb::aql::Query logsq(false, _vocbase, logs.c_str(), logs.size(),
                             bindVars, nullptr, arangodb::aql::PART_MAIN);

  auto compqResult = compq.execute(QueryRegistryFeature::QUERY_REGISTRY);
  if (compqResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(compqResult.code, compqResult.details);
  }
  auto logsqResult = logsq.execute(QueryRegistryFeature::QUERY_REGISTRY);
  if (logsqResult.code != TRI_ERROR_NO_ERROR) {
    THROW_ARANGO_EXCEPTION_MESSAGE(logsqResult.code, logsqResult.details);
  }

  auto everything = std::make_shared<VPackBuilder>();

  everything->openObject();

  try {
    everything->add("compact", compqResult.result->slice());
  } catch (std::exception const&) {
    LOG_TOPIC(ERR, Logger::AGENCY)
      << "Failed to assemble compaction part of everything package";
  }

  try{
    everything->add("logs", logsqResult.result->slice());
  } catch (std::exception const&) {
    LOG_TOPIC(ERR, Logger::AGENCY)
      << "Failed to assemble remaining part of everything package";
  }

  everything->close();

  return everything;

}

max_stars_repo_name: mikestaub/arangodb

max_issues_repo_name: mikestaub/arangodb

max_forks_repo_name: mikestaub/arangodb


text: #include <boost/math/special_functions/laguerre.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// -*- C++ -*-
#include <boost/test/included/unit_test.hpp>
#include <ContextHandleManager.h>

BOOST_AUTO_TEST_SUITE (ContextHandleManagerTestSuite) // name of the test suite is ContextHandleManagerTestSuite

BOOST_AUTO_TEST_CASE ( testCDtor )
{
  ContextHandleManager *tc = 0;
  try {
      tc = new ContextHandleManager;
      BOOST_CHECK (tc != 0);
      if (tc != 0)
      {
          try {
              delete tc;
          }
          catch (...)
          {
              BOOST_ERROR ( "Exception in deleting ARchiveHandleManager object" );
          }
      }
  } catch (...) {
      BOOST_ERROR ( "Exception in creating ARchiveHandleManager object" );
  }
}

BOOST_AUTO_TEST_SUITE_END( )

ext: tcc

max_stars_repo_name: nyue/ribclients

max_issues_repo_name: nyue/ribclients

max_forks_repo_name: nyue/ribclients


text:
// HardCoded.cpp
//
// C++ code to price an option, essential algorithms.
//
// We take CEV model with a choice of the elaticity parameter
// and the Euler method. We give option price and number of times
// S hits the origin.
//
// (C) Datasim Education BC 2008-2011
//

#ifndef _SCL_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#endif

#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif

#include "OptionData.hpp"
#include "StandardDeviation_StandardError.hpp"
#include "UtilitiesDJD/RNG/NormalGenerator.hpp"
#include "UtilitiesDJD/Geometry/Range.cpp"
#include <boost/tuple/tuple.hpp> // include tuple class
#include <boost/tuple/tuple_io.hpp> // include I/O for tuple
#include <vector>
#include <cmath>
#include <iostream>

template <class T> void print(const std::vector<T>& myList)
{  // A generic print function for vectors

	std::cout << std::endl << "Size of vector is " << l.size() << "\n[";

	// We must use a const iterator here, otherwise we get a compiler error.
	std::vector<T>::const_iterator i;
	for (i = myList.begin(); i != myList.end(); ++i)
	{
			std::cout << *i << ",";

	}

	std::cout << "]\n";
}

namespace SDEDefinition
{ // Defines drift + diffusion + data

	OptionData* data;				// The data for the option MC

	double drift(double t, double X)
	{ // Drift term

		return (data->r)*X; // r - D
	}

	double diffusion(double t, double X)
	{ // Diffusion term

		double betaCEV = 1.0;
		return data->sig * pow(X, betaCEV);

	}

	double diffusionDerivative(double t, double X)
	{ // Diffusion term, needed for the Milstein method

		double betaCEV = 1.0;
		return 0.5 * (data->sig) * (betaCEV) * pow(X, 2.0 * betaCEV - 1.0);
	}
} // End of namespace

int main()
{
	std::cout <<  "1 factor MC with explicit Euler\n";

	/*==========================MODIFIED================================*/
	vector<double> price_vec; // create a vector to store prices for each simulation
	/*================================================================*/

	// Batch 1 data
	OptionData myOption;
	myOption.K = 65.0;
	myOption.T = 0.25;
	myOption.r = 0.08;
	myOption.sig = 0.3;
	myOption.type = -1;	// Put -1, Call +1
	double S_0 = 60.0;

	//// Batch 2 data
	//OptionData myOption;
	//myOption.K = 100.0;
	//myOption.T = 1.0;
	//myOption.r = 0.0;
	//myOption.sig = 0.2;
	//myOption.type = -1;	// Put -1, Call +1
	//double S_0 = 100.0;

	//// Batch 4 data
	//OptionData myOption;
	//myOption.K = 100.0;
	//myOption.T = 30.0;
	//myOption.r = 0.08;
	//myOption.sig = 0.30;
	//myOption.type = 1;	// Put -1, Call +1
	//double S_0 = 100.0;

	long N = 100;
	std::cout << "Number of subintervals in time: ";
	std::cin >> N;

	// Create the basic SDE (Context class)
	Range<double> range (0.0, myOption.T);
	double VOld = S_0;
	double VNew;

	std::vector<double> x = range.mesh(N);

	// V2 mediator stuff
	long NSim = 50000;
	std::cout << "Number of simulations: ";
	std::cin >> NSim;

	double k = myOption.T / double (N);
	double sqrk = sqrt(k);

	// Normal random number
	double dW;
	double price = 0.0;	// Option price

	// NormalGenerator is a base class
	NormalGenerator* myNormal = new BoostNormal();

	using namespace SDEDefinition;
	SDEDefinition::data = &myOption;

	std::vector<double> res;
	int coun = 0; // Number of times S hits origin

	// A.
	for (long i = 1; i <= NSim; ++i)
	{ // Calculate a path at each iteration

		if ((i/10000) * 10000 == i)
		{// Give status after each 10000th iteration

				std::cout << i << std::endl;
		}

		VOld = S_0;
		for (unsigned long index = 1; index < x.size(); ++index)
		{

			// Create a random number
			dW = myNormal->getNormal();

			// The FDM (in this case explicit Euler)
			VNew = VOld  + (k * drift(x[index-1], VOld))
						+ (sqrk * diffusion(x[index-1], VOld) * dW);

			VOld = VNew;

			// Spurious values
			if (VNew <= 0.0) coun++;
		}

		double tmp = myOption.myPayOffFunction(VNew);
		/*==========================MODIFIED================================*/
		price_vec.push_back(tmp); // add each simulation price to the price vector
	    /*================================================================*/
		price += (tmp)/double(NSim);
	}

	// D. Finally, discounting the average price
	price *= exp(-myOption.r * myOption.T);

	// Cleanup; V2 use scoped pointer
	delete myNormal;

	std::cout << "Price, after discounting: " << price << ", " << std::endl;
	std::cout << "Number of times origin is hit: " << coun << endl;

	/*==========================MODIFIED================================*/
	// show the standard deviation and standard error
	boost::tuple<double, double> SD_SE = get_SD_SE(price_vec, myOption.r, myOption.T);

	cout << "SD = " << get<0>(SD_SE) << ", SE = " << get<1>(SD_SE) << endl;
	/*================================================================*/
	system("Pause");

	return 0;
}

max_stars_repo_path: Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/TestMC.cpp

max_stars_repo_name: bondxue/Option-Pricing-Model

max_issues_repo_name: bondxue/Option-Pricing-Model

max_forks_repo_name: bondxue/Option-Pricing-Model


text:
#ifndef CANARD_NET_OFP_V13_SET_FIELD_DECODER_HPP
#define CANARD_NET_OFP_V13_SET_FIELD_DECODER_HPP

#include <cstdint>
#include <tuple>
#include <boost/preprocessor/repeat.hpp>
#include <canard/net/ofp/detail/decode.hpp>
#include <canard/net/ofp/v13/action/set_field.hpp>
#include <canard/net/ofp/v13/common/oxm_header.hpp>
#include <canard/net/ofp/v13/detail/byteorder.hpp>
#include <canard/net/ofp/v13/detail/length_utility.hpp>
#include <canard/net/ofp/v13/exception.hpp>
#include <canard/net/ofp/v13/openflow.hpp>

namespace canard {
namespace net {
namespace ofp {
namespace v13 {

  struct set_field_decoder
  {
    using header_type = protocol::ofp_action_set_field;
    using type_id = std::uint32_t;
    using decode_type_list = default_set_field_list;
    static constexpr std::uint16_t header_size = sizeof(header_type);

    static_assert(
          std::tuple_size<default_set_field_list>::value == 36
        , "not match to the number of set_field types");

    template <class ReturnType, class Iterator, class Function>
    static auto decode(Iterator& first, Iterator last, Function function)
      -> ReturnType
    {
      auto const set_field
        = detail::decode_without_consumption<header_type>(first, last);

      auto const oxm_header = v13::oxm_header::decode_without_consumption(
          set_field.field, set_field.field + sizeof(set_field.field));

      if (set_field.len != detail::v13::exact_length(
            header_size + oxm_header.oxm_length())) {
        throw exception{
          protocol::bad_action_code::bad_set_len, "invalid set_field length"
        } << CANARD_NET_OFP_ERROR_INFO();
      }

      switch (oxm_header.oxm_type()) {

#     define CANARD_NET_OFP_V13_SET_FIELD_CASE(z, N, _) \
      using set_field ## N = \
            std::tuple_element<N, default_set_field_list>::type; \
      case set_field ## N::oxm_type(): \
        if (!set_field ## N::oxm_match_field \
            ::is_valid_oxm_match_field_length(oxm_header)) { \
          throw exception{ \
              protocol::bad_action_code::bad_set_len \
            , "invalid set_field's oxm_match_field length" \
          } << CANARD_NET_OFP_ERROR_INFO(); \
        } \
        return function(set_field ## N::decode(first, last));

      BOOST_PP_REPEAT(36, CANARD_NET_OFP_V13_SET_FIELD_CASE, _)

#     undef CANARD_NET_OFP_V13_SET_FIELD_CASE

      default:
        throw exception{
            protocol::bad_action_code::bad_set_type
          , "unknwon set_field's oxm_match_field type"
        } << CANARD_NET_OFP_ERROR_INFO();
      }
    }

    template <class ReturnType, class Iterator, class Function>
    static auto decode_without_consumption(
        Iterator first, Iterator last, Function function)
      -> ReturnType
    {
      return decode<ReturnType>(first, last, function);
    }
  };

} // namespace v13
} // namespace ofp
} // namespace net
} // namespace canard

#endif // CANARD_NET_OFP_V13_SET_FIELD_DECODER_HPP


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_DetailedWHIncoherentPhotonScatteringDistribution.hpp
//! \author Alex Robinson
//! \brief  The detailed Waller-Hartree incoherent photon scat. dist. decl.
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_DETAILED_WH_INCOHERENT_PHOTON_SCATTERING_DISTRIBUTION_HPP
#define MONTE_CARLO_DETAILED_WH_INCOHERENT_PHOTON_SCATTERING_DISTRIBUTION_HPP

// Boost Includes
#include <boost/scoped_ptr.hpp>

// Trilinos Includes
#include <Teuchos_Array.hpp>

// FRENSIE Includes
#include "MonteCarlo_WHIncoherentPhotonScatteringDistribution.hpp"

namespace MonteCarlo{

/*! The detailed Waller-Hartree incoherent photon scattering distribution class
 * \details This class will sample an interaction subshell for atomic
 * relaxation eventhough the Waller-Hartree model doesn't directly provide
 * that information. The subshell occupancies are used instead of the
 * more accurate subshell incoherent cross sections.
 */
class DetailedWHIncoherentPhotonScatteringDistribution : public WHIncoherentPhotonScatteringDistribution
{

public:

  //! Constructor
  DetailedWHIncoherentPhotonScatteringDistribution(
      const Teuchos::RCP<const Utility::OneDDistribution>& scattering_function,
      const Teuchos::Array<double>& subshell_occupancies,
      const Teuchos::Array<SubshellType>& subshell_order,
      const double kahn_sampling_cutoff_energy = 3.0 );

  //! Destructor
  ~DetailedWHIncoherentPhotonScatteringDistribution()
  { /* ... */ }

  //! Randomly scatter the photon and return the shell that was interacted with
  void scatterPhoton( PhotonState& photon,
		      ParticleBank& bank,
		      SubshellType& shell_of_interaction ) const;

private:

  //! Sample the subshell that is interacted with
  void sampleInteractionSubshell( SubshellType& shell_of_interaction ) const;

  // The shell interaction probabilities
  boost::scoped_ptr<const Utility::TabularOneDDistribution>
  d_subshell_occupancy_distribution;

  // The subshell ordering
  Teuchos::Array<SubshellType> d_subshell_order;
};

} // end MonteCarlo namespace

#endif // end MONTE_CARLO_DETAILED_WH_INCOHERENT_PHOTON_SCATTERING_DISTRIBUTION_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_DetailedWHIncoherentPhotonScatteringDistribution.hpp
//---------------------------------------------------------------------------//


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

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_ERFCX_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_ERFCX_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>

#include <boost/simd/meta/hierarchy/simd.hpp>
#include <boost/simd/arch/common/detail/generic/erf_kernel.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/abs.hpp>
#include <boost/simd/function/erfc.hpp>
#include <boost/simd/function/exp.hpp>
#include <boost/simd/function/is_inf.hpp>
#include <boost/simd/function/is_less.hpp>
#include <boost/simd/function/is_ltz.hpp>
#include <boost/simd/function/logical_andnot.hpp>
#include <boost/simd/function/nbtrue.hpp>
#include <boost/simd/function/oneminus.hpp>
#include <boost/simd/function/inc.hpp>
#include <boost/simd/function/sign.hpp>
#include <boost/simd/function/sqr.hpp>
#include <boost/config.hpp>
#include <cmath>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  namespace bs = boost::simd;

  BOOST_DISPATCH_OVERLOAD_IF ( erfcx_
                          , (typename A0, typename X)
                          , (detail::is_native<X>)
                          , bd::cpu_
                          , bs::pack_< bd::double_<A0>, X>
                          )
  {
   A0 operator() (const A0& x) const BOOST_NOEXCEPT
    {
      A0 y =  bs::abs(x);
      A0 lim1 = Ratio<A0, 15, 32>();
      A0 lim2 = A0(4);
      A0 res1(0), res2(0);
      auto test1 = (y <=lim1);
      std::size_t nb = bs::nbtrue(test1);
      if(nb > 0)
      {
        A0 ysq;
        A0 tmp = detail::erf_kernel1<A0>::erf1(x, y, ysq);
        res1 = oneminus(tmp)*exp(ysq);
        if (nb >= A0::static_size)
          return res1;
      }
      auto test2 = bs::is_less(x, lim2);
      auto test3 = bs::logical_andnot(test2, test1);
      std::size_t nb1 = bs::nbtrue(test3);
      if(nb1 > 0)
      {
        res2  = detail::erf_kernel1<A0>::erf2(x, y);
        A0 resb = res2;
        detail::erf_kernel1<A0>::finalize3(resb, x);
        res2 = if_else(is_ltz(x), resb, res2);
        nb += nb1;
        res2 = bs::if_else(test1, res1, res2);
        if (nb >= A0::static_size)
          return res2;
      }
      else
      {
        res2 =  res1;
      }
      auto test4 = logical_not(logical_or(test1, test2));
      A0 res3 = detail::erf_kernel1<A0>::erf3(x, y);
      A0 res3b = res3;
      detail::erf_kernel1<A0>::finalize3(res3b, x);
      res3 =  if_else (is_ltz(x), res3b, res3);
      return if_nan_else(is_nan(x), if_else(test4, res3, res2));
    }
  };

  BOOST_DISPATCH_OVERLOAD_IF ( erfcx_
                          , (typename A0, typename X)
                          , (detail::is_native<X>)
                          , bd::cpu_
                          , bs::pack_< bd::single_<A0>, X>
                          )
  {
    A0 operator() (const A0& a0) const BOOST_NOEXCEPT
    {

      auto test1 = bs::is_less(a0,  Ratio<A0, 2, 3>());
      std::size_t nb = bs::nbtrue(test1);
      A0 r2 = Zero<A0>(), r1 = Zero<A0>();
      if(nb > 0)
      {
        r1 = expx2(a0)*erfc(a0);
      }
      if(nb < A0::static_size)
      {
        A0 z =  a0/inc(a0) - Ratio<A0, 2, 5>();
        r2 = detail::erf_kernel<A0>::erfc2(z);
        r2 = if_else(is_ltz(r2), bs::rsqrt(bs::Pi<A0>())/a0, r2);
#ifndef BOOST_SIMD_NO_INFINITIES
        r2 = if_else(is_nan(a0), a0, if_zero_else(a0 == Inf<A0>(), r2));
#endif
      }
      return if_else(test1, r1, r2);
    }

  };

} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include <alglib/graph/models/adj_list.h>
#include <alglib/graph/edge.h>
#include <iostream>

using namespace std;
using namespace alglib::graph;
using namespace alglib::graph::models;

int main() {

    adj_list<string, edge_t<string, int>> al;

    string c1 = "deharadun",
           c2 = "rishikesh",
           c3 = "kulu manali",
           c4 = "haridwar";

    edge_t<string, int> e1(c1, c2, 100);
    edge_t<string, int> e2(c3, c4, 200);

    al.add_vertex(c1);
    al.add_vertex(c2);
    al.add_vertex(c3);
    al.add_edge(e1);
    al.add_edge(e2);

    cout << "All the vertices: ";
    for(auto it = al.vbegin(); it != al.vend(); it++)
        cout << *it << "\t";

    cout << endl;

    cout << "Vertices adjacent to kulu manali: ";
    for(auto it = al.avbegin(c3); it != al.avend(c3); it++)
        cout << *it << "\t";
    cout << endl;

    cout << "All the edges: ";
    for(auto it = al.ebegin(); it != al.eend(); ++it)
        cout << *it << "\t";

    cout << endl;

}

max_stars_repo_name: divkakwani/alglib

max_issues_repo_name: divkakwani/alglib

max_forks_repo_name: divkakwani/alglib


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

/** mldb_collection_delete_test.cc
    Jeremy Barnes, 13 December 2014
    Copyright (c) 2014 mldb.ai inc.  All rights reserved.

*/

#include "mldb/server/mldb_server.h"
#include "mldb/engine/plugin_collection.h"
#include "mldb/http/http_rest_proxy.h"
#include "mldb/builtin/plugin_resource.h"
#include "mldb/types/value_description.h"
#include <thread>
#include <chrono>

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>

using namespace std;

using namespace MLDB;

BOOST_AUTO_TEST_CASE( test_plugin_delete_while_loading )
{
    MldbServer server;

    server.init();

    string httpBoundAddress = server.bindTcp(PortRange(17000,18000), "127.0.0.1");

    cerr << "http listening on " << httpBoundAddress << endl;

    server.start();

    HttpRestProxy proxy(httpBoundAddress);

    // 1.  Add the JS script runner

    {
        PluginResource res;
        res.source.main = "'hello'";

        PolyConfig pluginConfig;
        pluginConfig.type = "javascript";
        pluginConfig.params = res;

        cerr << proxy.put("/v1/plugins/jsplugin", jsonEncode(pluginConfig));
    }

    auto res = proxy.perform("DELETE", "/v1/plugins/jsplugin");
    cerr << res << endl;
    BOOST_CHECK_EQUAL(res.code(), 204);

    cerr << proxy.get("/v1/plugins/jsplugin");

    BOOST_CHECK_EQUAL(proxy.get("/v1/plugins").jsonBody(),
                      Json::Value({}));

    server.shutdown();
}

ext: cc

max_stars_repo_name: kstepanmpmg/mldb

max_issues_repo_name: tomzhang/mldb

max_forks_repo_name: matebestek/mldb


text:
#include "accelerometer/calibration/calibrator.h"

#include <ros/node_handle.h>

#include "common/calibration/variables_center.h"
#include "common/calibration/variables_radius.h"
#include "accelerometer/calibration/cost_term.h"

#include <fstream>
#include <boost/property_tree/json_parser.hpp>

using namespace accelerometer;

// CONSTRUCTORS
calibrator::calibrator()
{
    // Initialize calibration.
    calibrator::m_calibration.setIdentity();

    // Initialize thread.
    calibrator::m_running = false;
}
calibrator::~calibrator()
{
    if(calibrator::m_running)
    {
        calibrator::m_thread.join();
    }
}

// METHODS
bool calibrator::start(const Eigen::Matrix<double, 3, 6>& data_set, double true_gravity_vector)
{
    // Check if thread is running.
    if(!calibrator::m_running)
    {
        // Reset calibration.
        calibrator::m_calibration.setIdentity();

        // Start optimization thread to generate fit.
        calibrator::m_thread = boost::thread(boost::bind(&calibrator::thread_worker, this, data_set, true_gravity_vector));
        return true;
    }
    else
    {
        return false;
    }
}

// CALIBRATION SAVING
std::string calibrator::print_calibration()
{
    // Write to string.
    std::stringstream output;
    output << "calibration units: m/s^2" << std::endl << std::endl;
    output << std::setprecision(6) << std::fixed;
    output << calibrator::m_calibration;

    return output.str();
}
bool calibrator::save_calibration_json(std::string filepath)
{
    // Use boost property tree to build up JSON file.
    boost::property_tree::ptree json_file;

    // Write as row-stepped array.
    boost::property_tree::ptree json_calibration;
    for(uint8_t i = 0; i < calibrator::m_calibration.rows(); ++i)
    {
        for(uint8_t j = 0; j < calibrator::m_calibration.cols(); ++j)
        {
            std::stringstream ss;
            ss << std::setprecision(10) << std::fixed << calibrator::m_calibration(i,j);
            json_calibration.push_back(boost::property_tree::ptree::value_type("", ss.str()));
        }
    }

    // Add component to JSON root.
    json_file.add_child("calibration", json_calibration);

    // Write JSON file.
    try
    {
        boost::property_tree::write_json(filepath, json_file);
    }
    catch(const std::exception& e)
    {
        ROS_ERROR_STREAM("error writing JSON calibration file (" << e.what() << ")");
        return false;
    }

    return true;
}
bool calibrator::save_calibration_yaml(std::string filepath)
{
    // Create stream for writing to file.
    std::ofstream yaml_file(filepath.c_str());

    if(!yaml_file)
    {
        ROS_ERROR_STREAM("error writing YAML calibration file (" << std::strerror(errno) << ")");
        return false;
    }

    // Write transformation component.
    yaml_file << "calibration: [";
    yaml_file << std::setprecision(6) << std::fixed;
    for(uint8_t i = 0; i < calibrator::m_calibration.rows(); ++i)
    {
        for(uint8_t j = 0; j < calibrator::m_calibration.cols(); ++j)
        {
            yaml_file << calibrator::m_calibration(i,j);
            if((i+1)*(j+1) < 16)
            {
                yaml_file << ", ";
            }
        }
    }
    yaml_file << "]";

    yaml_file.close();

    return true;
}

// THREADING
void calibrator::thread_worker(Eigen::Matrix<double, 3, 6> data_set, double true_gravity_vector)
{
    // Flag thread as running.
    calibrator::m_running = true;

    // Calculate the bounding box and it's parameters.
    Eigen::Vector3d bb_min, bb_max;
    bb_min.fill(std::numeric_limits<double>::infinity());
    bb_max.fill(-std::numeric_limits<double>::infinity());
    for(uint32_t j = 0; j < data_set.cols(); ++j)
    {
        for(uint32_t i = 0; i < 3; ++i)
        {
            if(data_set(i,j) < bb_min(i))
            {
                bb_min(i) = data_set(i,j);
            }
            if(data_set(i,j) > bb_max(i))
            {
                bb_max(i) = data_set(i,j);
            }
        }
    }
    // Calculate bounding box center.
    Eigen::Vector3d bb_width = bb_max - bb_min;
    Eigen::Vector3d bb_radius = bb_width / 2.0;
    Eigen::Vector3d bb_center = bb_max + bb_min;
    bb_center /= 2.0;

    // Set up the optimization components.
    std::shared_ptr<ifopt::variables_center> variables_center = std::make_shared<ifopt::variables_center>();
    std::shared_ptr<ifopt::variables_radius> variables_radius = std::make_shared<ifopt::variables_radius>();
    std::shared_ptr<ifopt::cost_term> cost_term = std::make_shared<ifopt::cost_term>(data_set);

    // Set initial guess and range for each variable.
    // Center
    variables_center->SetVariables(bb_center);
    variables_center->set_range(bb_center - bb_width*0.25, bb_center + bb_width*0.25);
    // Radius
    variables_radius->SetVariables(bb_radius);
    variables_radius->set_range(bb_radius * 0.5, bb_radius * 1.5);

    // Set component parameters.
    cost_term->p_gradient_perturbation(0.000001);

    // Set up the optimization problem.
    ifopt::Problem problem;
    problem.AddVariableSet(variables_center);
    problem.AddVariableSet(variables_radius);
    problem.AddCostSet(cost_term);

    // Run solver.
    ifopt::IpoptSolver solver;
    solver.SetOption("max_cpu_time", 30.0);
    solver.Solve(problem);

    // Check solve status.
    bool solved = solver.GetReturnStatus() == 0;

    // If solved, calculate calibration.
    if(solved)
    {
        // Extract fit parameters.
        auto fit_center = variables_center->GetValues();
        auto fit_radius = variables_radius->GetValues();

        // Calculate offset transform.
        Eigen::Matrix4d h_offset;
        h_offset.setIdentity();
        h_offset.block(0, 3, 3, 1) = -fit_center;

        // Calculate scale transform.
        Eigen::Matrix4d h_scale;
        h_scale.setIdentity();
        h_scale(0,0) = true_gravity_vector / fit_radius(0);
        h_scale(1,1) = true_gravity_vector / fit_radius(1);
        h_scale(2,2) = true_gravity_vector / fit_radius(2);

        // Calculate homogeneous transform.
        calibrator::m_calibration.noalias() = h_scale * h_offset;

        // Calculate fit points.
        Eigen::Matrix3d fit_points;
        fit_points.row(0) = fit_center - fit_radius;
        fit_points.row(1) = fit_center;
        fit_points.row(2) = fit_center + fit_radius;
        calibrator::new_fit(fit_points);

        // Calcuate calibration points.
        Eigen::Matrix3d calibration_points;
        Eigen::Vector4d p_u, p_c;
        p_u(3) = 1;
        for(uint32_t i = 0; i < 3; ++i)
        {
            p_u.block(0, 0, 3, 1) = fit_points.row(i).transpose();
            p_c.noalias() = calibrator::m_calibration * p_u;
            calibration_points.block(i, 0, 1, 3).noalias() = p_c.block(0, 0, 3, 1).transpose();
        }
        calibrator::new_calibration(calibration_points);

        // Signal new true gravity vector.
        calibrator::new_truth(true_gravity_vector);
    }

    // Signal completion.
    calibrator::calibration_completed(solved);

    // Flag thread as finished.
    calibrator::m_running = false;
}


text:
#define BOOST_TEST_MODULE "C++ Unit Tests for metaLBM"
#include <boost/test/included/unit_test.hpp>
#include <boost/test/unit_test.hpp>

#define NPROCS 1
#include "Lattice.h"
typedef double dataType;
typedef lbm::Lattice<dataType, lbm::LatticeType::D1Q3> L;
#include "Domain.h"
#include "Field.h"
#include "Initialize.h"

using namespace lbm;

BOOST_AUTO_TEST_SUITE(TestInitializeT)

BOOST_AUTO_TEST_CASE(initGlobalAlphaT) {
  ::lbm::Field<dataType, 1, true> alphaField("alpha");

  auto alphaGlobalField = ::lbm::initGlobalAlpha<dataType>();

  alphaField.setGlobalField(alphaGlobalField);

  for(unsigned int i = 0; i < gD::volume(); ++i) {
  const auto alpha_ = alphaField.getGlobalField(i, 0);
    BOOST_CHECK_EQUAL(alpha_, (dataType) 2);
  }

  }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: gtauzin/metaLBM

max_issues_repo_name: gtauzin/metaLBM

max_forks_repo_name: gtauzin/metaLBM


text:
#define BOOST_TEST_MODULE Tests

#ifdef BOOST_TEST_DYN_LINK
#    include <boost/test/unit_test.hpp>
#else
#    include <boost/test/included/unit_test.hpp>
#endif

#include <boost/test/tools/output_test_stream.hpp>

boost::test_tools::output_test_stream output;

#define CHECK_OUTPUT(msg) BOOST_CHECK(output.is_equal(msg))

class coutRedirect {
    std::streambuf* old;
  public:
    coutRedirect(std::streambuf* buf) : old(std::cout.rdbuf(buf)) {}
    ~coutRedirect() { std::cout.rdbuf(old); }
};

#include "Array.hpp"
#include "AVL.hpp"
#include "util.hpp"

BOOST_AUTO_TEST_SUITE(InsertionSort)

BOOST_AUTO_TEST_CASE(test1)
{
    Array<int, 5> x = { 4, 2, 4, 5, 1 };
    x.sort("insertion");
    output << x;
    CHECK_OUTPUT("1 2 4 4 5");
}

BOOST_AUTO_TEST_CASE(test2)
{
    Array<int, 100> a(2, 99);
    a.sort("insertion");
    for (std::size_t i = 0; i < a.size-1; ++i) {
        BOOST_CHECK_LE(a[i], a[i+1]);
    }
}

BOOST_AUTO_TEST_CASE(test3)
{
    Array<double, 10> x{ 10.2, 8.7, 8.3, 7.1, 6.9, 5.1, 4.3, 3.9, 2, 1.111 };
    x.sort("insertion");
    BOOST_CHECK_EQUAL(x[0], 1.111);
    BOOST_CHECK_EQUAL(x[1], 2);
    BOOST_CHECK_EQUAL(x[2], 3.9);
    BOOST_CHECK_EQUAL(x[3], 4.3);
    BOOST_CHECK_EQUAL(x[4], 5.1);
    BOOST_CHECK_EQUAL(x[5], 6.9);
    BOOST_CHECK_EQUAL(x[6], 7.1);
    BOOST_CHECK_EQUAL(x[7], 8.3);
    BOOST_CHECK_EQUAL(x[8], 8.7);
    BOOST_CHECK_EQUAL(x[9], 10.2);
}

BOOST_AUTO_TEST_CASE(test4)
{
    Array<int, 100> a(2, 99);
    a.sort("insertion");
    BOOST_CHECK(isSorted(a));
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(MergeSort)

BOOST_AUTO_TEST_CASE(test1)
{
    Array<int, 5> x = { 4, 2, 4, 5, 1 };
    x.sort("merge");
    output << x;
    CHECK_OUTPUT("1 2 4 4 5");
}

BOOST_AUTO_TEST_CASE(test2)
{
    Array<int, 100> a(2, 99);
    a.sort("merge");
    for (std::size_t i = 0; i < a.size-1; ++i) {
        BOOST_CHECK_LE(a[i], a[i+1]);
    }
}

BOOST_AUTO_TEST_CASE(test3)
{
    Array<double, 10> x{ 10.2, 8.7, 8.3, 7.1, 6.9, 5.1, 4.3, 3.9, 2, 1.111 };
    x.sort("merge");
    BOOST_CHECK_EQUAL(x[0], 1.111);
    BOOST_CHECK_EQUAL(x[1], 2);
    BOOST_CHECK_EQUAL(x[2], 3.9);
    BOOST_CHECK_EQUAL(x[3], 4.3);
    BOOST_CHECK_EQUAL(x[4], 5.1);
    BOOST_CHECK_EQUAL(x[5], 6.9);
    BOOST_CHECK_EQUAL(x[6], 7.1);
    BOOST_CHECK_EQUAL(x[7], 8.3);
    BOOST_CHECK_EQUAL(x[8], 8.7);
    BOOST_CHECK_EQUAL(x[9], 10.2);
}

BOOST_AUTO_TEST_CASE(test4)
{
    Array<int, 100> a(2, 99);
    a.sort("merge");
    BOOST_CHECK(isSorted(a));
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(HeapSort)

BOOST_AUTO_TEST_CASE(test1)
{
    Array<int, 5> x = { 4, 2, 4, 5, 1 };
    x.sort("heap");
    output << x;
    CHECK_OUTPUT("1 2 4 4 5");
}

BOOST_AUTO_TEST_CASE(test2)
{
    Array<int, 100> a(2, 99);
    a.sort("heap");
    for (std::size_t i = 0; i < a.size-1; ++i) {
        BOOST_CHECK_LE(a[i], a[i+1]);
    }
}

BOOST_AUTO_TEST_CASE(test3)
{
    Array<double, 10> x{ 10.2, 8.7, 8.3, 7.1, 6.9, 5.1, 4.3, 3.9, 2, 1.111 };
    x.sort("heap");
    BOOST_CHECK_EQUAL(x[0], 1.111);
    BOOST_CHECK_EQUAL(x[1], 2);
    BOOST_CHECK_EQUAL(x[2], 3.9);
    BOOST_CHECK_EQUAL(x[3], 4.3);
    BOOST_CHECK_EQUAL(x[4], 5.1);
    BOOST_CHECK_EQUAL(x[5], 6.9);
    BOOST_CHECK_EQUAL(x[6], 7.1);
    BOOST_CHECK_EQUAL(x[7], 8.3);
    BOOST_CHECK_EQUAL(x[8], 8.7);
    BOOST_CHECK_EQUAL(x[9], 10.2);
}

BOOST_AUTO_TEST_CASE(test4)
{
    Array<int, 100> a(2, 99);
    a.sort("heap");
    BOOST_CHECK(isSorted(a));
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(AVL_tree)

BOOST_AUTO_TEST_CASE(test1)
{
    coutRedirect guard(output.rdbuf());
    AVL<int> x;
    x.insert(10);
    x.insert(20);
    x.insert(30);
    x.insert(40);
    x.insert(50);
    x.insert(25);
    x.print("pre");
    CHECK_OUTPUT("30 20 10 25 40 50 \n");
}

BOOST_AUTO_TEST_CASE(test2)
{
    coutRedirect guard(output.rdbuf());
    AVL<int> x;
    x.insert(9);
    x.insert(5);
    x.insert(10);
    x.insert(0);
    x.insert(6);
    x.insert(11);
    x.insert(-1);
    x.insert(1);
    x.insert(2);
    x.print("pre");
    CHECK_OUTPUT("9 1 0 -1 5 2 6 10 11 \n");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Jorengarenar/homework

max_issues_repo_name: Jorengarenar/homework

max_forks_repo_name: Jorengarenar/homework