text:
#pragma once

#include <functional>
#include <string>

#include <boost/format.hpp>

#include "blackhole/attribute.hpp"
#include "blackhole/detail/config/underlying.hpp"
#include "blackhole/detail/stream/stream.hpp"
#include "blackhole/formatter/map/datetime.hpp"
#include "blackhole/keyword/timestamp.hpp"
#include "blackhole/utils/unique.hpp"

namespace blackhole {

namespace mapping {

template<typename T>
struct extracter {
    typedef std::function<void(aux::attachable_ostringstream&, const T&)> function_type;
    function_type func;

    extracter(std::function<void(aux::attachable_ostringstream&, const T&)> func) :
        func(func)
    {}

    void operator()(aux::attachable_ostringstream& stream, const attribute::value_t& value) const {
        typedef typename aux::underlying_type<T>::type underlying_type;
        func(stream, static_cast<T>(boost::get<underlying_type>(value)));
    }
};

class value_t {
    typedef std::function<void(aux::attachable_ostringstream&, const attribute::value_t&)> mapping_t;
    std::unordered_map<std::string, mapping_t> m_mappings;

public:
    // Generic overload for attributes, which has no keywords defined for them.
    template<typename T>
    void add(const std::string& key, typename extracter<T>::function_type handler) {
        m_mappings[key] = extracter<T>(handler);
    }

    // Overload for registered keywords. There is no need to provide attribute's name,
    // because it is already known.
    template<typename Keyword>
    void add(typename extracter<typename Keyword::type>::function_type handler) {
        add<typename Keyword::type>(Keyword::name(), handler);
    }

    // Overload for timestamp keyword. Fast datetime formatter will be used in that way.
    template<typename Keyword, class = typename std::enable_if<std::is_same<Keyword, keyword::tag::timestamp_t>::value>::type>
    void add(const std::string& format) {
        add<Keyword>(datetime_formatter_action_t(format));
    }

    template<typename Keyword, class = typename std::enable_if<std::is_same<Keyword, keyword::tag::timestamp_t>::value>::type>
    void add(const char* format) {
        add<Keyword>(datetime_formatter_action_t(format));
    }

    template<typename T>
    void operator()(aux::attachable_ostringstream& stream, const std::string& key, T&& value) const {
        auto it = m_mappings.find(key);
        if (it != m_mappings.end()) {
            const mapping_t& action = it->second;
            action(stream, std::forward<T>(value));
        } else {
            stream << value;
        }
    }

    template<typename T>
    boost::optional<std::string> operator()(const std::string& key, T&& value) const {
        auto it = m_mappings.find(key);
        if (it != m_mappings.end()) {
            const mapping_t& action = it->second;
            std::string buffer;
            aux::attachable_ostringstream stream;
            stream.attach(buffer);
            action(stream, std::forward<T>(value));
            stream.flush();
            return boost::optional<std::string>(buffer);
        }

        return boost::optional<std::string>();
    }
};

} // namespace mapping

} // namespace blackhole

max_stars_repo_name: bioothod/blackhole

max_issues_repo_name: bioothod/blackhole

max_forks_repo_name: bioothod/blackhole


text:
/*
 * Copyright 2017 Andrey Semashev
 *
 * Distributed under the Boost Software License, Version 1.0.
 * See http://www.boost.org/LICENSE_1_0.txt
 *
 * This header is deprecated, use boost/winapi/time.hpp instead.
 */

#ifndef BOOST_DETAIL_WINAPI_TIME_HPP_
#define BOOST_DETAIL_WINAPI_TIME_HPP_

#include <boost/config/header_deprecated.hpp>

BOOST_HEADER_DEPRECATED("<boost/winapi/time.hpp>")

#include <boost/winapi/time.hpp>
#include <boost/detail/winapi/detail/deprecated_namespace.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#endif // BOOST_DETAIL_WINAPI_TIME_HPP_

ext: hpp

max_issues_repo_name: Ingridamilsina/terminal

max_forks_repo_name: Ingridamilsina/terminal


text: #include <boost/qvm/static_assert.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <boost/algorithm/string.hpp>

#include <fstream>

#include "benchmark_utils.hpp"
#include "constant_mappings.hpp"
#include "scheduler/current_scheduler.hpp"
#include "scheduler/node_queue_scheduler.hpp"
#include "scheduler/topology.hpp"
#include "storage/table.hpp"
#include "utils/filesystem.hpp"
#include "utils/performance_warning.hpp"

namespace opossum {

std::ostream& get_out_stream(const bool verbose) {
  if (verbose) {
    return std::cout;
  }

  // Create no-op stream that just swallows everything streamed into it
  // See https://stackoverflow.com/a/11826666
  class NullBuffer : public std::streambuf {
   public:
    int overflow(int c) { return c; }
  };

  static NullBuffer null_buffer;
  static std::ostream null_stream(&null_buffer);
  return null_stream;
}

BenchmarkState::BenchmarkState(const size_t max_num_iterations, const opossum::Duration max_duration)
    : max_num_iterations(max_num_iterations), max_duration(max_duration) {}

bool BenchmarkState::keep_running() {
  switch (state) {
    case State::NotStarted:
      begin = std::chrono::high_resolution_clock::now();
      state = State::Running;
      break;
    case State::Over:
      return false;
    default: {}
  }

  if (num_iterations >= max_num_iterations) {
    end = std::chrono::high_resolution_clock::now();
    state = State::Over;
    return false;
  }

  end = std::chrono::high_resolution_clock::now();
  const auto duration = end - begin;
  if (duration >= max_duration) {
    state = State::Over;
    return false;
  }

  num_iterations++;

  return true;
}

BenchmarkConfig::BenchmarkConfig(const BenchmarkMode benchmark_mode, const bool verbose, const ChunkOffset chunk_size,
                                 const EncodingConfig encoding_type, const size_t max_num_query_runs,
                                 const Duration& max_duration, const UseMvcc use_mvcc,
                                 const std::optional<std::string>& output_file_path, const bool enable_scheduler,
                                 const bool enable_visualization, std::ostream& out)
    : benchmark_mode(benchmark_mode),
      verbose(verbose),
      chunk_size(chunk_size),
      encoding_config(encoding_type),
      max_num_query_runs(max_num_query_runs),
      max_duration(max_duration),
      use_mvcc(use_mvcc),
      output_file_path(output_file_path),
      enable_scheduler(enable_scheduler),
      enable_visualization(enable_visualization),
      out(out) {}

BenchmarkConfig BenchmarkConfig::get_default_config() { return BenchmarkConfig(); }

bool CLIConfigParser::cli_has_json_config(const int argc, char** argv) {
  const auto has_json = argc > 1 && boost::algorithm::ends_with(argv[1], ".json");
  if (has_json && argc > 2) {
    std::cout << "Passed multiple args with a json config. All CLI args will be ignored...";
  }

  return has_json;
}

nlohmann::json CLIConfigParser::parse_json_config_file(const std::string& json_file_str) {
  Assert(filesystem::is_regular_file(json_file_str), "No such file: " + json_file_str);

  nlohmann::json json_config;
  std::ifstream json_file{json_file_str};
  json_file >> json_config;

  return json_config;
}

BenchmarkConfig CLIConfigParser::parse_basic_options_json_config(const nlohmann::json& json_config) {
  const auto default_config = BenchmarkConfig::get_default_config();

  // Should the benchmark be run in verbose mode
  const auto verbose = json_config.value("verbose", default_config.verbose);
  auto& out = get_out_stream(verbose);

  // Display info about output destination
  std::optional<std::string> output_file_path;
  const auto output_file_string = json_config.value("output", "");
  if (!output_file_string.empty()) {
    output_file_path = output_file_string;
    out << "- Writing benchmark results to '" << *output_file_path << "'" << std::endl;
  } else {
    out << "- Writing benchmark results to stdout" << std::endl;
  }

  // Display info about MVCC being enabled or not
  const auto enable_mvcc = json_config.value("mvcc", default_config.use_mvcc == UseMvcc::Yes);
  const auto use_mvcc = enable_mvcc ? UseMvcc::Yes : UseMvcc::No;
  out << "- MVCC is " << (enable_mvcc ? "enabled" : "disabled") << std::endl;

  const auto enable_scheduler = json_config.value("scheduler", default_config.enable_scheduler);
  out << "- Running in " + std::string(enable_scheduler ? "multi" : "single") + "-threaded mode" << std::endl;

  // Determine benchmark and display it
  const auto benchmark_mode_str = json_config.value("mode", "IndividualQueries");
  auto benchmark_mode = BenchmarkMode::IndividualQueries;  // Just to init it deterministically
  if (benchmark_mode_str == "IndividualQueries") {
    benchmark_mode = BenchmarkMode::IndividualQueries;
  } else if (benchmark_mode_str == "PermutedQuerySets") {
    benchmark_mode = BenchmarkMode::PermutedQuerySets;
  } else {
    throw std::runtime_error("Invalid benchmark mode: '" + benchmark_mode_str + "'");
  }
  out << "- Running benchmark in '" << benchmark_mode_str << "' mode" << std::endl;

  const auto enable_visualization = json_config.value("visualize", default_config.enable_visualization);
  out << "- Visualization is " << (enable_visualization ? "on" : "off") << std::endl;

  // Get the specified encoding type
  std::unique_ptr<EncodingConfig> encoding_config{};
  const auto encoding_type_str = json_config.value("encoding", "Dictionary");
  const auto compression_type_str = json_config.value("compression", "");
  if (boost::algorithm::ends_with(encoding_type_str, ".json")) {
    // Use encoding file instead of default type
    encoding_config = std::make_unique<EncodingConfig>(parse_encoding_config(encoding_type_str));
    out << "- Encoding is custom from " << encoding_type_str << "" << std::endl;

    Assert(compression_type_str.empty(), "Specified both compression type and an encoding file. Invalid combination.");
  } else {
    encoding_config = std::make_unique<EncodingConfig>(
        EncodingConfig::encoding_spec_from_strings(encoding_type_str, compression_type_str));
    out << "- Encoding is '" << encoding_type_str << "'" << std::endl;
  }

  // Get all other variables
  const auto chunk_size = json_config.value("chunk_size", default_config.chunk_size);
  out << "- Chunk size is " << chunk_size << std::endl;

  const auto max_runs = json_config.value("runs", default_config.max_num_query_runs);
  out << "- Max runs per query is " << max_runs << std::endl;

  const auto default_duration_seconds = std::chrono::duration_cast<std::chrono::seconds>(default_config.max_duration);
  const auto max_duration = json_config.value("time", default_duration_seconds.count());
  out << "- Max duration per query is " << max_duration << " seconds" << std::endl;
  const Duration timeout_duration = std::chrono::duration_cast<opossum::Duration>(std::chrono::seconds{max_duration});

  return BenchmarkConfig{
      benchmark_mode, verbose,          chunk_size,       *encoding_config,     max_runs, timeout_duration,
      use_mvcc,       output_file_path, enable_scheduler, enable_visualization, out};
}

BenchmarkConfig CLIConfigParser::parse_basic_cli_options(const cxxopts::ParseResult& parse_result) {
  return parse_basic_options_json_config(basic_cli_options_to_json(parse_result));
}

nlohmann::json CLIConfigParser::basic_cli_options_to_json(const cxxopts::ParseResult& parse_result) {
  nlohmann::json json_config;

  json_config.emplace("verbose", parse_result["verbose"].as<bool>());
  json_config.emplace("runs", parse_result["runs"].as<size_t>());
  json_config.emplace("chunk_size", parse_result["chunk_size"].as<ChunkOffset>());
  json_config.emplace("time", parse_result["time"].as<size_t>());
  json_config.emplace("mode", parse_result["mode"].as<std::string>());
  json_config.emplace("encoding", parse_result["encoding"].as<std::string>());
  json_config.emplace("compression", parse_result["compression"].as<std::string>());
  json_config.emplace("scheduler", parse_result["scheduler"].as<bool>());
  json_config.emplace("mvcc", parse_result["mvcc"].as<bool>());
  json_config.emplace("visualize", parse_result["visualize"].as<bool>());
  json_config.emplace("output", parse_result["output"].as<std::string>());

  return json_config;
}

EncodingConfig CLIConfigParser::parse_encoding_config(const std::string& encoding_file_str) {
  Assert(filesystem::is_regular_file(encoding_file_str), "No such file: " + encoding_file_str);

  nlohmann::json encoding_config_json;
  std::ifstream json_file{encoding_file_str};
  json_file >> encoding_config_json;

  const auto encoding_spec_from_json = [](const nlohmann::json& json_spec) {
    Assert(json_spec.count("encoding"), "Need to specify encoding type for column.");
    const auto encoding_str = json_spec["encoding"];
    const auto compression_str = json_spec.value("compression", "");
    return EncodingConfig::encoding_spec_from_strings(encoding_str, compression_str);
  };

  Assert(encoding_config_json.count("default"), "Config must contain default encoding.");
  const auto default_spec = encoding_spec_from_json(encoding_config_json["default"]);

  DataTypeEncodingMapping type_encoding_mapping;
  const auto has_type_encoding = encoding_config_json.find("type") != encoding_config_json.end();
  if (has_type_encoding) {
    const auto type_encoding = encoding_config_json["type"];
    Assert(type_encoding.is_object(), "The type encoding needs to be specified as a json object.");

    for (const auto& type : nlohmann::json::iterator_wrapper(type_encoding)) {
      const auto type_str = boost::to_lower_copy(type.key());
      const auto data_type_it = data_type_to_string.right.find(type_str);
      Assert(data_type_it != data_type_to_string.right.end(), "Unknown data type for encoding: " + type_str);

      const auto& encoding_info = type.value();
      Assert(encoding_info.is_object(), "The type encoding info needs to be specified as a json object.");

      const auto data_type = data_type_it->second;
      type_encoding_mapping[data_type] = encoding_spec_from_json(encoding_info);
    }
  }

  TableColumnEncodingMapping custom_encoding_mapping;
  const auto has_custom_encoding = encoding_config_json.find("custom") != encoding_config_json.end();

  if (has_custom_encoding) {
    const auto custom_encoding = encoding_config_json["custom"];
    Assert(custom_encoding.is_object(), "The custom table encoding needs to be specified as a json object.");

    for (const auto& table : nlohmann::json::iterator_wrapper(custom_encoding)) {
      const auto& table_name = table.key();
      const auto& columns = table.value();

      Assert(columns.is_object(), "The custom column encoding needs to be specified as a json object.");
      custom_encoding_mapping.emplace(table_name, std::unordered_map<std::string, ColumnEncodingSpec>());

      for (const auto& column : nlohmann::json::iterator_wrapper(columns)) {
        const auto& column_name = column.key();
        const auto& encoding_info = column.value();
        Assert(encoding_info.is_object(), "The custom encoding info needs to be specified as a json object.");
        custom_encoding_mapping[table_name][column_name] = encoding_spec_from_json(encoding_info);
      }
    }
  }

  return EncodingConfig{default_spec, std::move(type_encoding_mapping), std::move(custom_encoding_mapping)};
}

std::string CLIConfigParser::detailed_help(const cxxopts::Options& options) {
  return options.help() + BenchmarkConfig::description + EncodingConfig::description;
}

EncodingConfig::EncodingConfig() : EncodingConfig{ColumnEncodingSpec{EncodingType::Dictionary}} {}

EncodingConfig::EncodingConfig(ColumnEncodingSpec default_encoding_spec)
    : EncodingConfig{default_encoding_spec, {}, {}} {}

EncodingConfig::EncodingConfig(ColumnEncodingSpec default_encoding_spec, DataTypeEncodingMapping type_encoding_mapping,
                               TableColumnEncodingMapping encoding_mapping)
    : default_encoding_spec{default_encoding_spec},
      type_encoding_mapping{std::move(type_encoding_mapping)},
      custom_encoding_mapping{std::move(encoding_mapping)} {}

EncodingConfig EncodingConfig::unencoded() { return EncodingConfig{ColumnEncodingSpec{EncodingType::Unencoded}}; }

ColumnEncodingSpec EncodingConfig::encoding_spec_from_strings(const std::string& encoding_str,
                                                              const std::string& compression_str) {
  const auto encoding = EncodingConfig::encoding_string_to_type(encoding_str);
  const auto compression = EncodingConfig::compression_string_to_type(compression_str);

  return compression ? ColumnEncodingSpec{encoding, *compression} : ColumnEncodingSpec{encoding};
}

EncodingType EncodingConfig::encoding_string_to_type(const std::string& encoding_str) {
  const auto type = encoding_type_to_string.right.find(encoding_str);
  Assert(type != encoding_type_to_string.right.end(), "Invalid encoding type: '" + encoding_str + "'");
  return type->second;
}

std::optional<VectorCompressionType> EncodingConfig::compression_string_to_type(const std::string& compression_str) {
  if (compression_str.empty()) return std::nullopt;

  const auto compression = vector_compression_type_to_string.right.find(compression_str);
  Assert(compression != vector_compression_type_to_string.right.end(),
         "Invalid compression type: '" + compression_str + "'");
  return compression->second;
}

nlohmann::json EncodingConfig::to_json() const {
  const auto encoding_spec_to_string_map = [](const ColumnEncodingSpec& spec) {
    nlohmann::json mapping{};
    mapping["encoding"] = encoding_type_to_string.left.at(spec.encoding_type);
    if (spec.vector_compression_type) {
      mapping["compression"] = vector_compression_type_to_string.left.at(spec.vector_compression_type.value());
    }
    return mapping;
  };

  nlohmann::json json{};
  json["default"] = encoding_spec_to_string_map(default_encoding_spec);

  nlohmann::json type_mapping{};
  for (const auto& [type, spec] : type_encoding_mapping) {
    const auto& type_str = data_type_to_string.left.at(type);
    type_mapping[type_str] = encoding_spec_to_string_map(spec);
  }

  if (!type_mapping.empty()) {
    json["type"] = type_mapping;
  }

  nlohmann::json table_mapping{};
  for (const auto& [table, column_config] : custom_encoding_mapping) {
    nlohmann::json column_mapping{};
    for (const auto& [column, spec] : column_config) {
      column_mapping[column] = encoding_spec_to_string_map(spec);
    }
    table_mapping[table] = column_mapping;
  }

  if (!table_mapping.empty()) {
    json["custom"] = table_mapping;
  }

  return json;
}

void BenchmarkTableEncoder::encode(const std::string& table_name, std::shared_ptr<Table> table,
                                   const EncodingConfig& config) {
  const auto& type_mapping = config.type_encoding_mapping;
  const auto& custom_mapping = config.custom_encoding_mapping;

  const auto& column_mapping_it = custom_mapping.find(table_name);
  const auto table_has_custom_encoding = column_mapping_it != custom_mapping.end();

  ChunkEncodingSpec chunk_spec;

  for (ColumnID column_id{0}; column_id < table->column_count(); ++column_id) {
    if (table_has_custom_encoding) {
      const auto& column_name = table->column_name(column_id);
      const auto& encoding_by_column_name = column_mapping_it->second;
      const auto& column_encoding = encoding_by_column_name.find(column_name);
      if (column_encoding != encoding_by_column_name.end()) {
        // The column has a custom encoding
        chunk_spec.push_back(column_encoding->second);
        continue;
      }
    }

    const auto& column_type = table->column_data_type(column_id);
    const auto& encoding_by_data_type = type_mapping.find(column_type);
    if (encoding_by_data_type != type_mapping.end()) {
      // The column type has a specific encoding
      chunk_spec.push_back(encoding_by_data_type->second);
      continue;
    }

    // No custom or type encoding were specified, use default
    chunk_spec.push_back(config.default_encoding_spec);
  }

  return ChunkEncoder::encode_all_chunks(table, chunk_spec);
}

// This is intentionally limited to 80 chars per line, as cxxopts does this too and it looks bad otherwise.
const char* BenchmarkConfig::description = R"(
============================
Benchmark Configuration JSON
============================
All options can also be provided as a JSON config file. This must be the only
argument passed in. The options are identical to and behave like the CLI options.
Example:
{
  "verbose": true,
  "scheduler": true,
  "chunk_size": 10000,
  "time": 5
}

The JSON config can also include benchmark-specific options (e.g. TPCH's scale
option). They will be parsed like the
CLI options.

{
  "verbose": true,
  "scale": 0.01
}
)";

// This is intentionally limited to 80 chars per line, as cxxopts does this too and it looks bad otherwise.
const char* EncodingConfig::description = R"(
======================
Encoding Configuration
======================
The encoding config represents the column encodings specified for a benchmark.
If encoding (and vector compression) were specified via command line args,
this will contain no custom encoding mapping but only the column default.
This will lead to each column in each chunk to be encoded/compressed by this
default. If a JSON config was provided, a column- and/or type-specific
encoding/compression can be chosen (same in each chunk). The JSON config must
look like this:

All encoding/compression types can be viewed with the `help` command or seen
in constant_mappings.cpp.
The encoding is always required, the compression is optional.

{
  "default": {
    "encoding": <ENCODING_TYPE_STRING>,               // required
    "compression": <VECTOR_COMPRESSION_TYPE_STRING>,  // optional
  },

  "type": {
    <DATA_TYPE>: {
      "encoding": <ENCODING_TYPE_STRING>,
      "compression": <VECTOR_COMPRESSION_TYPE_STRING>
    },
    <DATA_TYPE>: {
      "encoding": <ENCODING_TYPE_STRING>
    }
  },

  "custom": {
    <TABLE_NAME>: {
      <COLUMN_NAME>: {
        "encoding": <ENCODING_TYPE_STRING>,
        "compression": <VECTOR_COMPRESSION_TYPE_STRING>
      },
      <COLUMN_NAME>: {
        "encoding": <ENCODING_TYPE_STRING>
      }
    },
    <TABLE_NAME>: {
      <COLUMN_NAME>: {
        "encoding": <ENCODING_TYPE_STRING>,
        "compression": <VECTOR_COMPRESSION_TYPE_STRING>
      }
    }
  }
})";
}  // namespace opossum

ext: cpp

max_stars_repo_name: IanJamesMcKay/InMemoryDB

max_issues_repo_name: IanJamesMcKay/InMemoryDB

max_forks_repo_name: IanJamesMcKay/InMemoryDB


text:
#pragma once

#include <Eigen/Dense>
#include <vector>

#include "../flux_worker.hpp"

namespace boltzmann {
namespace impl_mls {

/**
 * @brief SpecularReflection
 *
 * velocity part (in Lagrange basis)
 *
 * upper hemisphere: outflow
 * lower hemisphere: inflow
 *
 */
class SpecularReflection : public boltzmann::impl::flux_worker
{
  using boltzmann::impl::flux_worker::vec_t;
  using boltzmann::impl::flux_worker::mat_t;

 public:
  SpecularReflection(const vec_t& hermite_weights, const vec_t& hermite_nodes)
      : w_(hermite_weights)
      , x_(hermite_nodes)
  {
    /* empty */
  }

  /**
   *
   *
   * @param out Ordering: out(i,j) = f(x_i, y_j)
   * \remark{Also see documentation of @ref H2N.}
   * @param in
   */
  virtual void apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const;

 private:
  const vec_t w_;
  const vec_t x_;
};

void
SpecularReflection::apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const
{
  AssertDimension(in.rows(), out.rows());
  AssertDimension(in.cols(), out.cols());
  AssertDimension(in.cols(), w_.size());

  int N = w_.size();

  int nhalf = N / 2;

  // reflection
  for (int j = 0; j < N; ++j) {
    for (int i = 0; i < N; ++i) {
      if (i < nhalf)
        out(i, j) = in(N - 1 - i, j);
      else
        out(i, j) = in(i, j);
    }
  }

  // multiply with weights
  for (int j = 0; j < N; ++j) {
    for (int i = 0; i < N; ++i) {
      out(i, j) *= x_[i];
    }
  }
}

}  // end namespace impl
}  // end namespace boltzmann


text:
//  Copyright Neil Groves 2014. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_DETAIL_COMBINE_CXX11_HPP
#define BOOST_RANGE_DETAIL_COMBINE_CXX11_HPP

#include <boost/range/iterator_range_core.hpp>
#include <boost/range/iterator.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/iterator/zip_iterator.hpp>

#include <fstream>

namespace boost
{
    namespace range
    {

template<typename... Ranges>
auto combine(Ranges&&... rngs) ->
    combined_range<decltype(boost::make_tuple(boost::begin(rngs)...))>
{
    return combined_range<decltype(boost::make_tuple(boost::begin(rngs)...))>(
                boost::make_tuple(boost::begin(rngs)...),
                boost::make_tuple(boost::end(rngs)...));
}

    } // namespace range

using range::combine;

} // namespace boost

#endif // include guard


text:
#ifndef STAN_MATH_PRIM_SCAL_PROB_LOGISTIC_RNG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_LOGISTIC_RNG_HPP

#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/log1p.hpp>
#include <stan/math/prim/scal/meta/length.hpp>
#include <stan/math/prim/scal/meta/VectorBuilder.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <boost/random/exponential_distribution.hpp>
#include <boost/random/variate_generator.hpp>

namespace stan {
  namespace math {

    template <class RNG>
    inline double
    logistic_rng(double mu,
                 double sigma,
                 RNG& rng) {
      using boost::variate_generator;
      using boost::random::exponential_distribution;

      static const char* function("logistic_rng");

      check_finite(function, "Location parameter", mu);
      check_positive_finite(function, "Scale parameter", sigma);

      variate_generator<RNG&, exponential_distribution<> >
        exp_rng(rng, exponential_distribution<>(1));
      return mu - sigma * std::log(exp_rng() / exp_rng());
    }

  }
}
#endif

max_stars_repo_name: yizhang-cae/torsten

max_issues_repo_name: yizhang-cae/torsten

max_forks_repo_name: yizhang-cae/torsten


text:
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////

#ifndef CROCODDYL_CORE_SOLVERS_FDDP_HPP_
#define CROCODDYL_CORE_SOLVERS_FDDP_HPP_

#include <Eigen/Cholesky>
#include <vector>

#include "crocoddyl/core/solvers/ddp.hpp"

namespace crocoddyl {

class SolverFDDP : public SolverDDP {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

  explicit SolverFDDP(boost::shared_ptr<ShootingProblem> problem);
  virtual ~SolverFDDP();

  virtual bool solve(const std::vector<Eigen::VectorXd>& init_xs = DEFAULT_VECTOR,
                     const std::vector<Eigen::VectorXd>& init_us = DEFAULT_VECTOR, const std::size_t& maxiter = 100,
                     const bool& is_feasible = false, const double& regInit = 1e-9);
  virtual const Eigen::Vector2d& expectedImprovement();
  void updateExpectedImprovement();
  virtual double calcDiff();
  virtual void forwardPass(const double& stepLength);

  double get_th_acceptnegstep() const;
  void set_th_acceptnegstep(const double& th_acceptnegstep);

 protected:
  double dg_;
  double dq_;
  double dv_;

 private:
  double th_acceptnegstep_;  //!< Threshold used for accepting step along ascent direction
};

}  // namespace crocoddyl

#endif  // CROCODDYL_CORE_SOLVERS_FDDP_HPP_

max_stars_repo_name: paLeziart/crocoddyl

max_issues_repo_name: paLeziart/crocoddyl

max_forks_repo_name: paLeziart/crocoddyl


text:
/* ----------------------------------------------------------------------------
 * GTDynamics Copyright 2020, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * See LICENSE for the license information
 * -------------------------------------------------------------------------- */

/**
 * @file  main.cpp
 * @brief Trajectory optimization for a legged robot with contacts.
 * @author Alejandro Escontrela
 */

#include <gtdynamics/dynamics/DynamicsGraph.h>
#include <gtdynamics/dynamics/OptimizerSetting.h>
#include <gtdynamics/factors/MinTorqueFactor.h>
#include <gtdynamics/universal_robot/Robot.h>
#include <gtdynamics/universal_robot/sdf.h>
#include <gtdynamics/utils/initialize_solution_utils.h>
#include <gtsam/base/Value.h>
#include <gtsam/base/Vector.h>
#include <gtsam/linear/NoiseModel.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/slam/PriorFactor.h>

#include <boost/algorithm/string/join.hpp>
#include <boost/optional.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>

using namespace gtdynamics;

int main(int argc, char** argv) {
  // Load the Vision 60 quadruped by Ghost robotics:
  // https://youtu.be/wrBNJKZKg10
  auto vision60 =
      CreateRobotFromFile(kUrdfPath + std::string("/vision60.urdf"));

  // Env parameters.
  gtsam::Vector3 gravity = (gtsam::Vector(3) << 0, 0, -9.8).finished();
  double mu = 2.0;

  // Contact points at feet.
  ContactPoints contact_points;
  contact_points.emplace(
      "lower0", ContactPoint{gtsam::Point3(0.14, 0, 0), 0});
  contact_points.emplace(
      "lower1", ContactPoint{gtsam::Point3(0.14, 0, 0), 1});
  contact_points.emplace(
      "lower2", ContactPoint{gtsam::Point3(0.14, 0, 0), 2});
  contact_points.emplace(
      "lower3", ContactPoint{gtsam::Point3(0.14, 0, 0), 3});

  // Specify optimal control problem parameters.
  double T = 3.0;                                     // Time horizon (s.)
  double dt = 1. / 240;                               // Time step (s.)
  int t_steps = static_cast<int>(std::ceil(T / dt));  // Timesteps.

  double sigma_dynamics = 1e-5;    // Variance of dynamics constraints.
  double sigma_objectives = 1e-3;  // Variance of additional objectives.

  // Specify boundary conditions for base and joints.
  gtsam::Pose3 base_pose_init = vision60.link("body")->wTcom();
  gtsam::Vector6 base_twist_init = gtsam::Z_6x1,
                 base_twist_final = gtsam::Z_6x1,
                 base_accel_init = gtsam::Z_6x1,
                 base_accel_final = gtsam::Z_6x1;
  gtsam::Vector joint_angles_init = gtsam::Vector::Zero(12),
                joint_vels_init = gtsam::Vector::Zero(12),
                joint_accels_init = gtsam::Vector::Zero(12),
                joint_vels_final = gtsam::Vector::Zero(12),
                joint_accels_final = gtsam::Vector::Zero(12);

  // Specify target poses we want to reach and at what times
  // we want to reach them.
  std::vector<gtsam::Pose3> des_poses;
  std::vector<double> des_poses_t;
  auto des_pose_nm = gtsam::noiseModel::Isotropic::Sigma(6, sigma_objectives);

  des_poses.push_back(gtsam::Pose3(gtsam::Rot3::RzRyRx(M_PI / 8, 0.0, 0.0),
                                   gtsam::Point3(0, 0, 0.1)));
  des_poses_t.push_back(0.75);

  des_poses.push_back(gtsam::Pose3(gtsam::Rot3::RzRyRx(-M_PI / 8, 0.0, 0.0),
                                   gtsam::Point3(0, 0, 0.1)));
  des_poses_t.push_back(1.5);

  des_poses.push_back(
      gtsam::Pose3(gtsam::Rot3::RzRyRx(0.0, M_PI / 10, M_PI / 8),
                   gtsam::Point3(0.0, 0, 0.1)));
  des_poses_t.push_back(2.25);

  des_poses.push_back(
      gtsam::Pose3(gtsam::Rot3::RzRyRx(0.0, -M_PI / 10, -M_PI / 8),
                   gtsam::Point3(0.0, 0, 0.1)));
  des_poses_t.push_back(3.0);

  // Build the trajectory factor graph and add boundary condition and goal
  // pose factors.
  auto opt = OptimizerSetting();
  opt.bp_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.bv_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.ba_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.p_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.v_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.a_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.f_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.fa_cost_model = gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics);
  opt.t_cost_model = gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.cp_cost_model = gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.cfriction_cost_model =
      gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.cv_cost_model = gtsam::noiseModel::Isotropic::Sigma(3, sigma_dynamics);
  opt.ca_cost_model = gtsam::noiseModel::Isotropic::Sigma(3, sigma_dynamics);
  opt.planar_cost_model =
      gtsam::noiseModel::Isotropic::Sigma(3, sigma_dynamics);
  opt.prior_q_cost_model =
      gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.prior_qv_cost_model =
      gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.prior_qa_cost_model =
      gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.prior_t_cost_model =
      gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.q_col_cost_model = gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.v_col_cost_model = gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  opt.time_cost_model = gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics);
  auto graph_builder = DynamicsGraph(opt, gravity);
  gtsam::NonlinearFactorGraph graph = graph_builder.trajectoryFG(
      vision60, t_steps, dt, CollocationScheme::Trapezoidal, contact_points,
      mu);

  auto base_link = vision60.link("body");
  gtsam::NonlinearFactorGraph objective_factors;

  // Add certain poses to be reached.
  for (size_t i = 0; i < des_poses.size(); i++)
    objective_factors.addPrior(
        internal::PoseKey(base_link->id(),
                          static_cast<int>(std::ceil(des_poses_t[i] / dt))),
        des_poses[i], des_pose_nm);

  // Add base boundary conditions to FG.
  objective_factors.addPrior(
      internal::PoseKey(base_link->id(), 0), base_pose_init,
      gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics));
  objective_factors.addPrior<gtsam::Vector6>(
      internal::TwistKey(base_link->id(), 0), base_twist_init,
      gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics));
  objective_factors.addPrior<gtsam::Vector6>(
      internal::TwistAccelKey(base_link->id(), 0), base_accel_init,
      gtsam::noiseModel::Isotropic::Sigma(6, sigma_dynamics));
  objective_factors.addPrior<gtsam::Vector6>(
      internal::TwistKey(base_link->id(), t_steps), base_twist_final,
      gtsam::noiseModel::Isotropic::Sigma(6, sigma_objectives));
  objective_factors.addPrior<gtsam::Vector6>(
      internal::TwistAccelKey(base_link->id(), t_steps), base_accel_final,
      gtsam::noiseModel::Isotropic::Sigma(6, sigma_objectives));

  // Add joint boundary conditions to FG.
  for (auto&& joint : vision60.joints()) {
    objective_factors.addPrior(
        internal::JointAngleKey(joint->id(), 0), 0.0,
        gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics));
    objective_factors.addPrior(
        internal::JointVelKey(joint->id(), 0), 0.0,
        gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics));
    objective_factors.addPrior(
        internal::JointAccelKey(joint->id(), 0), 0.0,
        gtsam::noiseModel::Isotropic::Sigma(1, sigma_dynamics));
    objective_factors.addPrior(
        internal::JointVelKey(joint->id(), t_steps), 0.0,
        gtsam::noiseModel::Isotropic::Sigma(1, sigma_objectives));
    objective_factors.addPrior(
        internal::JointAccelKey(joint->id(), t_steps), 0.0,
        gtsam::noiseModel::Isotropic::Sigma(1, sigma_objectives));
  }

  // Add min torque objectives.
  for (int t = 0; t <= t_steps; t++) {
    for (auto&& joint : vision60.joints())
      objective_factors.add(MinTorqueFactor(
          internal::TorqueKey(joint->id(), t),
          gtsam::noiseModel::Gaussian::Covariance(gtsam::I_1x1)));
  }
  graph.add(objective_factors);

  // Initialize solution.
  gtsam::Values init_vals;
  std::string initialization_technique = "inverse_kinematics";
  if (initialization_technique == "interp")
    // TODO(aescontrela): Figure out why the linearly interpolated initial
    // trajectory fails to optimize. My initial guess is that the optimizer has
    // a difficult time optimizing the trajectory when the initial solution lies
    // in the infeasible region. This would make sense if I were using an IPM to
    // solve this problem...
    init_vals = InitializeSolutionInterpolationMultiPhase(
        vision60, "body", base_pose_init, des_poses, des_poses_t, dt, 0.0,
        contact_points);
  else if (initialization_technique == "zeros")
    init_vals = ZeroValuesTrajectory(vision60, t_steps, 0, 0.0, contact_points);
  else if (initialization_technique == "inverse_kinematics")
    init_vals = InitializeSolutionInverseKinematics(
        vision60, "body", base_pose_init, des_poses, des_poses_t, dt, 0.0,
        contact_points);

  gtsam::LevenbergMarquardtParams params;
  params.setVerbosityLM("SUMMARY");
  gtsam::LevenbergMarquardtOptimizer optimizer(graph, init_vals, params);
  gtsam::Values results = optimizer.optimize();

  gtsam::Pose3 optimized_pose_init = Pose(results, base_link->id(), 0);
  gtsam::Pose3 optimized_pose_final =
      Pose(results, base_link->id(), t_steps - 1);

  std::cout << "Optimized Pose init trans: "
            << optimized_pose_init.translation()
            << "\n\tinit rot:" << optimized_pose_init.rotation().rpy()
            << std::endl;
  std::cout << "Optimized Pose final trans: "
            << optimized_pose_final.translation()
            << "\n\tfinal rot:" << optimized_pose_final.rotation().rpy()
            << std::endl;

  auto joint_vals_init = graph_builder.jointAnglesMap(vision60, results, 0);
  auto joint_vals_final =
      graph_builder.jointAnglesMap(vision60, results, t_steps);

  std::cout << "Joint vals init" << std::endl;
  for (auto&& jval : joint_vals_init)
    std::cout << "\t" << jval.first << ": " << jval.second << "," << std::endl;
  std::cout << "Joint vals final" << std::endl;
  for (auto&& jval : joint_vals_final)
    std::cout << "\t" << jval.first << ": " << jval.second << "," << std::endl;

  // Log the joint angles, velocities, accels, torques, and current goal pose.
  std::vector<std::string> jnames;
  for (auto&& joint : vision60.joints()) jnames.push_back(joint->name());
  std::string jnames_str = boost::algorithm::join(jnames, ",");
  std::ofstream traj_file;
  traj_file.open("traj.csv");
  // angles, vels, accels, torques.
  traj_file << jnames_str << "," << jnames_str << "," << jnames_str << ","
            << jnames_str << ",gol_x"
            << ",gol_y"
            << ",gol_z"
            << ",gol_qx"
            << ",gol_qy"
            << ",gol_qz"
            << ",gol_qw"
            << "\n";
  for (int t = 0; t <= t_steps; t++) {
    std::vector<std::string> vals;
    for (auto&& joint : vision60.joints())
      vals.push_back(std::to_string(JointAngle(results, joint->id(), t)));
    for (auto&& joint : vision60.joints())
      vals.push_back(std::to_string(JointVel(results, joint->id(), t)));
    for (auto&& joint : vision60.joints())
      vals.push_back(std::to_string(JointAccel(results, joint->id(), t)));
    for (auto&& joint : vision60.joints())
      vals.push_back(std::to_string(Torque(results, joint->id(), t)));

    for (size_t i = 0; i < des_poses.size(); i++) {
      gtsam::Pose3 dp = des_poses[i];
      if (t <= static_cast<int>(std::round(des_poses_t[i] / dt))) {
        vals.push_back(std::to_string(dp.x()));
        vals.push_back(std::to_string(dp.y()));
        vals.push_back(std::to_string(dp.z()));
        vals.push_back(std::to_string(dp.rotation().toQuaternion().x()));
        vals.push_back(std::to_string(dp.rotation().toQuaternion().y()));
        vals.push_back(std::to_string(dp.rotation().toQuaternion().z()));
        vals.push_back(std::to_string(dp.rotation().toQuaternion().w()));
        break;
      }
    }

    std::string vals_str = boost::algorithm::join(vals, ",");
    traj_file << vals_str << "\n";
  }
  traj_file.close();

  return 0;
}

max_stars_repo_name: danbarla/GTDynamics

max_issues_repo_name: danbarla/GTDynamics

max_forks_repo_name: danbarla/GTDynamics


text: #include <boost/winapi/heap_memory.hpp>


text:
/* $Id: map_context.hpp 48153 2011-01-01 15:57:50Z mordante $ */
/*
   Copyright (C) 2008 - 2011 by Tomasz Sniatowski <kailoran@gmail.com>
   Part of the Battle for Wesnoth Project http://www.wesnoth.org/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#ifndef EDITOR_MAP_CONTEXT_HPP_INCLUDED
#define EDITOR_MAP_CONTEXT_HPP_INCLUDED

#include "editor_map.hpp"

#include <boost/utility.hpp>

namespace editor {

/**
 * This class wraps around a map to provide a conscise interface for the editor to work with.
 * The actual map object can change rapidly (be assigned to), the map context persists
 * data (like the undo stacks) in this case. The functionality is here, not in editor_controller
 * as e.g. the undo stack is part of the map, not the editor as a whole. This might allow many
 * maps to be open at the same time.
 */
class map_context : private boost::noncopyable
{
public:
	/**
	 * Create a map context from an existing map. The filename is set to be
	 * empty, indicating a new map.
	 * Marked "explicit" to avoid automatic conversions.
	 */
	explicit map_context(const editor_map& map);

	/**
	 * Create map_context from a map file. If the map cannot be loaded, an
	 * exception will be thrown and the object will not be constructed. If the
	 * map file is a scenario, the map specified in its map_data key will be
	 * loaded, and the stored filename updated accordingly. Maps embedded
	 * inside scenarios do not change the filename, but set the "embedded" flag
	 * instead.
	 */
	map_context(const config& game_config, const std::string& filename);

	/**
	 * Map context destructor
	 */
	~map_context();

	/**
	 * Map accesor
	 */
	editor_map& get_map() { return map_; };

	/**
	 * Map accesor - const version
	 */
	const editor_map& get_map() const { return map_; }

	/**
	 * Draw a terrain on a single location on the map.
	 * Sets the refresh flags accordingly.
	 */
	void draw_terrain(t_translation::t_terrain terrain, const map_location& loc,
		bool one_layer_only = false);

	/**
	 * Actual drawing function used by both overloaded variants of draw_terrain.
	 */
	void draw_terrain_actual(t_translation::t_terrain terrain, const map_location& loc,
		bool one_layer_only = false);

	/**
	 * Draw a terrain on a set of locations on the map.
	 * Sets the refresh flags accordingly.
	 */
	void draw_terrain(t_translation::t_terrain terrain, const std::set<map_location>& locs,
		bool one_layer_only = false);

	/**
	 * Getter for the reload flag. Reload is the highest level of required refreshing,
	 * set when the map size has changed or the map was reassigned.
	 */
	bool needs_reload() const { return needs_reload_; }

	/**
	 * Setter for the reload flag
	 */
	void set_needs_reload(bool value=true) { needs_reload_ = value; }

	/**
	 * Getter for the terrain rebuild flag. Set whenever any terrain has changed.
	 */
	bool needs_terrain_rebuild() const { return needs_terrain_rebuild_; }

	/**
	 * Setter for the terrain rebuild flag
	 */
	void set_needs_terrain_rebuild(bool value=true) { needs_terrain_rebuild_ = value; }

	/**
	 * Getter fo the labels reset flag. Set when the labels need to be refreshed.
	 */
	bool needs_labels_reset() const { return needs_labels_reset_; }

	/**
	 * Setter for the labels reset flag
	 */
	void set_needs_labels_reset(bool value=true) { needs_labels_reset_ = value; }

	const std::set<map_location> changed_locations() const { return changed_locations_; }
	void clear_changed_locations();
	void add_changed_location(const map_location& loc);
	void add_changed_location(const std::set<map_location>& locs);
	void set_everything_changed();
	bool everything_changed() const;

	void clear_starting_position_labels(display& disp);

	void set_starting_position_labels(display& disp);

	void reset_starting_position_labels(display& disp);

	const std::string& get_filename() const { return filename_; }

	void set_filename(const std::string& fn) { filename_ = fn; }

	const std::string& get_map_data_key() const { return map_data_key_; }

	bool is_embedded() const { return embedded_; }

	void set_embedded(bool v) { embedded_ = v; }

	/**
	 * Saves the map under the current filename. Filename must be valid.
	 * May throw an exception on failure.
	 */
	bool save();

	void set_map(const editor_map& map);

	/**
	 * Performs an action (thus modyfying the map). An appropriate undo action is added to
	 * the undo stack. The redo stack is cleared. Note that this may throw, use caution
	 * when calling this with a dereferennced pointer that you own (i.e. use a smart pointer).
	 */
	void perform_action(const editor_action& action);

	/**
	 * Performs a partial action, assumes that the top undo action has been modified to
	 * maintain coherent state of the undo stacks, and so a new undo action is not
	 * created.
	 */
	void perform_partial_action(const editor_action& action);

	/** @return whether the map was modified since the last save */
	bool modified() const;

	/** Clear the modified state */
	void clear_modified();

	/** @return true when undo can be performed, false otherwise */
	bool can_undo() const;

	/** @return true when redo can be performed, false otherwise */
	bool can_redo() const;

	/** @return a pointer to the last undo action or NULL if the undo stack is empty */
	editor_action* last_undo_action();

	/** @return a pointer to the last redo action or NULL if the undo stack is empty */
	editor_action* last_redo_action();

	/** const version of last_undo_action */
	const editor_action* last_undo_action() const;

	/** const version of last_redo_action */
	const editor_action* last_redo_action() const;

	/** Un-does the last action, and puts it in the redo stack for a possible redo */
	void undo();

	/** Re-does a previousle undid action, and puts it back in the undo stack. */
	void redo();

	/**
	 * Un-does a single step from a undo action chain. The action is separated
	 * from the chain and it's undo (the redo) is added as a standalone action
	 * to the redo stack.
	 * Precodnition: the last undo action has to actually be an action chain.
	 */
	void partial_undo();

	/**
	 * Clear the undo and redo stacks
	 */
	void clear_undo_redo();

protected:
	/**
	 * The actual filename of this map. An empty string indicates a new map.
	 */
	std::string filename_;

	/**
	 * When a scenario file is loaded, the referenced map is loaded instead.
	 * The verbatim form of the reference is kept here.
	 */
	std::string map_data_key_;

	/**
	 * Whether the map context refers to a map embedded in a scenario file.
	 * This distinction is important in order to avoid overwriting the scenario.
	 */
	bool embedded_;

	/**
	 * The map object of this map_context.
	 */
	editor_map map_;

	/**
	 * Container type used to store actions in the undo and redo stacks
	 */
	typedef std::deque<editor_action*> action_stack;

	/**
	 * Checks if an action stack reached its capacity and removes the front element if so.
	 */
	void trim_stack(action_stack& stack);

	/**
	 * Clears an action stack and deletes all its contents. Helper function used when the undo
	 * or redo stack needs to be cleared
	 */
	void clear_stack(action_stack& stack);

	/**
	 * Perform an action at the back of one stack, and then move it to the back of the other stack.
	 * This is the implementation of both undo and redo which only differ in the direction.
	 */
	void perform_action_between_stacks(action_stack& from, action_stack& to);

	/**
	 * The undo stack. A double-ended queues due to the need to add items to one end,
	 * and remove from both when performing the undo or when trimming the size. This container owns
	 * all contents, i.e. no action in the stack shall be deleted, and unless otherwise noted the contents
	 * could be deleted at an time during normal operation of the stack. To work on an action, either
	 * remove it from the container or make a copy. Actions are inserted at the back of the container
	 * and disappear from the front when the capacity is exceeded.
	 * @todo Use boost's pointer-owning container?
	 */
	action_stack undo_stack_;

	/**
	 * The redo stack. @see undo_stack_
	 */
	action_stack redo_stack_;

	/**
	 * Action stack (i.e. undo and redo) maximum size
	 */
	static const size_t max_action_stack_size_;

	/**
	 * Number of actions performed since the map was saved. Zero means the map was not modified.
	 */
	int actions_since_save_;

	/**
	 * Cache of set starting position labels. Necessary for removing them.
	 */
	std::set<map_location> starting_position_label_locs_;

	/**
	 * Refresh flag indicating the map in this context should be completely reloaded by the display
	 */
	bool needs_reload_;

	/**
	 * Refresh flag indicating the terrain in the map has changed and requires a rebuild
	 */
	bool needs_terrain_rebuild_;

	/**
	 * Refresh flag indicating the labels in the map have changed
	 */
	bool needs_labels_reset_;

	std::set<map_location> changed_locations_;
	bool everything_changed_;
};

} //end namespace editor

#endif

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


text:
<<<<<<< HEAD
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

// Unit tests for denial-of-service detection/prevention code

#include "chainparams.h"
#include "keystore.h"
#include "net.h"
#include "net_processing.h"
#include "pow.h"
#include "script/sign.h"
#include "serialize.h"
#include "util.h"
#include "validation.h"

#include "test/test_wificoin.h"

#include <stdint.h>

#include <boost/test/unit_test.hpp>

// Tests these internal-to-net_processing.cpp methods:
extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer);
extern void EraseOrphansFor(NodeId peer);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
struct COrphanTx {
    CTransactionRef tx;
    NodeId fromPeer;
    int64_t nTimeExpire;
};
extern std::map<uint256, COrphanTx> mapOrphanTransactions;
=======
//
// Unit tests for denial-of-service detection/prevention code
//
#include <algorithm>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>

#include "main.h"
#include "wallet.h"
#include "net.h"
#include "util.h"

#include <stdint.h>

// Tests this internal-to-main.cpp method:
extern bool AddOrphanTx(const CTransaction& tx);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
extern std::map<uint256, CTransaction> mapOrphanTransactions;
extern std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev;
>>>>>>> 50d0f227934973e5559f2db2f3bb9b69428605a1

CService ip(uint32_t i)
{
    struct in_addr s;
    s.s_addr = i;
<<<<<<< HEAD
    return CService(CNetAddr(s), Params().GetDefaultPort());
}

static NodeId id = 0;

void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds);

BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup)

// Test eviction of an outbound peer whose chain never advances
// Mock a node connection, and use mocktime to simulate a peer
// which never sends any headers messages.  PeerLogic should
// decide to evict that outbound peer, after the appropriate timeouts.
// Note that we protect 4 outbound nodes from being subject to
// this logic; this test takes advantage of that protection only
// being applied to nodes which send headers with sufficient
// work.
BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
{
    std::atomic<bool> interruptDummy(false);

    // Mock an outbound peer
    CAddress addr1(ip(0xa0b0c001), NODE_NONE);
    CNode dummyNode1(id++, ServiceFlags(NODE_NETWORK|NODE_WITNESS), 0, INVALID_SOCKET, addr1, 0, 0, CAddress(), "", /*fInboundIn=*/ false);
    dummyNode1.SetSendVersion(PROTOCOL_VERSION);

    peerLogic->InitializeNode(&dummyNode1);
    dummyNode1.nVersion = 1;
    dummyNode1.fSuccessfullyConnected = true;

    // This test requires that we have a chain with non-zero work.
    BOOST_CHECK(chainActive.Tip() != nullptr);
    BOOST_CHECK(chainActive.Tip()->nChainWork > 0);

    // Test starts here
    peerLogic->SendMessages(&dummyNode1, interruptDummy); // should result in getheaders
    BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
    dummyNode1.vSendMsg.clear();

    int64_t nStartTime = GetTime();
    // Wait 21 minutes
    SetMockTime(nStartTime+21*60);
    peerLogic->SendMessages(&dummyNode1, interruptDummy); // should result in getheaders
    BOOST_CHECK(dummyNode1.vSendMsg.size() > 0);
    // Wait 3 more minutes
    SetMockTime(nStartTime+24*60);
    peerLogic->SendMessages(&dummyNode1, interruptDummy); // should result in disconnect
    BOOST_CHECK(dummyNode1.fDisconnect == true);
    SetMockTime(0);

    bool dummy;
    peerLogic->FinalizeNode(dummyNode1.GetId(), dummy);
}

void AddRandomOutboundPeer(std::vector<CNode *> &vNodes, PeerLogicValidation &peerLogic)
{
    CAddress addr(ip(GetRandInt(0xffffffff)), NODE_NONE);
    vNodes.emplace_back(new CNode(id++, ServiceFlags(NODE_NETWORK|NODE_WITNESS), 0, INVALID_SOCKET, addr, 0, 0, CAddress(), "", /*fInboundIn=*/ false));
    CNode &node = *vNodes.back();
    node.SetSendVersion(PROTOCOL_VERSION);

    peerLogic.InitializeNode(&node);
    node.nVersion = 1;
    node.fSuccessfullyConnected = true;

    CConnmanTest::AddNode(node);
}

BOOST_AUTO_TEST_CASE(stale_tip_peer_management)
{
    const Consensus::Params& consensusParams = Params().GetConsensus();
    constexpr int nMaxOutbound = 8;
    CConnman::Options options;
    options.nMaxConnections = 125;
    options.nMaxOutbound = nMaxOutbound;
    options.nMaxFeeler = 1;

    connman->Init(options);
    std::vector<CNode *> vNodes;

    // Mock some outbound peers
    for (int i=0; i<nMaxOutbound; ++i) {
        AddRandomOutboundPeer(vNodes, *peerLogic);
    }

    peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);

    // No nodes should be marked for disconnection while we have no extra peers
    for (const CNode *node : vNodes) {
        BOOST_CHECK(node->fDisconnect == false);
    }

    SetMockTime(GetTime() + 3*consensusParams.nPowTargetSpacing + 1);

    // Now tip should definitely be stale, and we should look for an extra
    // outbound peer
    peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);
    BOOST_CHECK(connman->GetTryNewOutboundPeer());

    // Still no peers should be marked for disconnection
    for (const CNode *node : vNodes) {
        BOOST_CHECK(node->fDisconnect == false);
    }

    // If we add one more peer, something should get marked for eviction
    // on the next check (since we're mocking the time to be in the future, the
    // required time connected check should be satisfied).
    AddRandomOutboundPeer(vNodes, *peerLogic);

    peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);
    for (int i=0; i<nMaxOutbound; ++i) {
        BOOST_CHECK(vNodes[i]->fDisconnect == false);
    }
    // Last added node should get marked for eviction
    BOOST_CHECK(vNodes.back()->fDisconnect == true);

    vNodes.back()->fDisconnect = false;

    // Update the last announced block time for the last
    // peer, and check that the next newest node gets evicted.
    UpdateLastBlockAnnounceTime(vNodes.back()->GetId(), GetTime());

    peerLogic->CheckForStaleTipAndEvictPeers(consensusParams);
    for (int i=0; i<nMaxOutbound-1; ++i) {
        BOOST_CHECK(vNodes[i]->fDisconnect == false);
    }
    BOOST_CHECK(vNodes[nMaxOutbound-1]->fDisconnect == true);
    BOOST_CHECK(vNodes.back()->fDisconnect == false);

    bool dummy;
    for (const CNode *node : vNodes) {
        peerLogic->FinalizeNode(node->GetId(), dummy);
    }

    CConnmanTest::ClearNodes();
}

BOOST_AUTO_TEST_CASE(DoS_banning)
{
    std::atomic<bool> interruptDummy(false);

    connman->ClearBanned();
    CAddress addr1(ip(0xa0b0c001), NODE_NONE);
    CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, CAddress(), "", true);
    dummyNode1.SetSendVersion(PROTOCOL_VERSION);
    peerLogic->InitializeNode(&dummyNode1);
    dummyNode1.nVersion = 1;
    dummyNode1.fSuccessfullyConnected = true;
    Misbehaving(dummyNode1.GetId(), 100); // Should get banned
    peerLogic->SendMessages(&dummyNode1, interruptDummy);
    BOOST_CHECK(connman->IsBanned(addr1));
    BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned

    CAddress addr2(ip(0xa0b0c002), NODE_NONE);
    CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, CAddress(), "", true);
    dummyNode2.SetSendVersion(PROTOCOL_VERSION);
    peerLogic->InitializeNode(&dummyNode2);
    dummyNode2.nVersion = 1;
    dummyNode2.fSuccessfullyConnected = true;
    Misbehaving(dummyNode2.GetId(), 50);
    peerLogic->SendMessages(&dummyNode2, interruptDummy);
    BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet...
    BOOST_CHECK(connman->IsBanned(addr1));  // ... but 1 still should be
    Misbehaving(dummyNode2.GetId(), 50);
    peerLogic->SendMessages(&dummyNode2, interruptDummy);
    BOOST_CHECK(connman->IsBanned(addr2));

    bool dummy;
    peerLogic->FinalizeNode(dummyNode1.GetId(), dummy);
    peerLogic->FinalizeNode(dummyNode2.GetId(), dummy);
}

BOOST_AUTO_TEST_CASE(DoS_banscore)
{
    std::atomic<bool> interruptDummy(false);

    connman->ClearBanned();
    gArgs.ForceSetArg("-banscore", "111"); // because 11 is my favorite number
    CAddress addr1(ip(0xa0b0c001), NODE_NONE);
    CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, CAddress(), "", true);
    dummyNode1.SetSendVersion(PROTOCOL_VERSION);
    peerLogic->InitializeNode(&dummyNode1);
    dummyNode1.nVersion = 1;
    dummyNode1.fSuccessfullyConnected = true;
    Misbehaving(dummyNode1.GetId(), 100);
    peerLogic->SendMessages(&dummyNode1, interruptDummy);
    BOOST_CHECK(!connman->IsBanned(addr1));
    Misbehaving(dummyNode1.GetId(), 10);
    peerLogic->SendMessages(&dummyNode1, interruptDummy);
    BOOST_CHECK(!connman->IsBanned(addr1));
    Misbehaving(dummyNode1.GetId(), 1);
    peerLogic->SendMessages(&dummyNode1, interruptDummy);
    BOOST_CHECK(connman->IsBanned(addr1));
    gArgs.ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));

    bool dummy;
    peerLogic->FinalizeNode(dummyNode1.GetId(), dummy);
}

BOOST_AUTO_TEST_CASE(DoS_bantime)
{
    std::atomic<bool> interruptDummy(false);

    connman->ClearBanned();
    int64_t nStartTime = GetTime();
    SetMockTime(nStartTime); // Overrides future calls to GetTime()

    CAddress addr(ip(0xa0b0c001), NODE_NONE);
    CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, CAddress(), "", true);
    dummyNode.SetSendVersion(PROTOCOL_VERSION);
    peerLogic->InitializeNode(&dummyNode);
    dummyNode.nVersion = 1;
    dummyNode.fSuccessfullyConnected = true;

    Misbehaving(dummyNode.GetId(), 100);
    peerLogic->SendMessages(&dummyNode, interruptDummy);
    BOOST_CHECK(connman->IsBanned(addr));

    SetMockTime(nStartTime+60*60);
    BOOST_CHECK(connman->IsBanned(addr));

    SetMockTime(nStartTime+60*60*24+1);
    BOOST_CHECK(!connman->IsBanned(addr));

    bool dummy;
    peerLogic->FinalizeNode(dummyNode.GetId(), dummy);
}

CTransactionRef RandomOrphan()
{
    std::map<uint256, COrphanTx>::iterator it;
    it = mapOrphanTransactions.lower_bound(InsecureRand256());
    if (it == mapOrphanTransactions.end())
        it = mapOrphanTransactions.begin();
    return it->second.tx;
=======
    return CService(CNetAddr(s), GetDefaultPort());
}

BOOST_AUTO_TEST_SUITE(DoS_tests)

BOOST_AUTO_TEST_CASE(DoS_banning)
{
    CNode::ClearBanned();
    CAddress addr1(ip(0xa0b0c001));
    CNode dummyNode1(INVALID_SOCKET, addr1, "", true);
    dummyNode1.Misbehaving(100); // Should get banned
    BOOST_CHECK(CNode::IsBanned(addr1));
    BOOST_CHECK(!CNode::IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned

    CAddress addr2(ip(0xa0b0c002));
    CNode dummyNode2(INVALID_SOCKET, addr2, "", true);
    dummyNode2.Misbehaving(50);
    BOOST_CHECK(!CNode::IsBanned(addr2)); // 2 not banned yet...
    BOOST_CHECK(CNode::IsBanned(addr1));  // ... but 1 still should be
    dummyNode2.Misbehaving(50);
    BOOST_CHECK(CNode::IsBanned(addr2));
}

BOOST_AUTO_TEST_CASE(DoS_banscore)
{
    CNode::ClearBanned();
    mapArgs["-banscore"] = "111"; // because 11 is my favorite number
    CAddress addr1(ip(0xa0b0c001));
    CNode dummyNode1(INVALID_SOCKET, addr1, "", true);
    dummyNode1.Misbehaving(100);
    BOOST_CHECK(!CNode::IsBanned(addr1));
    dummyNode1.Misbehaving(10);
    BOOST_CHECK(!CNode::IsBanned(addr1));
    dummyNode1.Misbehaving(1);
    BOOST_CHECK(CNode::IsBanned(addr1));
    mapArgs.erase("-banscore");
}

BOOST_AUTO_TEST_CASE(DoS_bantime)
{
    CNode::ClearBanned();
    int64 nStartTime = GetTime();
    SetMockTime(nStartTime); // Overrides future calls to GetTime()

    CAddress addr(ip(0xa0b0c001));
    CNode dummyNode(INVALID_SOCKET, addr, "", true);

    dummyNode.Misbehaving(100);
    BOOST_CHECK(CNode::IsBanned(addr));

    SetMockTime(nStartTime+60*60);
    BOOST_CHECK(CNode::IsBanned(addr));

    SetMockTime(nStartTime+60*60*24+1);
    BOOST_CHECK(!CNode::IsBanned(addr));
}

static bool CheckNBits(unsigned int nbits1, int64 time1, unsigned int nbits2, int64 time2)\
{
    if (time1 > time2)
        return CheckNBits(nbits2, time2, nbits1, time1);
    int64 deltaTime = time2-time1;

    CBigNum required;
    required.SetCompact(ComputeMinWork(nbits1, deltaTime));
    CBigNum have;
    have.SetCompact(nbits2);
    return (have <= required);
}

BOOST_AUTO_TEST_CASE(DoS_checknbits)
{
    using namespace boost::assign; // for 'map_list_of()'

    // Timestamps,nBits from the bitcoin block chain.
    // These are the block-chain checkpoint blocks
    typedef std::map<int64, unsigned int> BlockData;
    BlockData chainData =
        map_list_of(1239852051,486604799)(1262749024,486594666)
        (1279305360,469854461)(1280200847,469830746)(1281678674,469809688)
        (1296207707,453179945)(1302624061,453036989)(1309640330,437004818)
        (1313172719,436789733);

    // Make sure CheckNBits considers every combination of block-chain-lock-in-points
    // "sane":
    BOOST_FOREACH(const BlockData::value_type& i, chainData)
    {
        BOOST_FOREACH(const BlockData::value_type& j, chainData)
        {
            BOOST_CHECK(CheckNBits(i.second, i.first, j.second, j.first));
        }
    }

    // Test a couple of insane combinations:
    BlockData::value_type firstcheck = *(chainData.begin());
    BlockData::value_type lastcheck = *(chainData.rbegin());

    // First checkpoint difficulty at or a while after the last checkpoint time should fail when
    // compared to last checkpoint
    BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*10, lastcheck.second, lastcheck.first));
    BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*60*24*14, lastcheck.second, lastcheck.first));

    // ... but OK if enough time passed for difficulty to adjust downward:
    BOOST_CHECK(CheckNBits(firstcheck.second, lastcheck.first+60*60*24*365*4, lastcheck.second, lastcheck.first));
}

CTransaction RandomOrphan()
{
    std::map<uint256, CTransaction>::iterator it;
    it = mapOrphanTransactions.lower_bound(GetRandHash());
    if (it == mapOrphanTransactions.end())
        it = mapOrphanTransactions.begin();
    return it->second;
>>>>>>> 50d0f227934973e5559f2db2f3bb9b69428605a1
}

BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
{
    CKey key;
    key.MakeNewKey(true);
    CBasicKeyStore keystore;
    keystore.AddKey(key);

    // 50 orphan transactions:
    for (int i = 0; i < 50; i++)
    {
<<<<<<< HEAD
        CMutableTransaction tx;
        tx.vin.resize(1);
        tx.vin[0].prevout.n = 0;
        tx.vin[0].prevout.hash = InsecureRand256();
        tx.vin[0].scriptSig << OP_1;
        tx.vout.resize(1);
        tx.vout[0].nValue = 1*CENT;
        tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());

        AddOrphanTx(MakeTransactionRef(tx), i);
=======
        CTransaction tx;
        tx.vin.resize(1);
        tx.vin[0].prevout.n = 0;
        tx.vin[0].prevout.hash = GetRandHash();
        tx.vin[0].scriptSig << OP_1;
        tx.vout.resize(1);
        tx.vout[0].nValue = 1*CENT;
        tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID());

        AddOrphanTx(tx);
>>>>>>> 50d0f227934973e5559f2db2f3bb9b69428605a1
    }

    // ... and 50 that depend on other orphans:
    for (int i = 0; i < 50; i++)
    {
<<<<<<< HEAD
        CTransactionRef txPrev = RandomOrphan();

        CMutableTransaction tx;
        tx.vin.resize(1);
        tx.vin[0].prevout.n = 0;
        tx.vin[0].prevout.hash = txPrev->GetHash();
        tx.vout.resize(1);
        tx.vout[0].nValue = 1*CENT;
        tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
        SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);

        AddOrphanTx(MakeTransactionRef(tx), i);
=======
        CTransaction txPrev = RandomOrphan();

        CTransaction tx;
        tx.vin.resize(1);
        tx.vin[0].prevout.n = 0;
        tx.vin[0].prevout.hash = txPrev.GetHash();
        tx.vout.resize(1);
        tx.vout[0].nValue = 1*CENT;
        tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID());
        SignSignature(keystore, txPrev, tx, 0);

        AddOrphanTx(tx);
>>>>>>> 50d0f227934973e5559f2db2f3bb9b69428605a1
    }

    // This really-big orphan should be ignored:
    for (int i = 0; i < 10; i++)
    {
<<<<<<< HEAD
        CTransactionRef txPrev = RandomOrphan();

        CMutableTransaction tx;
        tx.vout.resize(1);
        tx.vout[0].nValue = 1*CENT;
        tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
        tx.vin.resize(2777);
        for (unsigned int j = 0; j < tx.vin.size(); j++)
        {
            tx.vin[j].prevout.n = j;
            tx.vin[j].prevout.hash = txPrev->GetHash();
        }
        SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL);
=======
        CTransaction txPrev = RandomOrphan();

        CTransaction tx;
        tx.vout.resize(1);
        tx.vout[0].nValue = 1*CENT;
        tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID());
        tx.vin.resize(500);
        for (unsigned int j = 0; j < tx.vin.size(); j++)
        {
            tx.vin[j].prevout.n = j;
            tx.vin[j].prevout.hash = txPrev.GetHash();
        }
        SignSignature(keystore, txPrev, tx, 0);
>>>>>>> 50d0f227934973e5559f2db2f3bb9b69428605a1
        // Re-use same signature for other inputs
        // (they don't have to be valid for this test)
        for (unsigned int j = 1; j < tx.vin.size(); j++)
            tx.vin[j].scriptSig = tx.vin[0].scriptSig;

<<<<<<< HEAD
        BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i));
    }

    // Test EraseOrphansFor:
    for (NodeId i = 0; i < 3; i++)
    {
        size_t sizeBefore = mapOrphanTransactions.size();
        EraseOrphansFor(i);
        BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore);
=======
        BOOST_CHECK(!AddOrphanTx(tx));
>>>>>>> 50d0f227934973e5559f2db2f3bb9b69428605a1
    }

    // Test LimitOrphanTxSize() function:
    LimitOrphanTxSize(40);
    BOOST_CHECK(mapOrphanTransactions.size() <= 40);
    LimitOrphanTxSize(10);
    BOOST_CHECK(mapOrphanTransactions.size() <= 10);
    LimitOrphanTxSize(0);
    BOOST_CHECK(mapOrphanTransactions.empty());
<<<<<<< HEAD
=======
    BOOST_CHECK(mapOrphanTransactionsByPrev.empty());
}

BOOST_AUTO_TEST_CASE(DoS_checkSig)
{
    // Test signature caching code (see key.cpp Verify() methods)

    CKey key;
    key.MakeNewKey(true);
    CBasicKeyStore keystore;
    keystore.AddKey(key);
    unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;

    // 100 orphan transactions:
    static const int NPREV=100;
    CTransaction orphans[NPREV];
    for (int i = 0; i < NPREV; i++)
    {
        CTransaction& tx = orphans[i];
        tx.vin.resize(1);
        tx.vin[0].prevout.n = 0;
        tx.vin[0].prevout.hash = GetRandHash();
        tx.vin[0].scriptSig << OP_1;
        tx.vout.resize(1);
        tx.vout[0].nValue = 1*CENT;
        tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID());

        AddOrphanTx(tx);
    }

    // Create a transaction that depends on orphans:
    CTransaction tx;
    tx.vout.resize(1);
    tx.vout[0].nValue = 1*CENT;
    tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID());
    tx.vin.resize(NPREV);
    for (unsigned int j = 0; j < tx.vin.size(); j++)
    {
        tx.vin[j].prevout.n = 0;
        tx.vin[j].prevout.hash = orphans[j].GetHash();
    }
    // Creating signatures primes the cache:
    boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
    for (unsigned int j = 0; j < tx.vin.size(); j++)
        BOOST_CHECK(SignSignature(keystore, orphans[j], tx, j));
    boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
    boost::posix_time::time_duration msdiff = mst2 - mst1;
    long nOneValidate = msdiff.total_milliseconds();
    if (fDebug) printf("DoS_Checksig sign: %ld\n", nOneValidate);

    // ... now validating repeatedly should be quick:
    // 2.8GHz machine, -g build: Sign takes ~760ms,
    // uncached Verify takes ~250ms, cached Verify takes ~50ms
    // (for 100 single-signature inputs)
    mst1 = boost::posix_time::microsec_clock::local_time();
    for (unsigned int i = 0; i < 5; i++)
        for (unsigned int j = 0; j < tx.vin.size(); j++)
            BOOST_CHECK(VerifySignature(CCoins(orphans[j], MEMPOOL_HEIGHT), tx, j, flags, SIGHASH_ALL));
    mst2 = boost::posix_time::microsec_clock::local_time();
    msdiff = mst2 - mst1;
    long nManyValidate = msdiff.total_milliseconds();
    if (fDebug) printf("DoS_Checksig five: %ld\n", nManyValidate);

    BOOST_CHECK_MESSAGE(nManyValidate < nOneValidate, "Signature cache timing failed");

    // Empty a signature, validation should fail:
    CScript save = tx.vin[0].scriptSig;
    tx.vin[0].scriptSig = CScript();
    BOOST_CHECK(!VerifySignature(CCoins(orphans[0], MEMPOOL_HEIGHT), tx, 0, flags, SIGHASH_ALL));
    tx.vin[0].scriptSig = save;

    // Swap signatures, validation should fail:
    std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig);
    BOOST_CHECK(!VerifySignature(CCoins(orphans[0], MEMPOOL_HEIGHT), tx, 0, flags, SIGHASH_ALL));
    BOOST_CHECK(!VerifySignature(CCoins(orphans[1], MEMPOOL_HEIGHT), tx, 1, flags, SIGHASH_ALL));
    std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig);

    // Exercise -maxsigcachesize code:
    mapArgs["-maxsigcachesize"] = "10";
    // Generate a new, different signature for vin[0] to trigger cache clear:
    CScript oldSig = tx.vin[0].scriptSig;
    BOOST_CHECK(SignSignature(keystore, orphans[0], tx, 0));
    BOOST_CHECK(tx.vin[0].scriptSig != oldSig);
    for (unsigned int j = 0; j < tx.vin.size(); j++)
        BOOST_CHECK(VerifySignature(CCoins(orphans[j], MEMPOOL_HEIGHT), tx, j, flags, SIGHASH_ALL));
    mapArgs.erase("-maxsigcachesize");

    LimitOrphanTxSize(0);
>>>>>>> 50d0f227934973e5559f2db2f3bb9b69428605a1
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: leangjia/wificoin

max_issues_repo_name: leangjia/wificoin

max_forks_repo_name: leangjia/wificoin


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Sylko Olzscher
 *
 */
#include "test-core-004.h"
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <cyng/chrono.h>
#include <cyng/traits.h>
#include <cyng/sys/cpu.h>
#include <thread>

namespace cyng
{
	bool test_core_004()
	{
		std::cout << chrono::to_string(std::chrono::system_clock::now()) << "---" << std::endl;
//
// 		auto tp1 = make_object(std::chrono::system_clock::now());
// 		tp1.serialize(std::cout) << std::endl;
//
//         auto tp2 = make_object(std::chrono::system_clock::from_time_t(chrono::tm_to_tt(chrono::init_tm(2001, 8, 19, 2, 3, 4))));
// 		tp2.serialize(std::cout) << std::endl;
//
		std::cout << "eod idx: " << type_tag_traits<eod>() << std::endl;
		std::cout << "buffer_t idx: " << type_tag_traits<buffer_t>() << std::endl;
		std::cout << "long double idx: " << type_tag_traits<long double>() << std::endl;

		std::cout << "buffer_t built-in: " << std::boolalpha << built_in_type<buffer_t>() << std::endl;
		std::cout << "long double built-in: " << std::boolalpha << built_in_type<long double>() << std::endl;

// 		auto u1 = make_object(boost::uuids::random_generator()());
// 		std::cout << "uuid tag: " << u1.get_class().tag() <<  " = " << traits::get_tag_name(u1.get_class().tag()) << std::endl;
		for (std::size_t idx = 0; idx < 10; ++idx)
		{
			std::cout << sys::get_total_cpu_load() << std::endl;
			std::this_thread::sleep_for(std::chrono::seconds(1));
		}
// 		std::cout << sys::get_total_cpu_load() << std::endl;
//
		return true;
	}
}

max_stars_repo_name: solosTec/cyng

max_issues_repo_name: solosTec/cyng

max_forks_repo_name: solosTec/cyng


text:
#include "BoostOdeint.hpp"

#include <Eigen/Core>

#include <tuple>
#include <iostream>

using namespace sodes::odeint;
using namespace Eigen;

// System to be solved
ArrayXd lorenz(const Ref<ArrayXd> x, Ref<ArrayXd> dxdt, const double &t)
{
    double sigma = 10.0;
    double R = 28.0;
    double b = 8.0 / 3.0;

    dxdt[0] = sigma * (x[1] - x[0]);
    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];
    dxdt[2] = -b * x[2] + x[0] * x[1];

    return dxdt;
}

int main (){
    // Defining the state vector with initial conditions
    int num_of_states = 3;
    ArrayXd X(num_of_states);
    X << 0., 1., 0.1;

    // Set time range and increment
    auto t_init = 0.0;
    auto t_final = 10.0;
    auto t_span = std::make_tuple(t_init, t_final);
    auto dt = 0.01;

    // Containers to store solution
    std::vector<ArrayXd> x_sol;
    std::vector<double> times;
    std::tie(times, x_sol) = solve_ivp_const(lorenz, t_span, dt, X, "runge_kutta_cash_karp54");

    // Displaying result on terminal
    auto steps = times.size();
    for (size_t i = 0; i < steps; i++)
    {
        std::cout << times[i] << '\t' << x_sol[i][0] << '\t' << x_sol[i][1] << '\t' << x_sol[i][2] << '\n';
    }
}

max_stars_repo_name: volpatto/pysodes

max_issues_repo_name: volpatto/pysodes

max_forks_repo_name: volpatto/pysodes


text:
// Copyright (c) 2015
// Author: Chrono Law
#include <std.hpp>
using namespace std;

#include <boost/assign.hpp>
#include <boost/circular_buffer.hpp>
using namespace boost;

//////////////////////////////////////////
void case1()
{
    circular_buffer<int> cb(5);
    assert(cb.empty());

    cb.push_back(1);
    cb.push_front(2);
    assert(cb.front() == 2);
    cb.insert(cb.begin(), 3);

    for (auto pos = cb.begin(); pos != cb.end();++pos)
    {   cout << *pos << ",";    }
    cout << endl;

    cb.pop_front();
    assert(cb.size() == 2);
    cb.push_back();
    assert(cb[0] = 2);

    //using namespace boost::assign;
    circular_buffer<int> cb1 = (assign::list_of(1),2,3);
    circular_buffer<int> cb2 = (assign::list_of(3),4,5);
    circular_buffer<int> cb3 = cb1;

    assert(cb1 < cb2);
    assert(cb1 == cb3);

}

//////////////////////////////////////////
template<typename T>
void print(T& cb)
{
    for (auto& x: cb)
    {   cout << x << ",";   }
    cout << endl;
}

void case2()
{
    circular_buffer<int> cb = (assign::list_of(1),2,3);
    print(cb);

    cb.push_back(4);
    print(cb);

    cb.push_back(5);
    print(cb);

    cb.pop_front();
    print(cb);

}

//////////////////////////////////////////
void case3()
{
    circular_buffer<int> cb =(assign::list_of(1),2,3,4,5);

    assert(cb.full());
    print(cb);

    int *p = cb.linearize();
    assert(p[0]== 1 && p[3] == 4);
    assert(cb.is_linearized());

    cb.rotate(cb.begin()+ 2);
    print(cb);

}

//////////////////////////////////////////
void case4()
{
    using namespace boost::assign;

    circular_buffer_space_optimized<int> cb( 10);
    push_back(cb)(1),2,3,4;

    assert(cb.size() == 4);
    assert(cb.capacity() == 10);

    cb.resize(100, 10);
    assert(cb.size() == cb.capacity());

}

//////////////////////////////////////////

int main()
{
    case1();
    case2();
    case3();
    case4();
}


text:
/*
 * Copyright (c) 2010-2012 frankee zhou (frankee.zhou at gmail dot com)
 *
 * Distributed under under the Apache License, version 2.0 (the "License").
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include <cetty/protobuf/service/ProtobufClientServiceAdaptor.h>

#include <boost/bind.hpp>
#include <google/protobuf/descriptor.h>

#include <cetty/service/ClientService.h>
#include <cetty/protobuf/service/ProtobufService.h>
#include <cetty/protobuf/service/ProtobufServiceMessage.h>
#include <cetty/protobuf/service/service.pb.h>
#include <cetty/util/Exception.h>

namespace cetty {
namespace protobuf {
namespace service {

using namespace google::protobuf;
using namespace cetty::service;
using namespace cetty::protobuf::service;
using namespace cetty::util;

// Call the given method of the remote service.  The signature of this
// procedure looks the same as Service::CallMethod(), but the requirements
// are less strict in one important way:  the request and response objects
// need not be of any specific class as long as their descriptors are
// method->input_type() and method->output_type().

ProtobufClientServiceAdaptor::ProtobufClientServiceAdaptor(const ChannelPtr& channel)
    : channel_(channel) {
}

ProtobufClientServiceAdaptor::~ProtobufClientServiceAdaptor() {
}

void ProtobufClientServiceAdaptor::doCallMethod(
    const ::google::protobuf::MethodDescriptor* method,
    const ConstMessagePtr& request,
    const ProtobufServiceFuturePtr& future) {

    if (channel_.expired()) {
        if (future) {
            future->setFailure(Exception(""));
        }

        return;
    }

    ProtobufServiceMessagePtr message(
        new ProtobufServiceMessage(MSG_REQUEST,
                                   method->service()->full_name(),
                                   method->name(),
                                   (MessagePtr)request));

    callMethod<ProtobufServiceMessagePtr, ProtobufServiceMessagePtr>(channel_.lock(), message, future);
}

}
}
}


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

#include <gtest/gtest.h>

#ifndef STAT_TEST // Don't perform statistical tests if boost is not found
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#endif

#include "chrono/motion_functions/ChFunction_Ramp.h"

#include "chrono_sensor/ChFunction_SensorNoise.h"
#include "chrono_sensor/ChFunction_SensorBias.h"
#include "chrono_sensor/ChFunction_SensorDigitize.h"

using namespace chrono;
using namespace chrono::vehicle::sensor;

#ifndef STAT_TEST // Don't perform statistical tests if boost is not found
using namespace boost::accumulators;

TEST(Function_Noise, stddev_mean_single_value) {
  ChFunction_Ramp f_ramp;
  f_ramp.Set_ang(0.1);
  f_ramp.Set_y0(0.4);

  double mean_val(0.5);
  double stddev_val(0.2);

  ChFunction_SensorNoise<> f_noise(mean_val, stddev_val);

  accumulator_set<double, stats<tag::mean, tag::variance>> acc;

  for (int i = 0; i < 1000; i++) {
    double x = (double) i / 50.0;
    double y = f_ramp.Get_y(x);
    double y_noise = f_noise.Get_y(y);
    double noise = y_noise - y;
    acc(noise);
  }
  auto m = mean(acc);
  auto st = sqrt(variance(acc));
  ASSERT_NEAR(mean(acc), mean_val, mean_val / 30.);
  ASSERT_NEAR(sqrt(variance(acc)), stddev_val, stddev_val / 30.);
}

TEST(Function_Noise, stddev_mean_vector) {
  ChFunction_Ramp f_ramp;
  f_ramp.Set_ang(0.1);
  f_ramp.Set_y0(0.4);

  ChVector<> mean_val(0.5, 0.25, 0.);
  ChVector<> stddev_val(0.2, 0.4, 0.);

  ChFunction_SensorNoise<ChVector<>> f_noise(mean_val, stddev_val);

  accumulator_set<double, stats<tag::mean, tag::variance>> acc_x;
  accumulator_set<double, stats<tag::mean, tag::variance>> acc_y;
  accumulator_set<double, stats<tag::mean, tag::variance>> acc_z;

  for (int i = 0; i < 10000; i++) {
    double id = static_cast<double>(i) / 50.;
    ChVector<> x = ChVector<>(id);
    ChVector<> y = ChVector<>(f_ramp.Get_y(x.x()), f_ramp.Get_y(x.y()), f_ramp.Get_y(x.z()));
    ChVector<> y_noise = f_noise.Get_y(y);
    ChVector<> noise = y_noise - y;
    acc_x(noise.x());
    acc_y(noise.y());
    acc_z(noise.z());
  }

  ASSERT_NEAR(mean(acc_x), mean_val.x(), mean_val.x() / 30.);
  ASSERT_NEAR(sqrt(variance(acc_x)), stddev_val.x(), stddev_val.x() / 30.);
  ASSERT_NEAR(mean(acc_y), mean_val.y(), mean_val.y() / 30.);
  ASSERT_NEAR(sqrt(variance(acc_y)), stddev_val.y(), stddev_val.y() / 30.);
  ASSERT_NEAR(mean(acc_z), mean_val.z(), mean_val.z() / 30.);
  ASSERT_NEAR(sqrt(variance(acc_z)), stddev_val.z(), stddev_val.z() / 30.);
}
#endif

TEST(Function_Noise, clone) {
  double mean_val = 0.5;
  double stddev_val = 0.2;

  ChFunction_SensorNoise<> f_noise(mean_val, stddev_val);
  auto f_noise_clone = f_noise.Clone();
  ASSERT_EQ(f_noise, *f_noise_clone);
  delete f_noise_clone;
}

TEST(Function_Bias, single_value) {
  double bias = 5.;
  double x = 1.;
  ChFunction_SensorBias<> f_bias(bias);
  ASSERT_EQ(x + bias, f_bias.Get_y(x));
}

TEST(Function_Bias, vector) {
  ChVector<> bias(5., 4., 3.);
  ChVector<> x(2., 4., 8.);
  ChFunction_SensorBias<ChVector<>> f_bias(bias);
  ASSERT_EQ(x + bias, f_bias.Get_y(x));
}

TEST(Function_Bias, quaternion) {
  ChQuaternion<> initial_rot = Q_from_AngAxis(20 * CH_C_DEG_TO_RAD, ChVector<>(0., 0., 1.));
  ChQuaternion<> bias = Q_from_AngAxis(25 * CH_C_DEG_TO_RAD, ChVector<>(0., 0., 1.));
  ChFunction_SensorBias<ChQuaternion<>> f_bias(bias);
  auto ret = f_bias.Get_y(initial_rot);
  ChVector<> va(5., 0., 0.);
  ChVector<> vb = ret.Rotate(va);
  ASSERT_NEAR(vb.x(), 3.53553390593, 1e-6);
  ASSERT_NEAR(vb.y(), 3.53553390593, 1e-6);
}

TEST(Function_Bias, clone) {
  double bias = 5.;
  ChFunction_SensorBias<> f_bias(bias);

  auto f_bias_clone = f_bias.Clone();
  ASSERT_EQ(f_bias, *f_bias_clone);
  delete f_bias_clone;
}

TEST(Function_Digitize, single_value) {
  double bits = 4;
  double min = 0.0;
  double max = 50.;
  double res = (max - min) / pow(2, bits);
  ChFunction_SensorDigitize<> f_dig(bits, max - min);
  auto test = f_dig.Get_y(3.45);
  ASSERT_EQ(f_dig.Get_y(3.45), res * round(3.45 / res));
}

TEST(Function_Digitize, vector) {
  double bits(12.);
  ChVector<> min(0.0);
  ChVector<> max(50.);
  ChVector<> res;
  ChFunction_SensorDigitize<ChVector<>> f_dig(bits, max - min);
  for (int i = 0; i < 3; ++i) {
    res[i] = (max[i] - min[i]) / pow(2., bits);
    ASSERT_EQ(f_dig.Get_y(ChVector<>(3.45))[i], res[i] * round(3.45 / res[i]));
  }
}

TEST(Function_Digitize, quaternion) {
  double bits(12.);
  ChVector<> min(0.);
  ChVector<> max(50.);
  ChQuaternion<> res;
  ChFunction_SensorDigitize<ChQuaternion<>> f_dig(bits, max - min);
  auto t = f_dig.Get_y(ChQuaternion<>(3.45, ChVector<>(3.45)));
  auto r = ChQuaternion<>(0.49950151852068797, ChVector<>(0.50016605009254234));
  ASSERT_TRUE(t.Equals(r));
}