text:
/*
Copyright 2009-2021 Nicolas Colombe

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 <gen/poissonsampling.hpp>
#include <math/geometrytraits.hpp>
#include <math/vector2.hpp>
#include <math/aabb2d.hpp>

#include <core/random.hpp>
#include <core/heapobject.hpp>

#include <boost/random.hpp>
//#include <boost/pool/pool_alloc.hpp>
#include <boost/geometry/index/rtree.hpp>

typedef std::pair<eXl::Vector2d, unsigned int> value;
typedef boost::geometry::index::rtree< value, boost::geometry::index::rstar<16, 4> > PointIndex;

namespace eXl
{

  static const unsigned int k_BootstrapLimit = 30;
  static const unsigned int k_GeneratedPoints = 30;

  //typedef boost::fast_pool_allocator<Vector2d,
  //  boost::default_user_allocator_new_delete,
  //  boost::details::pool::default_mutex,
  //  64, 128> allocator;

  typedef std::list<Vector2d/*, allocator*/> PointsStack;

  struct PoissonDiskSampling_Impl : public HeapObject
  {
    PoissonDiskSampling_Impl(Polygoni const& iPoly, Random& iGen) : m_PrecisePoly(iPoly), m_Gen(iGen)
    {
      //m_Stack.reserve(1024);
    }

    void AddPoint(Vector2d const& iPoint, float iCovering)
    {

      for(unsigned int i = 0; i < m_PointsIndex.size(); ++i)
      {
        double checkRadius = (m_Covering[i] + iCovering);
        AABB2Dd box = AABB2Dd::FromCenterAndSize(iPoint, Vector2d::ONE * checkRadius * 2);
        PointIndex const& index = m_PointsIndex[i];
        std::vector<value> returned_values;
        index.query(boost::geometry::index::within(box), std::back_inserter(returned_values));
        for(auto val : returned_values)
        {
          if((iPoint - val.first).Length() < checkRadius)
          {
            m_PointsValid[i][val.second] = false;
          }
        }
      }

      m_Stack.push_back(iPoint);
    }

    PointsStack m_Stack;

    std::vector<PointIndex>             m_PointsIndex;
    std::vector<std::vector<bool> >     m_PointsValid;
    std::vector<std::vector<Vector2d> > m_Points;
    std::vector<float>                  m_Covering;

    Polygond              m_PrecisePoly;
    Random&               m_Gen;
  };

  PoissonDiskSampling::PoissonDiskSampling(Polygoni const& iPoly, Random& iGen)
    :m_Impl(eXl_NEW PoissonDiskSampling_Impl(iPoly, iGen))
  {

  }

  PoissonDiskSampling::~PoissonDiskSampling()
  {
    eXl_DELETE m_Impl;
  }

  void PoissonDiskSampling::Sample(float iRadius, float iCovering, unsigned int iMaxPts)
  {
    Vector<Polygond> shrinkedPoly;
    {
      m_Impl->m_PrecisePoly.Shrink(iCovering, shrinkedPoly);
      if(shrinkedPoly.empty())
      {
        return;
      }
    }

    PointIndex curIndex;
    std::vector<Vector2d> curPoints;

    unsigned int numPts = 0;
    RandomWrapper rand(&m_Impl->m_Gen);

    for(auto poly : shrinkedPoly)
    {
      boost::random::uniform_real_distribution<double> distribX(poly.GetAABB().m_Data[0].X(), poly.GetAABB().m_Data[1].X());
      boost::random::uniform_real_distribution<double> distribY(poly.GetAABB().m_Data[0].Y(), poly.GetAABB().m_Data[1].Y());

      for(unsigned int i = 0; i<k_BootstrapLimit; ++i)
      {
        Vector2d origPt(distribX(rand),distribY(rand));
        if(poly.ContainsPoint(origPt))
        {
          m_Impl->AddPoint(origPt, iCovering);
          curIndex.insert(std::make_pair(origPt, numPts));
          curPoints.push_back(origPt);
          ++numPts;
          break;
        }
      }

      while(!m_Impl->m_Stack.empty()
      && (iMaxPts == 0 || numPts < iMaxPts))
      {
        boost::random::uniform_real_distribution<double> distribTheta(-Mathd::PI, Mathd::PI);
        Vector2d origPt = m_Impl->m_Stack.front();
        m_Impl->m_Stack.pop_front();

        for(unsigned int i = 0; i<k_GeneratedPoints; ++i)
        {
          double angle = distribTheta(rand);
          Vector2d point = origPt + Vector2d(Mathd::Cos(angle), Mathd::Sin(angle)) * iRadius * 2;
          if(poly.ContainsPoint(point))
          {
            AABB2Dd box = AABB2Dd::FromCenterAndSize(point, Vector2d(iRadius, iRadius) * 4);
            bool validPoint = true;
            std::vector<value> returned_values;
            curIndex.query(boost::geometry::index::within(box), std::back_inserter(returned_values));

            for(auto val : returned_values)
            {
              if((point - val.first).Length() < 2*iRadius)
              {
                validPoint = false;
                break;
              }
            }
            if(validPoint)
            {
              m_Impl->AddPoint(point, iCovering);
              curIndex.insert(std::make_pair(point, numPts));
              curPoints.push_back(point);
              ++numPts;
            }
          }
        }
      }
    }

    m_Impl->m_Covering.push_back(iCovering);
    m_Impl->m_Points.push_back(std::vector<Vector2d>());
    m_Impl->m_PointsValid.push_back(std::vector<bool>());
    m_Impl->m_PointsIndex.push_back(PointIndex());

    m_Impl->m_Points.back().swap(curPoints);
    m_Impl->m_PointsIndex.back().swap(curIndex);
    m_Impl->m_PointsValid.back().resize(numPts, true);

  }

  unsigned int PoissonDiskSampling::GetNumLayers() const
  {
    return m_Impl->m_PointsIndex.size();
  }

  void PoissonDiskSampling::GetLayer(unsigned int iLayer, Vector<Vector2d>& oPoints) const
  {
    oPoints.clear();
    if(iLayer < m_Impl->m_PointsIndex.size())
    {
      for(unsigned int i = 0; i<m_Impl->m_Points[iLayer].size(); ++i)
      {
        if(m_Impl->m_PointsValid[iLayer][i])
        {
          oPoints.push_back(m_Impl->m_Points[iLayer][i]);
        }
      }
    }
  }

}

max_stars_repo_name: eXl-Nic/eXl

max_issues_repo_name: eXl-Nic/eXl

max_forks_repo_name: eXl-Nic/eXl


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// protocol.cpp
//
// Identification: src/wire/protocol.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "wire/packet_manager.h"

#include <boost/algorithm/string.hpp>
#include <cstdio>
#include <unordered_map>

#include "common/cache.h"
#include "common/macros.h"
#include "common/portal.h"
#include "optimizer/simple_optimizer.h"
#include "planner/abstract_plan.h"
#include "planner/delete_plan.h"
#include "planner/insert_plan.h"
#include "planner/update_plan.h"
#include "tcop/tcop.h"
#include "type/types.h"
#include "type/value.h"
#include "type/value_factory.h"
#include "wire/marshal.h"

#define PROTO_MAJOR_VERSION(x) x >> 16

namespace peloton {
namespace wire {

// TODO: Remove hardcoded auth strings
// Hardcoded authentication strings used during session startup. To be removed
const std::unordered_map<std::string, std::string>
    // clang-format off
    PacketManager::parameter_status_map_ =
        boost::assign::map_list_of("application_name", "psql")
				("client_encoding", "UTF8")
				("DateStyle", "ISO, MDY")
				("integer_datetimes", "on")
				("IntervalStyle", "postgres")
				("is_superuser", "on")
				("server_encoding", "UTF8")
				("server_version", "9.5devel")
				("session_authorization", "postgres")
				("standard_conforming_strings", "on")
				("TimeZone", "US/Eastern");
// clang-format on

std::vector<PacketManager *> PacketManager::packet_managers_;
std::mutex PacketManager::packet_managers_mutex_;

PacketManager::PacketManager()
    : txn_state_(NetworkTransactionStateType::IDLE), pkt_cntr_(0) {
  traffic_cop_.reset(new tcop::TrafficCop());
  {
    std::lock_guard<std::mutex> lock(PacketManager::packet_managers_mutex_);
    PacketManager::packet_managers_.push_back(this);
    LOG_DEBUG("Registered new PacketManager [count=%d]",
              (int)PacketManager::packet_managers_.size());
  }
}

PacketManager::~PacketManager() {
  {
    std::lock_guard<std::mutex> lock(PacketManager::packet_managers_mutex_);
    PacketManager::packet_managers_.erase(
        std::remove(PacketManager::packet_managers_.begin(),
                    PacketManager::packet_managers_.end(), this),
        PacketManager::packet_managers_.end());
    LOG_DEBUG("Removed PacketManager [count=%d]",
              (int)PacketManager::packet_managers_.size());
  }
}

void PacketManager::InvalidatePreparedStatements(oid_t table_id) {
  if (table_statement_cache_.find(table_id) == table_statement_cache_.end()) {
    return;
  }
  LOG_DEBUG("Marking all PreparedStatements that access table '%d' as invalid",
            (int)table_id);
  for (auto statement : table_statement_cache_[table_id]) {
    LOG_DEBUG("Setting PreparedStatement '%s' as needing to be replanned",
              statement->GetStatementName().c_str());
    statement->SetNeedsPlan(true);
  }
}

void PacketManager::ReplanPreparedStatement(Statement *statement) {
  std::string error_message;
  auto new_statement = traffic_cop_->PrepareStatement(
      statement->GetStatementName(), statement->GetQueryString(),
      error_message);
  // But then rip out its query plan and stick it in our old statement
  if (new_statement.get() == nullptr) {
    LOG_ERROR(
        "Failed to generate a new query plan for PreparedStatement '%s'\n%s",
        statement->GetStatementName().c_str(), error_message.c_str());
  } else {
    LOG_DEBUG("Generating new plan for PreparedStatement '%s'",
              statement->GetStatementName().c_str());

    auto old_plan = statement->GetPlanTree();
    auto new_plan = new_statement->GetPlanTree();
    statement->SetPlanTree(new_plan);
    new_statement->SetPlanTree(old_plan);
    statement->SetNeedsPlan(false);

    // TODO: We may need to delete the old plan and new statement here
  }
}

void PacketManager::MakeHardcodedParameterStatus(
    const std::pair<std::string, std::string> &kv) {
  std::unique_ptr<OutputPacket> response(new OutputPacket());
  response->msg_type = NetworkMessageType::PARAMETER_STATUS;
  PacketPutString(response.get(), kv.first);
  PacketPutString(response.get(), kv.second);
  responses.push_back(std::move(response));
}
/*
 * process_startup_packet - Processes the startup packet
 *  (after the size field of the header).
 */
bool PacketManager::ProcessStartupPacket(InputPacket *pkt) {
  std::string token, value;
  std::unique_ptr<OutputPacket> response(new OutputPacket());

  int32_t proto_version = PacketGetInt(pkt, sizeof(int32_t));

  // Only protocol version 3 is supported
  if (PROTO_MAJOR_VERSION(proto_version) != 3) {
    LOG_ERROR("Protocol error: Only protocol version 3 is supported.");
    exit(EXIT_FAILURE);
  }

  // TODO: check for more malformed cases
  // iterate till the end
  for (;;) {
    // loop end case?
    if (pkt->ptr >= pkt->len) break;
    GetStringToken(pkt, token);

    // if the option database was found
    if (token.compare("database") == 0) {
      // loop end?
      if (pkt->ptr >= pkt->len) break;
      GetStringToken(pkt, client_.dbname);
    } else if (token.compare(("user")) == 0) {
      // loop end?
      if (pkt->ptr >= pkt->len) break;
      GetStringToken(pkt, client_.user);
    } else {
      if (pkt->ptr >= pkt->len) break;
      GetStringToken(pkt, value);
      client_.cmdline_options[token] = value;
    }
  }

  // send auth-ok ('R')
  response->msg_type = NetworkMessageType::AUTHENTICATION_REQUEST;
  PacketPutInt(response.get(), 0, 4);
  responses.push_back(std::move(response));

  // Send the parameterStatus map ('S')
  for (auto it = parameter_status_map_.begin();
       it != parameter_status_map_.end(); it++) {
    MakeHardcodedParameterStatus(*it);
  }

  // ready-for-query packet -> 'Z'
  SendReadyForQuery(NetworkTransactionStateType::IDLE);

  // we need to send the response right away
  force_flush = true;

  return true;
}

void PacketManager::PutTupleDescriptor(
    const std::vector<FieldInfo> &tuple_descriptor) {
  if (tuple_descriptor.empty()) return;

  std::unique_ptr<OutputPacket> pkt(new OutputPacket());
  pkt->msg_type = NetworkMessageType::ROW_DESCRIPTION;
  PacketPutInt(pkt.get(), tuple_descriptor.size(), 2);

  for (auto col : tuple_descriptor) {
    PacketPutString(pkt.get(), std::get<0>(col));
    // TODO: Table Oid (int32)
    PacketPutInt(pkt.get(), 0, 4);
    // TODO: Attr id of column (int16)
    PacketPutInt(pkt.get(), 0, 2);
    // Field data type (int32)
    PacketPutInt(pkt.get(), std::get<1>(col), 4);
    // Data type size (int16)
    PacketPutInt(pkt.get(), std::get<2>(col), 2);
    // Type modifier (int32)
    PacketPutInt(pkt.get(), -1, 4);
    // Format code for text
    PacketPutInt(pkt.get(), 0, 2);
  }
  responses.push_back(std::move(pkt));
}

void PacketManager::SendDataRows(std::vector<StatementResult> &results,
                                 int colcount, int &rows_affected) {
  if (results.empty() || colcount == 0) return;

  size_t numrows = results.size() / colcount;

  // 1 packet per row
  for (size_t i = 0; i < numrows; i++) {
    std::unique_ptr<OutputPacket> pkt(new OutputPacket());
    pkt->msg_type = NetworkMessageType::DATA_ROW;
    PacketPutInt(pkt.get(), colcount, 2);
    for (int j = 0; j < colcount; j++) {
      auto content = results[i * colcount + j].second;
      if (content.size() == 0) {
        // content is NULL
        PacketPutInt(pkt.get(), NULL_CONTENT_SIZE, 4);
        // no value bytes follow
      } else {
        // length of the row attribute
        PacketPutInt(pkt.get(), content.size(), 4);
        // contents of the row attribute
        PacketPutBytes(pkt.get(), content);
      }
    }
    responses.push_back(std::move(pkt));
  }
  rows_affected = numrows;
}

void PacketManager::CompleteCommand(const std::string &query_type, int rows) {
  std::unique_ptr<OutputPacket> pkt(new OutputPacket());
  pkt->msg_type = NetworkMessageType::COMMAND_COMPLETE;
  std::string tag = query_type;
  /* After Begin, we enter a txn block */
  if (query_type.compare("BEGIN") == 0) {
    txn_state_ = NetworkTransactionStateType::BLOCK;
  }
  /* After commit, we end the txn block */
  else if (query_type.compare("COMMIT") == 0) {
    txn_state_ = NetworkTransactionStateType::IDLE;
  }
  /* After rollback, the txn block is ended */
  else if (!query_type.compare("ROLLBACK")) {
    txn_state_ = NetworkTransactionStateType::IDLE;
  }
  /* the rest are custom status messages for each command */
  else if (!query_type.compare("INSERT")) {
    tag += " 0 " + std::to_string(rows);
  } else {
    tag += " " + std::to_string(rows);
  }
  PacketPutString(pkt.get(), tag);

  responses.push_back(std::move(pkt));
}

/*
 * put_empty_query_response - Informs the client that an empty query was sent
 */
void PacketManager::SendEmptyQueryResponse() {
  std::unique_ptr<OutputPacket> response(new OutputPacket());
  response->msg_type = NetworkMessageType::EMPTY_QUERY_RESPONSE;
  responses.push_back(std::move(response));
}

bool PacketManager::HardcodedExecuteFilter(std::string query_type) {
  // Skip SET
  if (query_type.compare("SET") == 0 || query_type.compare("SHOW") == 0)
    return false;
  // skip duplicate BEGIN
  if (!query_type.compare("BEGIN") &&
      txn_state_ == NetworkTransactionStateType::BLOCK) {
    return false;
  }
  // skip duplicate Commits
  if (!query_type.compare("COMMIT") &&
      txn_state_ == NetworkTransactionStateType::IDLE)
    return false;
  // skip duplicate Rollbacks
  if (!query_type.compare("ROLLBACK") &&
      txn_state_ == NetworkTransactionStateType::IDLE)
    return false;
  return true;
}

// The Simple Query Protocol
void PacketManager::ExecQueryMessage(InputPacket *pkt, const size_t thread_id) {
  std::string q_str;
  PacketGetString(pkt, pkt->len, q_str);

  std::vector<std::string> queries;
  boost::split(queries, q_str, boost::is_any_of(";"));

  if (queries.size() == 1) {
    SendEmptyQueryResponse();
    SendReadyForQuery(txn_state_);
    return;
  }

  for (auto query : queries) {
    // iterate till before the empty string after the last ';'
    if (query != queries.back()) {
      if (query.empty()) {
        SendEmptyQueryResponse();
        SendReadyForQuery(NetworkTransactionStateType::IDLE);
        return;
      }

      std::vector<StatementResult> result;
      std::vector<FieldInfo> tuple_descriptor;
      std::string error_message;
      int rows_affected;

      // execute the query using tcop
      auto status = traffic_cop_->ExecuteStatement(
          query, result, tuple_descriptor, rows_affected, error_message,
          thread_id);

      // check status
      if (status == ResultType::FAILURE) {
        SendErrorResponse(
            {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
        break;
      }

      // send the attribute names
      PutTupleDescriptor(tuple_descriptor);

      // send the result rows
      SendDataRows(result, tuple_descriptor.size(), rows_affected);

      // TODO: should change to query_type
      CompleteCommand(query, rows_affected);
    } else if (queries.size() == 1) {
      // just a ';' sent
      SendEmptyQueryResponse();
    }
  }

  // PAVLO: 2017-01-15
  // There used to be code here that would invoke this method passing
  // in NetworkMessageType::READY_FOR_QUERY as the argument. But when
  // I switched to strong types, this obviously doesn't work. So I
  // switched it to be NetworkTransactionStateType::IDLE. I don't know
  // we just don't always send back the internal txn state?
  SendReadyForQuery(NetworkTransactionStateType::IDLE);
}

/*
 * exec_parse_message - handle PARSE message
 */
void PacketManager::ExecParseMessage(InputPacket *pkt) {
  std::string error_message, statement_name, query_string, query_type;
  GetStringToken(pkt, statement_name);

  // Read prepare statement name
  // Read query string
  GetStringToken(pkt, query_string);
  skipped_stmt_ = false;
  Statement::ParseQueryType(query_string, query_type);

  // For an empty query or a query to be filtered, just send parse complete
  // response and don't execute
  if (query_string == "" || HardcodedExecuteFilter(query_type) == false) {
    skipped_stmt_ = true;
    skipped_query_string_ = std::move(query_string);
    skipped_query_type_ = std::move(query_type);

    // Send Parse complete response
    std::unique_ptr<OutputPacket> response(new OutputPacket());
    response->msg_type = NetworkMessageType::PARSE_COMPLETE;
    responses.push_back(std::move(response));
    return;
  }

  // Prepare statement
  std::shared_ptr<Statement> statement(nullptr);

  LOG_DEBUG("PrepareStatement[%s] => %s", statement_name.c_str(),
            query_string.c_str());

  statement = traffic_cop_->PrepareStatement(statement_name, query_string,
                                             error_message);
  if (statement.get() == nullptr) {
    skipped_stmt_ = true;
    SendErrorResponse(
        {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
    LOG_TRACE("ExecParse Error");
    return;
  }

  // Read number of params
  int num_params = PacketGetInt(pkt, 2);

  // Read param types
  std::vector<int32_t> param_types(num_params);
  auto type_buf_begin = pkt->Begin() + pkt->ptr;
  auto type_buf_len = ReadParamType(pkt, num_params, param_types);

  // Cache the received query
  bool unnamed_query = statement_name.empty();
  statement->SetParamTypes(param_types);

  // Stat
  if (FLAGS_stats_mode != STATS_TYPE_INVALID) {
    // Make a copy of param types for stat collection
    stats::QueryMetric::QueryParamBuf query_type_buf;
    query_type_buf.len = type_buf_len;
    query_type_buf.buf = PacketCopyBytes(type_buf_begin, type_buf_len);

    // Unnamed statement
    if (unnamed_query) {
      unnamed_stmt_param_types_ = query_type_buf;
    } else {
      statement_param_types_[statement_name] = query_type_buf;
    }
  }

  // Unnamed statement
  if (unnamed_query) {
    unnamed_statement_ = statement;
  } else {
    auto entry = std::make_pair(statement_name, statement);
    statement_cache_.insert(entry);
    for (auto table_id : statement->GetReferencedTables()) {
      table_statement_cache_[table_id].push_back(statement.get());
    }
  }
  // Send Parse complete response
  std::unique_ptr<OutputPacket> response(new OutputPacket());
  response->msg_type = NetworkMessageType::PARSE_COMPLETE;
  responses.push_back(std::move(response));
}

void PacketManager::ExecBindMessage(InputPacket *pkt) {
  std::string portal_name, statement_name;
  // BIND message
  GetStringToken(pkt, portal_name);
  GetStringToken(pkt, statement_name);

  if (skipped_stmt_) {
    // send bind complete
    std::unique_ptr<OutputPacket> response(new OutputPacket());
    response->msg_type = NetworkMessageType::BIND_COMPLETE;
    responses.push_back(std::move(response));
    return;
  }

  // Read parameter format
  int num_params_format = PacketGetInt(pkt, 2);
  std::vector<int16_t> formats(num_params_format);

  auto format_buf_begin = pkt->Begin() + pkt->ptr;
  auto format_buf_len = ReadParamFormat(pkt, num_params_format, formats);

  int num_params = PacketGetInt(pkt, 2);
  // error handling
  if (num_params_format != num_params) {
    std::string error_message =
        "Malformed request: num_params_format is not equal to num_params";
    SendErrorResponse(
        {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
    return;
  }

  // Get statement info generated in PARSE message
  std::shared_ptr<Statement> statement;
  stats::QueryMetric::QueryParamBuf param_type_buf;

  // UNNAMED STATEMENT
  if (statement_name.empty()) {
    statement = unnamed_statement_;
    param_type_buf = unnamed_stmt_param_types_;

    // Check unnamed statement
    if (statement.get() == nullptr) {
      std::string error_message = "Invalid unnamed statement";
      LOG_ERROR("%s", error_message.c_str());
      SendErrorResponse(
          {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
      return;
    }
    // NAMED STATEMENT
  } else {
    auto statement_cache_itr = statement_cache_.find(statement_name);
    if (statement_cache_itr != statement_cache_.end()) {
      statement = *statement_cache_itr;
      param_type_buf = statement_param_types_[statement_name];
    }
    // Did not find statement with same name
    else {
      std::string error_message = "The prepared statement does not exist";
      LOG_ERROR("%s", error_message.c_str());
      SendErrorResponse(
          {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
      return;
    }
  }

  const auto &query_string = statement->GetQueryString();
  const auto &query_type = statement->GetQueryType();

  // check if the loaded statement needs to be skipped
  skipped_stmt_ = false;
  if (HardcodedExecuteFilter(query_type) == false) {
    skipped_stmt_ = true;
    skipped_query_string_ = query_string;
    std::unique_ptr<OutputPacket> response(new OutputPacket());
    // Send Bind complete response
    response->msg_type = NetworkMessageType::BIND_COMPLETE;
    responses.push_back(std::move(response));
    return;
  }

  // Check whether somebody wants us to generate a new query plan
  // for this prepared statement
  if (statement->GetNeedsPlan()) {
    ReplanPreparedStatement(statement.get());
  }

  // Group the parameter types and the parameters in this vector
  std::vector<std::pair<int, std::string>> bind_parameters(num_params);
  std::vector<type::Value> param_values(num_params);

  auto param_types = statement->GetParamTypes();

  auto val_buf_begin = pkt->Begin() + pkt->ptr;
  auto val_buf_len = ReadParamValue(pkt, num_params, param_types,
                                    bind_parameters, param_values, formats);

  int format_codes_number = PacketGetInt(pkt, 2);
  LOG_TRACE("format_codes_number: %d", format_codes_number);
  // Set the result-column format code
  if (format_codes_number == 0) {
    // using the default text format
    result_format_ =
        std::move(std::vector<int>(statement->GetTupleDescriptor().size(), 0));
  } else if (format_codes_number == 1) {
    // get the format code from packet
    auto result_format = PacketGetInt(pkt, 2);
    result_format_ = std::move(std::vector<int>(
        statement->GetTupleDescriptor().size(), result_format));
  } else {
    // get the format code for each column
    result_format_.clear();
    for (int format_code_idx = 0; format_code_idx < format_codes_number;
         ++format_code_idx) {
      result_format_.push_back(PacketGetInt(pkt, 2));
      LOG_TRACE("format code: %d", *result_format_.rbegin());
    }
  }

  if (param_values.size() > 0) {
    statement->GetPlanTree()->SetParameterValues(&param_values);
    // Instead of tree traversal, we should put param values in the
    // executor context.
  }

  std::shared_ptr<stats::QueryMetric::QueryParams> param_stat(nullptr);
  if (FLAGS_stats_mode != STATS_TYPE_INVALID && num_params > 0) {
    // Make a copy of format for stat collection
    stats::QueryMetric::QueryParamBuf param_format_buf;
    param_format_buf.len = format_buf_len;
    param_format_buf.buf = PacketCopyBytes(format_buf_begin, format_buf_len);
    PL_ASSERT(format_buf_len > 0);

    // Make a copy of value for stat collection
    stats::QueryMetric::QueryParamBuf param_val_buf;
    param_val_buf.len = val_buf_len;
    param_val_buf.buf = PacketCopyBytes(val_buf_begin, val_buf_len);
    PL_ASSERT(val_buf_len > 0);

    param_stat.reset(new stats::QueryMetric::QueryParams(
        param_format_buf, param_type_buf, param_val_buf, num_params));
  }

  // Construct a portal.
  // Notice that this will move param_values so no value will be left there.
  auto portal =
      new Portal(portal_name, statement, std::move(param_values), param_stat);
  std::shared_ptr<Portal> portal_reference(portal);

  auto itr = portals_.find(portal_name);
  // Found portal name in portal map
  if (itr != portals_.end()) {
    itr->second = portal_reference;
  }
  // Create a new entry in portal map
  else {
    portals_.insert(std::make_pair(portal_name, portal_reference));
  }
  // send bind complete
  std::unique_ptr<OutputPacket> response(new OutputPacket());
  response->msg_type = NetworkMessageType::BIND_COMPLETE;
  responses.push_back(std::move(response));
}

size_t PacketManager::ReadParamType(InputPacket *pkt, int num_params,
                                    std::vector<int32_t> &param_types) {
  auto begin = pkt->ptr;
  // get the type of each parameter
  for (int i = 0; i < num_params; i++) {
    int param_type = PacketGetInt(pkt, 4);
    param_types[i] = param_type;
  }
  auto end = pkt->ptr;
  return end - begin;
}

size_t PacketManager::ReadParamFormat(InputPacket *pkt, int num_params_format,
                                      std::vector<int16_t> &formats) {
  auto begin = pkt->ptr;
  // get the format of each parameter
  for (int i = 0; i < num_params_format; i++) {
    formats[i] = PacketGetInt(pkt, 2);
  }
  auto end = pkt->ptr;
  return end - begin;
}

// For consistency, this function assumes the input vectors has the correct size
size_t PacketManager::ReadParamValue(
    InputPacket *pkt, int num_params, std::vector<int32_t> &param_types,
    std::vector<std::pair<int, std::string>> &bind_parameters,
    std::vector<type::Value> &param_values, std::vector<int16_t> &formats) {
  auto begin = pkt->ptr;
  ByteBuf param;
  for (int param_idx = 0; param_idx < num_params; param_idx++) {
    int param_len = PacketGetInt(pkt, 4);
    // BIND packet NULL parameter case
    if (param_len == -1) {
      // NULL mode
      auto peloton_type = PostgresValueTypeToPelotonValueType(
          static_cast<PostgresValueType>(param_types[param_idx]));
      bind_parameters[param_idx] =
          std::make_pair(peloton_type, std::string(""));
      param_values[param_idx] =
          type::ValueFactory::GetNullValueByType(peloton_type);
    } else {
      PacketGetBytes(pkt, param_len, param);

      if (formats[param_idx] == 0) {
        // TEXT mode
        std::string param_str = std::string(std::begin(param), std::end(param));
        bind_parameters[param_idx] =
            std::make_pair(type::Type::VARCHAR, param_str);
        if (PostgresValueTypeToPelotonValueType(
                (PostgresValueType)param_types[param_idx]) ==
            type::Type::VARCHAR) {
          param_values[param_idx] =
              type::ValueFactory::GetVarcharValue(param_str);
        } else {
          param_values[param_idx] =
              (type::ValueFactory::GetVarcharValue(param_str))
                  .CastAs(PostgresValueTypeToPelotonValueType(
                      (PostgresValueType)param_types[param_idx]));
        }
        PL_ASSERT(param_values[param_idx].GetTypeId() != type::Type::INVALID);
      } else {
        // BINARY mode
        switch (static_cast<PostgresValueType>(param_types[param_idx])) {
          case PostgresValueType::INTEGER: {
            int int_val = 0;
            for (size_t i = 0; i < sizeof(int); ++i) {
              int_val = (int_val << 8) | param[i];
            }
            bind_parameters[param_idx] =
                std::make_pair(type::Type::INTEGER, std::to_string(int_val));
            param_values[param_idx] =
                type::ValueFactory::GetIntegerValue(int_val).Copy();
            break;
          }
          case PostgresValueType::BIGINT: {
            int64_t int_val = 0;
            for (size_t i = 0; i < sizeof(int64_t); ++i) {
              int_val = (int_val << 8) | param[i];
            }
            bind_parameters[param_idx] =
                std::make_pair(type::Type::BIGINT, std::to_string(int_val));
            param_values[param_idx] =
                type::ValueFactory::GetBigIntValue(int_val).Copy();
            break;
          }
          case PostgresValueType::DOUBLE: {
            double float_val = 0;
            unsigned long buf = 0;
            for (size_t i = 0; i < sizeof(double); ++i) {
              buf = (buf << 8) | param[i];
            }
            PL_MEMCPY(&float_val, &buf, sizeof(double));
            bind_parameters[param_idx] =
                std::make_pair(type::Type::DECIMAL, std::to_string(float_val));
            param_values[param_idx] =
                type::ValueFactory::GetDecimalValue(float_val).Copy();
            break;
          }
          case PostgresValueType::VARBINARY: {
            bind_parameters[param_idx] = std::make_pair(
                type::Type::VARBINARY,
                std::string(reinterpret_cast<char *>(&param[0]), param_len));
            param_values[param_idx] = type::ValueFactory::GetVarbinaryValue(
                &param[0], param_len, true);
            break;
          }
          default: {
            LOG_ERROR("Do not support data type: %d", param_types[param_idx]);
            break;
          }
        }
        PL_ASSERT(param_values[param_idx].GetTypeId() != type::Type::INVALID);
      }
    }
  }
  auto end = pkt->ptr;
  return end - begin;
}

bool PacketManager::ExecDescribeMessage(InputPacket *pkt) {
  if (skipped_stmt_) {
    // send 'no-data' message
    std::unique_ptr<OutputPacket> response(new OutputPacket());
    response->msg_type = NetworkMessageType::NO_DATA_RESPONSE;
    responses.push_back(std::move(response));
    return true;
  }

  ByteBuf mode;
  std::string portal_name;
  PacketGetBytes(pkt, 1, mode);
  GetStringToken(pkt, portal_name);
  if (mode[0] == 'P') {
    LOG_TRACE("Describe a portal");
    auto portal_itr = portals_.find(portal_name);

    // TODO: error handling here
    // Ahmed: This is causing the continuously running thread
    // Changed the function signature to return boolean
    // when false is returned, the connection is closed
    if (portal_itr == portals_.end()) {
      LOG_ERROR("Did not find portal : %s", portal_name.c_str());
      std::vector<FieldInfo> tuple_descriptor;
      PutTupleDescriptor(tuple_descriptor);
      return false;
    }

    auto portal = portal_itr->second;
    if (portal == nullptr) {
      LOG_ERROR("Portal does not exist : %s", portal_name.c_str());
      std::vector<FieldInfo> tuple_descriptor;
      PutTupleDescriptor(tuple_descriptor);
      return false;
    }

    auto statement = portal->GetStatement();
    PutTupleDescriptor(statement->GetTupleDescriptor());
  } else {
    LOG_TRACE("Describe a prepared statement");
  }
  return true;
}

void PacketManager::ExecExecuteMessage(InputPacket *pkt, const size_t thread_id) {
  // EXECUTE message
  std::vector<StatementResult> results;
  std::string error_message, portal_name;
  int rows_affected = 0;
  GetStringToken(pkt, portal_name);

  // covers weird JDBC edge case of sending double BEGIN statements. Don't
  // execute them
  if (skipped_stmt_) {
    if (skipped_query_string_ == "") {
      SendEmptyQueryResponse();
    } else {
      CompleteCommand(skipped_query_type_, rows_affected);
    }
    skipped_stmt_ = false;
    return;
  }

  auto portal = portals_[portal_name];
  if (portal.get() == nullptr) {
    LOG_ERROR("Did not find portal : %s", portal_name.c_str());
    SendErrorResponse(
        {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
    SendReadyForQuery(txn_state_);
    return;
  }

  auto statement = portal->GetStatement();
  const auto &query_type = statement->GetQueryType();

  auto param_stat = portal->GetParamStat();
  if (statement.get() == nullptr) {
    LOG_ERROR("Did not find statement in portal : %s", portal_name.c_str());
    SendErrorResponse(
        {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
    SendReadyForQuery(txn_state_);
    return;
  }

  auto statement_name = statement->GetStatementName();
  bool unnamed = statement_name.empty();
  auto param_values = portal->GetParameters();

  auto status = traffic_cop_->ExecuteStatement(
      statement, param_values, unnamed, param_stat, result_format_, results,
      rows_affected, error_message,
      thread_id);

  switch (status) {
    case ResultType::FAILURE:
      LOG_ERROR("Failed to execute: %s", error_message.c_str());
      SendErrorResponse(
          {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}});
      return;
    case ResultType::ABORTED:
      if (query_type != "ROLLBACK") {
        LOG_DEBUG("Failed to execute: Conflicting txn aborted");
        // Send an error response if the abort is not due to ROLLBACK query
        SendErrorResponse({{NetworkMessageType::SQLSTATE_CODE_ERROR,
                            SqlStateErrorCodeToString(
                                SqlStateErrorCode::SERIALIZATION_ERROR)}});
      }
      return;
    default: {
      auto tuple_descriptor = statement->GetTupleDescriptor();
      SendDataRows(results, tuple_descriptor.size(), rows_affected);
      CompleteCommand(query_type, rows_affected);
      return;
    }
  }
}

void PacketManager::ExecCloseMessage(InputPacket *pkt) {
  uchar close_type = 0;
  std::string name;
  PacketGetByte(pkt, close_type);
  PacketGetString(pkt, 0, name);
  bool is_unnamed = (name.size() == 0) ? true : false;
  switch (close_type) {
    case 'S':
      LOG_TRACE("Deleting statement %s from cache", name.c_str());
      if (is_unnamed) {
        unnamed_statement_.reset();
      } else {
        // TODO: Invalidate table_statement_cache!
        statement_cache_.delete_key(name);
      }
      break;
    case 'P': {
      LOG_TRACE("Deleting portal %s from cache", name.c_str());
      auto portal_itr = portals_.find(name);
      if (portal_itr != portals_.end()) {
        // delete portal if it exists
        portals_.erase(portal_itr);
      }
      break;
    }
    default:
      // do nothing, simply send close complete
      break;
  }
  // Send close complete response
  std::unique_ptr<OutputPacket> response(new OutputPacket());
  response->msg_type = NetworkMessageType::CLOSE_COMPLETE;
  responses.push_back(std::move(response));
}

/*
 * process_packet - Main switch block; process incoming packets,
 *  Returns false if the session needs to be closed.
 */
bool PacketManager::ProcessPacket(InputPacket *pkt, const size_t thread_id) {
  LOG_TRACE("Message type: %c", static_cast<unsigned char>(pkt->msg_type));
  // We don't set force_flush to true for `PBDE` messages because they're
  // part of the extended protocol. Buffer responses and don't flush until
  // we see a SYNC
  switch (pkt->msg_type) {
    case NetworkMessageType::SIMPLE_QUERY_COMMAND: {
      LOG_TRACE("SIMPLE_QUERY_COMMAND");
      ExecQueryMessage(pkt, thread_id);
      force_flush = true;
    } break;
    case NetworkMessageType::PARSE_COMMAND: {
      LOG_TRACE("PARSE_COMMAND");
      ExecParseMessage(pkt);
    } break;
    case NetworkMessageType::BIND_COMMAND: {
      LOG_TRACE("BIND_COMMAND");
      ExecBindMessage(pkt);
    } break;
    case NetworkMessageType::DESCRIBE_COMMAND: {
      LOG_TRACE("DESCRIBE_COMMAND");
      return ExecDescribeMessage(pkt);
    } break;
    case NetworkMessageType::EXECUTE_COMMAND: {
      LOG_TRACE("EXECUTE_COMMAND");
      ExecExecuteMessage(pkt, thread_id);
    } break;
    case NetworkMessageType::SYNC_COMMAND: {
      LOG_TRACE("SYNC_COMMAND");
      SendReadyForQuery(txn_state_);
      force_flush = true;
    } break;
    case NetworkMessageType::CLOSE_COMMAND: {
      LOG_TRACE("CLOSE_COMMAND");
      ExecCloseMessage(pkt);
    } break;
    case NetworkMessageType::TERMINATE_COMMAND: {
      LOG_TRACE("TERMINATE_COMMAND");
      force_flush = true;
      return false;
    } break;
    case NetworkMessageType::NULL_COMMAND: {
      LOG_TRACE("NULL");
      force_flush = true;
      return false;
    } break;
    default: {
      LOG_ERROR("Packet type not supported yet: %d (%c)",
                static_cast<int>(pkt->msg_type),
                static_cast<unsigned char>(pkt->msg_type));
    }
  }
  return true;
}

/*
 * send_error_response - Sends the passed string as an error response.
 *    For now, it only supports the human readable 'M' message body
 */
void PacketManager::SendErrorResponse(
    std::vector<std::pair<NetworkMessageType, std::string>> error_status) {
  std::unique_ptr<OutputPacket> pkt(new OutputPacket());
  pkt->msg_type = NetworkMessageType::ERROR_RESPONSE;

  for (auto entry : error_status) {
    PacketPutByte(pkt.get(), static_cast<unsigned char>(entry.first));
    PacketPutString(pkt.get(), entry.second);
  }

  // put null terminator
  PacketPutByte(pkt.get(), 0);

  // don't care if write finished or not, we are closing anyway
  responses.push_back(std::move(pkt));
}

void PacketManager::SendReadyForQuery(NetworkTransactionStateType txn_status) {
  std::unique_ptr<OutputPacket> pkt(new OutputPacket());
  pkt->msg_type = NetworkMessageType::READY_FOR_QUERY;

  PacketPutByte(pkt.get(), static_cast<unsigned char>(txn_status));

  responses.push_back(std::move(pkt));
}

void PacketManager::Reset() {
  client_.Reset();
  is_started = false;
  force_flush = false;

  responses.clear();
  unnamed_statement_.reset();
  result_format_.clear();
  txn_state_ = NetworkTransactionStateType::IDLE;
  skipped_stmt_ = false;
  skipped_query_string_.clear();
  skipped_query_type_.clear();

  statement_cache_.clear();
  table_statement_cache_.clear();
  portals_.clear();
  pkt_cntr_ = 0;

  traffic_cop_->Reset();
}

}  // End wire namespace
}  // End peloton namespace

ext: cpp

max_stars_repo_name: rntlqvnf/peloton

max_issues_repo_name: rntlqvnf/peloton

max_forks_repo_name: rntlqvnf/peloton


text:
#include <iostream>
#include <string>
#include <algorithm>
#include <utility> // std::pair, std::make_pair
#include <cmath> // float comparison
#include <limits>
#include <cstdint>  // for std::uint8_t

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "persistent_cohomology"
#include <boost/test/unit_test.hpp>

#include <gudhi/graph_simplicial_complex.h>
#include <gudhi/reader_utils.h>
#include <gudhi/Simplex_tree.h>
#include <gudhi/Persistent_cohomology.h>

using namespace Gudhi;
using namespace Gudhi::persistent_cohomology;
using namespace boost::unit_test;

typedef Simplex_tree<> typeST;

std::string test_rips_persistence(int coefficient, int min_persistence) {
  // file is copied in CMakeLists.txt
  std::ifstream simplex_tree_stream;
  simplex_tree_stream.open("simplex_tree_file_for_unit_test.txt");
  typeST st;
  simplex_tree_stream >> st;
  simplex_tree_stream.close();

  // Display the Simplex_tree
  std::cout << "The complex contains " << st.num_simplices() << " simplices" << " - dimension= " << st.dimension()
      << std::endl;

  // Check
  BOOST_CHECK(st.num_simplices() == 98);
  BOOST_CHECK(st.dimension() == 3);

  // Sort the simplices in the order of the filtration
  st.initialize_filtration();

  // Compute the persistence diagram of the complex
  Persistent_cohomology<Simplex_tree<>, Field_Zp> pcoh(st);

  pcoh.init_coefficients( coefficient );  // initializes the coefficient field for homology
  // Check infinite rips
  pcoh.compute_persistent_cohomology( min_persistence );  // Minimal lifetime of homology feature to be recorded.
  std::ostringstream ossInfinite;

  pcoh.output_diagram(ossInfinite);
  std::string strInfinite = ossInfinite.str();
  return strInfinite;
}

void test_rips_persistence_in_dimension(int dimension) {
  std::string value0("  0 0.02 1.12");
  std::string value1("  0 0.03 1.13");
  std::string value2("  0 0.04 1.14");
  std::string value3("  0 0.05 1.15");
  std::string value4("  0 0.06 1.16");
  std::string value5("  0 0.07 1.17");
  std::string value6("  0 0.08 1.18");
  std::string value7("  0 0.09 1.19");
  std::string value8("  0 0 inf"    );
  std::string value9("  0 0.01 inf" );

  value0.insert(0,std::to_string(dimension));
  value1.insert(0,std::to_string(dimension));
  value2.insert(0,std::to_string(dimension));
  value3.insert(0,std::to_string(dimension));
  value4.insert(0,std::to_string(dimension));
  value5.insert(0,std::to_string(dimension));
  value6.insert(0,std::to_string(dimension));
  value7.insert(0,std::to_string(dimension));
  value8.insert(0,std::to_string(dimension));
  value9.insert(0,std::to_string(dimension));

  std::cout << "********************************************************************" << std::endl;
  std::cout << "TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=" << dimension << " MIN_PERS=0" << std::endl;

  std::string str_rips_persistence = test_rips_persistence(dimension, 0);
  std::cout << str_rips_persistence << std::endl;

  BOOST_CHECK(str_rips_persistence.find(value0) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value1) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value2) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value3) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value4) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value5) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value6) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value7) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found
  std::cout << "str_rips_persistence=" << str_rips_persistence << std::endl;

  std::cout << "********************************************************************" << std::endl;
  std::cout << "TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=" << dimension << " MIN_PERS=1" << std::endl;

  str_rips_persistence = test_rips_persistence(dimension, 1);

  BOOST_CHECK(str_rips_persistence.find(value0) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value1) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value2) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value3) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value4) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value5) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value6) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value7) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found
  std::cout << "str_rips_persistence=" << str_rips_persistence << std::endl;

  std::cout << "********************************************************************" << std::endl;
  std::cout << "TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=" << dimension << " MIN_PERS=2" << std::endl;

  str_rips_persistence = test_rips_persistence(dimension, 2);

  BOOST_CHECK(str_rips_persistence.find(value0) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value1) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value2) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value3) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value4) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value5) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value6) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value7) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found
  std::cout << "str_rips_persistence=" << str_rips_persistence << std::endl;

  std::cout << "********************************************************************" << std::endl;
  std::cout << "TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=" << dimension << " MIN_PERS=Inf" << std::endl;

  str_rips_persistence = test_rips_persistence(dimension, (std::numeric_limits<int>::max)());

  BOOST_CHECK(str_rips_persistence.find(value0) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value1) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value2) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value3) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value4) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value5) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value6) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value7) == std::string::npos); // Check not found
  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found
  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found
  std::cout << "str_rips_persistence=" << str_rips_persistence << std::endl;
}

BOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_1 )
{
  test_rips_persistence_in_dimension(1);
}

BOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_2 )
{
  test_rips_persistence_in_dimension(2);
}

BOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_3 )
{
  test_rips_persistence_in_dimension(3);
}

BOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_5 )
{
  test_rips_persistence_in_dimension(5);
}

// TODO(VR): not working from 6
// std::string str_rips_persistence = test_rips_persistence(6, 0);
// TODO(VR): division by zero
// std::string str_rips_persistence = test_rips_persistence(0, 0);

/** SimplexTree minimal options to test the limits.
 *
 * Maximum number of simplices to compute persistence is <CODE>std::numeric_limits<std::uint8_t>::max()<\CODE> = 256.*/
struct MiniSTOptions {
  typedef linear_indexing_tag Indexing_tag;
  typedef short Vertex_handle;
  typedef double Filtration_value;
  // Maximum number of simplices to compute persistence is 2^8 - 1 = 255. One is reserved for null_key
  typedef std::uint8_t Simplex_key;
  static const bool store_key = true;
  static const bool store_filtration = false;
  static const bool contiguous_vertices = false;
};

using Mini_simplex_tree = Gudhi::Simplex_tree<MiniSTOptions>;
using Mini_st_persistence =
    Gudhi::persistent_cohomology::Persistent_cohomology<Mini_simplex_tree, Gudhi::persistent_cohomology::Field_Zp>;

BOOST_AUTO_TEST_CASE( persistence_constructor_exception )
{
  Mini_simplex_tree st;

  // To make number of simplices = 255
  const short simplex_0[] = {0, 1, 2, 3, 4, 5, 6, 7};
  st.insert_simplex_and_subfaces(simplex_0);

  // Sort the simplices in the order of the filtration
  st.initialize_filtration();

  BOOST_CHECK(st.num_simplices() <= std::numeric_limits<MiniSTOptions::Simplex_key>::max());
  // Class for homology computation
  BOOST_CHECK_NO_THROW(Mini_st_persistence pcoh(st));

  st.insert_simplex({8});
  BOOST_CHECK(st.num_simplices() > std::numeric_limits<MiniSTOptions::Simplex_key>::max());
  // Class for homology computation
  BOOST_CHECK_THROW(Mini_st_persistence pcoh2(st), std::out_of_range);

}

max_stars_repo_name: jmarino/gudhi-devel

max_issues_repo_name: jmarino/gudhi-devel

max_forks_repo_name: jmarino/gudhi-devel


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

#ifndef BOOST_ASIO_BASIC_STREAMBUF_HPP
#define BOOST_ASIO_BASIC_STREAMBUF_HPP

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

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

#include <boost/asio/detail/push_options.hpp>
#include <algorithm>
#include <limits>
#include <memory>
#include <stdexcept>
#include <streambuf>
#include <vector>
#include <boost/asio/detail/pop_options.hpp>

#include <boost/asio/buffer.hpp>
#include <boost/asio/detail/noncopyable.hpp>

namespace boost {
namespace asio {

/// Automatically resizable buffer class based on std::streambuf.
template <typename Allocator = std::allocator<char> >
class basic_streambuf
  : public std::streambuf,
    private noncopyable
{
public:
#if defined(GENERATING_DOCUMENTATION)
  /// The type used to represent the get area as a list of buffers.
  typedef implementation_defined const_buffers_type;

  /// The type used to represent the put area as a list of buffers.
  typedef implementation_defined mutable_buffers_type;
#else
  typedef boost::asio::const_buffers_1 const_buffers_type;
  typedef boost::asio::mutable_buffers_1 mutable_buffers_type;
#endif

  /// Construct a buffer with a specified maximum size.
  explicit basic_streambuf(
      std::size_t max_size = (std::numeric_limits<std::size_t>::max)(),
      const Allocator& allocator = Allocator())
    : max_size_(max_size),
      buffer_(allocator)
  {
    std::size_t pend = (std::min<std::size_t>)(max_size_, buffer_delta);
    buffer_.resize((std::max<std::size_t>)(pend, 1));
    setg(&buffer_[0], &buffer_[0], &buffer_[0]);
    setp(&buffer_[0], &buffer_[0] + pend);
  }

  /// Return the size of the get area in characters.
  std::size_t size() const
  {
    return pptr() - gptr();
  }

  /// Return the maximum size of the buffer.
  std::size_t max_size() const
  {
    return max_size_;
  }

  /// Get a list of buffers that represents the get area.
  const_buffers_type data() const
  {
    return boost::asio::buffer(boost::asio::const_buffer(gptr(),
          (pptr() - gptr()) * sizeof(char_type)));
  }

  /// Get a list of buffers that represents the put area, with the given size.
  mutable_buffers_type prepare(std::size_t size)
  {
    reserve(size);
    return boost::asio::buffer(boost::asio::mutable_buffer(
          pptr(), size * sizeof(char_type)));
  }

  /// Move the start of the put area by the specified number of characters.
  void commit(std::size_t n)
  {
    if (pptr() + n > epptr())
      n = epptr() - pptr();
    pbump(static_cast<int>(n));
  }

  /// Move the start of the get area by the specified number of characters.
  void consume(std::size_t n)
  {
    if (gptr() + n > pptr())
      n = pptr() - gptr();
    gbump(static_cast<int>(n));
  }

protected:
  enum { buffer_delta = 128 };

  int_type underflow()
  {
    if (gptr() < pptr())
    {
      setg(&buffer_[0], gptr(), pptr());
      return traits_type::to_int_type(*gptr());
    }
    else
    {
      return traits_type::eof();
    }
  }

  int_type overflow(int_type c)
  {
    if (!traits_type::eq_int_type(c, traits_type::eof()))
    {
      if (pptr() == epptr())
      {
        std::size_t buffer_size = pptr() - gptr();
        if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta)
        {
          reserve(max_size_ - buffer_size);
        }
        else
        {
          reserve(buffer_delta);
        }
      }

      *pptr() = traits_type::to_char_type(c);
      pbump(1);
      return c;
    }

    return traits_type::not_eof(c);
  }

  void reserve(std::size_t n)
  {
    // Get current stream positions as offsets.
    std::size_t gnext = gptr() - &buffer_[0];
    std::size_t gend = egptr() - &buffer_[0];
    std::size_t pnext = pptr() - &buffer_[0];
    std::size_t pend = epptr() - &buffer_[0];

    // Check if there is already enough space in the put area.
    if (n <= pend - pnext)
    {
      return;
    }

    // Shift existing contents of get area to start of buffer.
    if (gnext > 0)
    {
      std::rotate(&buffer_[0], &buffer_[0] + gnext, &buffer_[0] + pend);
      gend -= gnext;
      pnext -= gnext;
    }

    // Ensure buffer is large enough to hold at least the specified size.
    if (n > pend - pnext)
    {
      if (n <= max_size_ && pnext <= max_size_ - n)
      {
        buffer_.resize((std::max<std::size_t>)(pnext + n, 1));
      }
      else
      {
        throw std::length_error("boost::asio::streambuf too long");
      }
    }

    // Update stream positions.
    setg(&buffer_[0], &buffer_[0], &buffer_[0] + gend);
    setp(&buffer_[0] + pnext, &buffer_[0] + pnext + n);
  }

private:
  std::size_t max_size_;
  std::vector<char_type, Allocator> buffer_;
};

} // namespace asio
} // namespace boost

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

#endif // BOOST_ASIO_BASIC_STREAMBUF_HPP

ext: hpp

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
#ifndef BOOST_METAPARSE_V1_FOLDL_REJECT_INCOMPLETE_START_WITH_PARSER_HPP
#define BOOST_METAPARSE_V1_FOLDL_REJECT_INCOMPLETE_START_WITH_PARSER_HPP

// Copyright Abel Sinkovics (abel@sinkovics.hu)  2015.
// 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)

#include <boost/metaparse/v1/foldl_reject_incomplete.hpp>
#include <boost/metaparse/v1/get_remaining.hpp>
#include <boost/metaparse/v1/get_position.hpp>
#include <boost/metaparse/v1/get_result.hpp>
#include <boost/metaparse/v1/is_error.hpp>

#include <boost/mpl/eval_if.hpp>

namespace boost
{
  namespace metaparse
  {
    namespace v1
    {
      template <class P, class StateP, class ForwardOp>
      class foldl_reject_incomplete_start_with_parser
      {
      private:
        template <class Res>
        struct apply_unchecked :
          foldl_reject_incomplete<
            P,
            typename get_result<Res>::type,
            ForwardOp
          >::template apply<
            typename get_remaining<Res>::type,
            typename get_position<Res>::type
          >
        {};
      public:
        typedef foldl_reject_incomplete_start_with_parser type;

        template <class S, class Pos>
        struct apply :
          boost::mpl::eval_if<
            typename is_error<typename StateP::template apply<S, Pos> >::type,
            typename StateP::template apply<S, Pos>,
            apply_unchecked<typename StateP::template apply<S, Pos> >
          >
        {};
      };
    }
  }
}

#endif

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
// -*-C++-*-
/*
  (c) Copyright 2003-2005, Hewlett-Packard Development Company, LP

  See the file named COPYING for license details
*/

/** @file
    Variable sized chunks of data; containers for the individual
    records that are stored within, typed, and aligned to 8 byte
    boundaries
*/

#ifndef DATASERIES_EXTENT_H
#define DATASERIES_EXTENT_H

extern "C" {
    char *dataseriesVersion();
}

#include <unistd.h>
#include <inttypes.h>
#include <cstring>

#if defined(__linux__) && defined(__GNUC__) && __GNUC__ >= 2
#  ifdef __i386__
#    if defined __i486__ || defined __pentium__ || defined __pentiumpro__ || defined __pentium4__ || defined __k6__ || defined __k8__ || defined __athlon__
// ok, will get the good byteswap
#    else
// Note that in particular __i386__ is not enough to have defined here
// the swap routine is significantly worse than the i486 version; see
// /usr/include/bits/byteswap.h.  See the test_byteflip part of test.C
// for the performance test, it will fail unless you've selected the
// best of the routines
#      warning "Automatically defining __i486__ on the assumption you have at least that type of CPU"
#      warning "Not doing this gets a much slower byte swap routine"
#      define __i486__ 1
#    endif
#  endif
#  include <byteswap.h>
#endif

#if (defined(__FreeBSD__)||defined(__OpenBSD__)) && defined(__GNUC__) && __GNUC__ >= 2 && (defined(__i486__) || defined (__x86_64__))
#  define bswap_32(x)                                                   \
    (__extension__                                                      \
     ({ register uint32_t bswap32_out, bswap32_in = (x);                \
         __asm__("bswap %0" : "=r" (bswap32_out) : "0" (bswap32_in));   \
         bswap32_out; }))
#endif

#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>

#include <Lintel/CompilerMarkup.hpp>
#include <Lintel/TypeCompat.hpp>

#include <DataSeries/ExtentType.hpp>

// Defined and explained in DataSeriesSink.cpp
extern const int MAX_THREADS;

class ExtentSeries;

/** \brief Stores a sequence of records having the same type.
 *
 * Each @c Extent has two components
 *   - A buffer containing fixed size records.  The size of
 *     each individual record can be determined from the ExtentType,
 *     allowing random access.  Variable32 fields are represented
 *     by a 4 byte index into the string pool.
 *   - A string pool for variable32 fields. */
class Extent : boost::noncopyable, public boost::enable_shared_from_this<Extent> {
  public:
    typedef boost::shared_ptr<Extent> Ptr;

    typedef ExtentType::byte byte;
    typedef ExtentType::int32 int32;
    typedef ExtentType::uint32 uint32;
    typedef ExtentType::int64 int64;
    // G++-3 changed the way vectors work to remove the clear
    // similarity between them and an array; since they could be
    // implemented as a two level lookup (that's still constant time),
    // and using them to get to the byte array is now more difficult,
    // we implement our own to guarentee the assumption that we are
    // really representing a variable sized array of bytes, which is
    // what we want.  Later change to the C++ spec clarified that
    // arrays have to be contiguous, so we could switch back at some point.
    class ByteArray {
      public:
        ByteArray() { beginV = endV = maxV = NULL; }
        ~ByteArray();
        size_t size() const { return endV - beginV; }
        void resize(size_t newsize, bool zero_it = true) {
            size_t oldsize = size();
            if (newsize <= oldsize) {
                // shrink
                endV = beginV + newsize;
            } else if (newsize < static_cast<size_t>(maxV - beginV)) {
                endV = beginV + newsize;
                if (zero_it) {
                    memset(beginV + oldsize,0,newsize - oldsize);
                }
            } else {
                copyResize(newsize, zero_it);
            }
        }
        void clear(); // frees allocated memory
        void reserve(size_t reserve_bytes);
        bool empty() const { return endV == beginV; }
        byte *begin() const { return beginV; };
        byte *begin(size_t offset) const { return beginV + offset; }
        byte *end() const { return endV; };
        byte &operator[] (size_t offset) const { return *(begin(offset)); }

        void swap(ByteArray &with) {
            swap(beginV,with.beginV);
            swap(endV,with.endV);
            swap(maxV,with.maxV);
        }

        typedef byte * iterator;

        // glibc prefers to use mmap to allocate large memory chunks; we
        // allocate and de-allocate those fairly regularly; so we increase
        // the threshold.  This function is automatically called once when
        // we have to resize a bytearray, if you disagree with the defaults,
        // you can call this manually and set the options yourself.
        // if you want to look at the retaining space code again, version
        // d5bb884b572b07590a8131710f01513577e24813, prior to 2007-10-25
        // will have a copy of the old code.
        static void initMallocTuning();
      private:
        void swap(byte * &a, byte * &b) {
            byte *tmp = a;
            a = b;
            b = tmp;
        }

        void copyResize(size_t newsize, bool zero_it);
        byte *beginV, *endV, *maxV;
    };

    /// \cond INTERNAL_ONLY
    const ExtentType::Ptr type;
    /// \endcond

    /** Returns the type of the Extent; reference valid until extent is destroyed. */
    const ExtentType &getType() const FUNC_DEPRECATED {
        return *type;
    }

    /** Returns the type of the Extent */
    const ExtentType::Ptr getTypePtr() const {
        return type;
    }

    /** This constructor creates an @c Extent from raw bytes in
        the external format created by packData.  It will
        Extract the name of the appropriate @c ExtentType from
        the input bytes and look it up in the given @c ExtentTypeLibrary.
        If needs_bitflip is true, it indicates that the endianness
        of the host processor is opposite the endianness of the
        input data. */
    Extent(const ExtentTypeLibrary &library, Extent::ByteArray &packeddata,
           const bool need_bitflip); // TODO: consider deprecating.
    /** Similar to the above constructor, except that the ExtentType is passed explicitly.
        deprecated, just call unpackData directly after making the extent. */
    Extent(const ExtentType &type, Extent::ByteArray &packeddata, const bool need_bitflip) FUNC_DEPRECATED;
    /** Creates an empty @c Extent. */
    Extent(const ExtentType &type) FUNC_DEPRECATED;

    /** Creates an empty @c Extent. */
    Extent(const ExtentType::Ptr type);

    /** Creates an empty @c Extent. */
    Extent(const std::string &xmltype);

    /** Use ExtentSeries::newExtent() instead of this function.  Creates a new empty Extent. If
        series.extent() == NULL, the Extent creation will set the series' extent to the new
        extent.  */
    Extent(ExtentSeries &myseries) FUNC_DEPRECATED;

    /** Destroy the extent, verifies that there are no shared pointers to the extent */
    ~Extent();

    /** Swap the contents of two &c Extent.

        Preconditions:
        - Both Extents must have the same type.

        Provided the preconditions are met, this
        function does not throw. */
    void swap(Extent &with);

    /** Clears the contents of the Extent.  Note that
        there is no way to clear the type. */
    void clear() {
        fixeddata.clear();
        variabledata.clear();
        init();
    }
    /** Returns the total size of the @c Extent in bytes. */
    size_t size() {
        return fixeddata.size() + variabledata.size();
    }

    /** Returns the number of records in this Extent */
    size_t nRecords() {
        return fixeddata.size() / getTypePtr()->fixedrecordsize();
    }

    /// \cond INTERNAL_ONLY
    /** The following are defined by the file format and can't be changed.
        These determine the index of each compression algorithm in the
        compression_algs[] array */
    static const Extent::byte compress_mode_none = 0;
    static const Extent::byte compress_mode_lzo = 1;
    static const Extent::byte compress_mode_zlib = 2;
    static const Extent::byte compress_mode_bz2 = 3;
    static const Extent::byte compress_mode_lzf = 4;
    static const Extent::byte compress_mode_snappy = 5;
    static const Extent::byte compress_mode_lz4 = 6;
    static const Extent::byte compress_mode_lz4hc = 7;
    /// \endcond

    // Should be equal to the number of constants compress_mode_{name}
    // specified above.  Careful: because of the way the compression bit flags
    // are stored in ints, this cannot ever be greater than 16.
    static const int num_comp_algs = 8;

    struct compression_alg
    {
        const char* name;
        int compress_flag;
        bool (*packFunc)( byte*, int32, ByteArray&, int );
        bool (*unpackFunc)( byte*, byte*, int32, int32& );
    };

    /* This array contains the available compression algorithms */
    static compression_alg compression_algs[];

    /* Compress_all is set to the bitwise or of all the compress flags in compression_algs */
    static const int compress_all = ~( INT_MIN >> ( sizeof(INT_MIN)*8 - num_comp_algs ) );

    /** \defgroup Extent_compress Extent::compress
        The compress_flag ints are used to indicate which compression
        algorithms will be tried when converting an Extent
        to its external representation.  Multiple flags can
        be |'ed together and the algorithm that
        yields the best compression will be chosen.  Which
        algorithms are available depends on which libraries
        are found when DataSeries is compiled.  If an algorithm
        which is not supported is requested, it will be ignored.

        \brief converts an Extent to the external representation which is stored
        in files.

        \arg into Output buffer to write the result to.

        \arg compression_modes Specifies which compression algorithms will be
        tried.  The one that yields the smallest result will be selected.

        \arg compression_level must be between 1 and 9 inclusive.  In general larger
        values give better compression but require more time/space.  See the
        documentation of the individual compression schemes for details.

        \arg header_packed If header_packed is not null, *header_packed will recieve
        the pre-compression size of the Extent header.
        \arg fixed_packed If fixed_packed is not null, *fixed_packed will recieve
        the pre-compression size in bytes of the fixed size records.
        \arg variable_packed If variable_packed is not null, *variable_packed
        will recieve the pre-compression size of the string pool.

        \return a "checksum" calculated from the underlying checksums in the packed extent */
    uint32_t packData(Extent::ByteArray &into,
                      uint32_t compression_modes = compress_all,
                      uint32_t compression_level = 9,
                      uint32_t *header_packed = NULL,
                      uint32_t *fixed_packed = NULL,
                      uint32_t *variable_packed = NULL);

    /** Loads an Extent from the external representation.

        \arg need_bitflip Indicates whether the endianness of
        from is the same as the that of the host machine.

        Preconditions:
        - The type of the data must be the type of this Extent.

        Note you can't unpack the same data twice, it may modify the
        input data */
    void unpackData(Extent::ByteArray &from, bool need_bitflip);

    /** Returns true if position is inside the fixed data for this extent, otherwise false */
    bool insideExtentFixed(byte *position) const {
        return position >= fixeddata.begin() && position < fixeddata.end();
    }

    /** Returns the total size in bytes that an Extent created
        using @param from will need.  (This will be the result of size() after
        unpacking.)

        \param from The byte array to use as input
        \param need_bitflip Do we need to flip the byte order when unpacking?
        \param type What type does the raw data represent?

        Preconditions:
        - from must be in the external representation of Extents.
    */
    static uint32_t unpackedSize(Extent::ByteArray &from, bool need_bitflip,
                                 const ExtentType::Ptr type);
    static uint32_t unpackedSize(Extent::ByteArray &from, bool need_bitflip,
                                 const ExtentType &type) FUNC_DEPRECATED {
        return unpackedSize(from, need_bitflip, type.shared_from_this());
    }

    /** Returns the name of the type of the Extent stored in @param from

        \param from What byte array should we get the type for?

        Preconditions:
        - from must be in the external representation of Extents. */
    static const std::string getPackedExtentType(const Extent::ByteArray &from);

    /** All of the pack and unpack functions should be used only through pointers
        which are entered into the compression_alg[] array, and called in
        compressBytes() or uncompressBytes() */

    /// \cond INTERNAL_ONLY
    // most pack routines return false if packing the data with a
    // particular compression algorithm wouldn't gain anything over leaving
    // the data uncompressed (compressBytes does an overall check for this
    // after compression; if into.size > 0, will only code up to that size
    // for the BZ2 and Zlib packing options (LZO doesn't allow this)
    static bool packBZ2(byte *input, int32 inputsize,
                        Extent::ByteArray &into, int compression_level);
    static bool packZLib(byte *input, int32 inputsize,
                         Extent::ByteArray &into, int compression_level);
    static bool packLZO(byte *input, int32 inputsize,
                        Extent::ByteArray &into, int compression_level);
    static bool packLZF(byte *input, int32 inputsize,
                        Extent::ByteArray &into, int compression_level);
    static bool packSnappy(byte *input, int32 inputsize,
                           Extent::ByteArray &into, int compression_level);
    static bool packLZ4(byte *input, int32 inputsize,
                        Extent::ByteArray &into, int compression_level);
    static bool packLZ4HC(byte *input, int32 inputsize,
                          Extent::ByteArray &into, int compression_level);

    // The unpack functions return true iff uncompression completed successfully
    // without errors.
    static bool unpackBZ2( byte* output, byte *input,
                           int32 input_size, int32 &output_size );
    static bool unpackZLib( byte* output, byte *input,
                            int32 input_size, int32 &output_size );
    static bool unpackLZO( byte* output, byte *input,
                           int32 input_size, int32 &output_size );
    static bool unpackLZF( byte* output, byte *input,
                           int32 input_size, int32 &output_size );
    static bool unpackSnappy( byte* output, byte *input,
                              int32 input_size, int32 &output_size );
    static bool unpackLZ4( byte* output, byte *input,
                           int32 input_size, int32 &output_size );

    static inline uint32_t flip4bytes(uint32 v) {
#if defined(bswap_32)
        return bswap_32(v);
#else
        // fastest method on PIII & PA2.0-- see test.C for a bunch of variants
        // that we chose the best will be verified by test.C
        return ((v >> 24) & 0xFF) | ((v>>8) & 0xFF00) |
                ((v & 0xFF00) << 8) | ((v & 0xFF) << 24);
#endif
    }
    static inline void flip4bytes(byte *data) {
        *(uint32_t *)data = flip4bytes(*(uint32_t *)data);
    }
    //
    static inline void flip8bytes(byte *data) {
#if defined(bswap_64)
        *(uint64_t *)data = bswap_64(*(uint64_t *)data);
#else
        uint32 a = *(uint32 *)data;
        uint32 b = *(uint32 *)(data + 4);
        *(uint32 *)(data + 4) = flip4bytes(a);
        *(uint32 *)data = flip4bytes(b);
#endif
    }
    /// \endcond

    // returns true if it successfully read the extent; returns false
    // on eof (with into.size() == 0); aborts otherwise
    // updates offset to the end of the extent
    static bool preadExtent(int fd, off64_t &offset, Extent::ByteArray &into, bool need_bitflip);

    // returns true if it read amount bytes, returns false if it read
    // 0 bytes and eof_ok; aborts otherwise
    static bool checkedPread(int fd, off64_t offset, byte *into, int amount,
                             bool eof_ok = false);

    // The verification checks are the dataseries internal checksums
    // that verify that the files were read correctly.  The
    // pre_uncompress check verifies the checksum over the compressed
    // data.  The post_uncompress check verifies the data after it has
    // been uncompressed, and after some of the transforms
    // (e.g. relative packing) have been applied.  The
    // unpack_variable32 check verifies that
    // Variable32Field::selfcheck() passes for all of the variable32
    // fields.

    // set the environment variable to one or more of:
    // DATASERIES_READ_CHECKS=preuncompress,postuncompress,variable32,all,none
    // This function is automatically called before unpacking the first extent
    // if it hasn't already been called.
    static void setReadChecksFromEnv(bool default_with_env_unset = false);

    /// \cond INTERNAL_ONLY
    // be smart before directly accessing these!  here because making
    // them private and using friend class ExtentSeries::iterator
    // didn't work.
    Extent::ByteArray fixeddata;
    Extent::ByteArray variabledata;

    /// For read-in extents, this will be the filename, for just created
    /// extents this will be in_memory_str.
    std::string extent_source;

    /// Default extent_source
    static const std::string in_memory_str;

    /// For read-in extents, this will be the offset, for just created
    /// extents this will be -1.
    int64_t extent_source_offset;

    // This function is here to verify that we got the right
    // flip4bytes when we compiled DataSeries, it's used by
    // DataSeries/src/test.C
    static void run_flip4bytes(uint32_t *buf, unsigned buflen);

  private:
    // you are responsible for deleting the return buffer
    static Extent::ByteArray *compressBytes(byte *input, int32 input_size,
                                            int compression_modes,
                                            int compression_level, byte *mode);

    static int32 uncompressBytes(byte *into, byte *from,
                                 byte compression_mode, int32 intosize,
                                 int32 fromsize);

    void compactNulls(Extent::ByteArray &fixed_coded);
    void uncompactNulls(Extent::ByteArray &fixed_coded, int32_t &size);
    friend class ExtentSeries;
    void createRecords(unsigned int nrecords); // will leave iterator pointing at the current record
    void init();
    /// \endcond
};

#endif

max_stars_repo_name: sbu-fsl/DataSeries

max_issues_repo_name: yoursunny/DataSeries

max_forks_repo_name: sbu-fsl/DataSeries


text:
#include <boost/filesystem.hpp>
#include <iostream>
#include <ctime>

using namespace boost::filesystem;

int main()
{
  path p{"C:\\Windows\\win.ini"};
  try
  {
    std::time_t t = last_write_time(p);
    std::cout << std::ctime(&t) << '\n';
  }
  catch (filesystem_error &e)
  {
    std::cerr << e.what() << '\n';
  }
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
// BSD 3-Clause License

// Copyright (c) 2021, Chenyu
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:

// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.

// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.

// 3. Neither the name of the copyright holder nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "rbr_sdp_solver.h"

#include <ceres/rotation.h>

#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>

#include <Eigen/Eigenvalues>
#include <Eigen/QR>

#include "bcm_sdp_solver.h"
#include "math/matrix_square_root.h"

namespace gopt {
namespace solver {

RBRSDPSolver::RBRSDPSolver(const size_t n, const size_t block_dim)
    : RBRSDPSolver(n, block_dim, solver::SDPSolverOptions()) {}

RBRSDPSolver::RBRSDPSolver(
    const size_t n, const size_t block_dim,
    const solver::SDPSolverOptions& options)
    : BCMSDPSolver(n, block_dim, options){
  X_ = Eigen::MatrixXd::Identity(dim_ * n, dim_ * n);
}

void RBRSDPSolver::Solve(solver::Summary& summary) {
  double prev_func_val = std::numeric_limits<double>::max();
  double cur_func_val = this->EvaluateFuncVal();
  double duration = 0.0;
  double error = 0.0;

  summary.begin_time = std::chrono::high_resolution_clock::now();
  while (summary.total_iterations_num < sdp_solver_options_.max_iterations) {
    if (sdp_solver_options_.verbose) {
      this->LogToStd(summary.total_iterations_num, prev_func_val, cur_func_val,
                     error, duration);
    }

    if (IsConverge(prev_func_val, cur_func_val, sdp_solver_options_.tolerance, &error)) {
      break;
    }

    // convergence rate? Take it for consideration.
    for (size_t k = 0; k < n_; k++) {
      // Eliminating the k-th row and column from Y to form Bk
      Eigen::MatrixXd B = Eigen::MatrixXd::Zero(3 * (n_ - 1), 3 * (n_ - 1));
      this->ReformingB(k, B);

      // Eliminating the k-th column and all but the k-th row from R to form Wk
      Eigen::MatrixXd W = Eigen::MatrixXd::Zero(3 * (n_ - 1), 3);
      this->ReformingW(k, W);

      Eigen::MatrixXd B_multi_W = B * W;
      Eigen::MatrixXd WtBW = W.transpose() * B_multi_W;

      // FIXME: (chenyu) Solving matrix square root with
      // SVD and LDL^T would generate different result
      Eigen::MatrixXd WtBW_sqrt = MatrixSquareRoot(WtBW);
      // Eigen::MatrixXd WtBW_sqrt =
      // MatrixSquareRootForSemidefinitePositiveMat(WtBW);

      // FIXME: (chenyu) Eigen 3.3.0 is required for the use of
      // CompleteOrthogonalDecomposition<>
      // Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd> cqr(WtBW_sqrt);
      // Eigen::Matrix3d moore_penrose_pseinv = cqr.pseudoInverse();
      Eigen::Matrix3d moore_penrose_pseinv = WtBW_sqrt.inverse();

      // compute S by fixing the error of Equ.(47) in Erikson's paper
      Eigen::MatrixXd S = -B_multi_W * moore_penrose_pseinv;

      // reordering X
      this->ReorderingUnknown(k, B, S);
    }

    summary.total_iterations_num++;
    duration = summary.Duration();

    // Update function value
    prev_func_val = cur_func_val;
    cur_func_val = this->EvaluateFuncVal();
  }

  summary.total_iterations_num++;
  if (sdp_solver_options_.verbose) {
    this->LogToStd(summary.total_iterations_num, prev_func_val, cur_func_val,
                   error, duration);
  }
}

double RBRSDPSolver::EvaluateFuncVal() const {
  return EvaluateFuncVal(X_);
}

double RBRSDPSolver::EvaluateFuncVal(const Eigen::MatrixXd& Y) const {
  return (Q_ * Y).trace();
}

void RBRSDPSolver::ReformingB(const size_t k, Eigen::MatrixXd& B) {
  size_t r = 0, c = 0;  // the row and column index of matrix B

  for (size_t i = 0; i < n_; i++) {
    if (i == k) continue;
    c = 0;
    for (size_t j = 0; j < n_; j++) {
      if (j == k) continue;

      B.block(3 * r, 3 * c, 3, 3) = X_.block(3 * i, 3 * j, 3, 3);
      c++;
    }
    r++;
  }
}

void RBRSDPSolver::ReformingW(const size_t k, Eigen::MatrixXd& W) {
  size_t r = 0;  // row index of matrix W

  for (size_t i = 0; i < n_; i++) {
    if (i == k) continue;

    W.block(3 * r, 0, 3, 3) = Q_.block(3 * i, 3 * k, 3, 3);
    r++;
  }
}

void RBRSDPSolver::ReorderingUnknown(const size_t k, const Eigen::MatrixXd& B,
                                     const Eigen::MatrixXd& S) {
  // Reordering X according to [Algorithm 1] in paper:
  // - Z. Wen, D. Goldfarb, S. Ma, and K. Scheinberg.
  //   Row by row methods for semidefinite programming.
  //   Technical report, Columbia University, 2009. 7

  // Update X(k, k)
  X_.block(3 * k, 3 * k, 3, 3) = Eigen::Matrix3d::Identity();

  // Update the k-th column of Y, except Y(k, k)
  size_t j = 0;  // the j-th block of S
  for (size_t i = 0; i < n_; i++) {
    if (i == k) continue;
    X_.block(3 * i, 3 * k, 3, 3) = S.block(3 * j, 0, 3, 3);
    j++;
  }

  // Update the k-th row of Y, except Y(k, k)
  size_t i = 0;  // the i-th block of S
  for (size_t j = 0; j < n_; j++) {
    if (j == k) continue;
    X_.block(3 * k, 3 * j, 3, 3) = S.block(3 * i, 0, 3, 3).transpose();
    i++;
  }
}

}  // namespace solver
}  // namespace gopt

ext: cc

max_stars_repo_name: AIBluefisher/GraphOptim

max_issues_repo_name: whuaegeanse/GraphOptim

max_forks_repo_name: whuaegeanse/GraphOptim


text:
//--------------------------------------------------------------------------------
//This is a file from Arkengine
//
//
//Copyright (c) arkenthera.All rights reserved.
//
//BasicRenderWindow.cpp
//--------------------------------------------------------------------------------

#include "Core/YumeHeaders.h"
#include "GodRays.h"
#include "Logging/logging.h"
#include "Core/YumeMain.h"
#include "Renderer/YumeLPVCamera.h"
#include <boost/shared_ptr.hpp>

#include "Input/YumeInput.h"

#include "Renderer/YumeTexture2D.h"

#include "Renderer/YumeResourceManager.h"

#include "Engine/YumeEngine.h"

#include "UI/YumeDebugOverlay.h"

#include "Renderer/Light.h"
#include "Renderer/StaticModel.h"
#include "Renderer/Scene.h"

#include "UI/YumeOptionsMenu.h"
#include "Renderer/RenderPass.h"

YUME_DEFINE_ENTRY_POINT(YumeEngine::GodRays);

#define TURNOFF 1
//#define NO_MODEL
//#define OBJECTS_CAST_SHADOW
#define NO_SKYBOX
#define NO_PLANE

namespace YumeEngine
{

	GodRays::GodRays()
		: angle1_(0),
		updown1_(0),
		leftRight1_(0)
	{
		REGISTER_ENGINE_LISTENER;
	}

	GodRays::~GodRays()
	{

	}

	void GodRays::Start()
	{
		YumeResourceManager* rm_ = gYume->pResourceManager;
		YumeMiscRenderer* renderer = gYume->pRenderer;
		Scene* scene = renderer->GetScene();
		YumeCamera* camera = renderer->GetCamera();

		gYume->pInput->AddListener(this);

#ifndef DISABLE_CEF

		optionsMenu_ = new YumeOptionsMenu;
		gYume->pUI->AddUIElement(optionsMenu_);
		optionsMenu_->SetVisible(true);

		overlay_ = new YumeDebugOverlay;
		overlay_->GetBinding("SampleName")->SetValue("Cornell Showcase 2");
		gYume->pUI->AddUIElement(overlay_);
		overlay_->SetVisible(true);

#endif

		MaterialPtr emissiveBlue = YumeAPINew Material;
		emissiveBlue->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0,0,1,1));
		emissiveBlue->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
		emissiveBlue->SetShaderParameter("Roughness",0.001f);
		emissiveBlue->SetShaderParameter("ShadingMode",0);
		emissiveBlue->SetShaderParameter("has_diffuse_tex",false);
		emissiveBlue->SetShaderParameter("has_alpha_tex",false);
		emissiveBlue->SetShaderParameter("has_specular_tex",false);
		emissiveBlue->SetShaderParameter("has_normal_tex",false);
		emissiveBlue->SetShaderParameter("has_roughness_tex",false);

		MaterialPtr emissiveRed = YumeAPINew Material;
		emissiveRed->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0,0,1));
		emissiveRed->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
		emissiveRed->SetShaderParameter("Roughness",0.001f);
		emissiveRed->SetShaderParameter("ShadingMode",0);
		emissiveRed->SetShaderParameter("has_diffuse_tex",false);
		emissiveRed->SetShaderParameter("has_alpha_tex",false);
		emissiveRed->SetShaderParameter("has_specular_tex",false);
		emissiveRed->SetShaderParameter("has_normal_tex",false);
		emissiveRed->SetShaderParameter("has_roughness_tex",false);

		MaterialPtr emissivePink = YumeAPINew Material;
		emissivePink->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0.0784314f,0.576471f,1));
		emissivePink->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
		emissivePink->SetShaderParameter("Roughness",0.001f);
		emissivePink->SetShaderParameter("ShadingMode",0);
		emissivePink->SetShaderParameter("has_diffuse_tex",false);
		emissivePink->SetShaderParameter("has_alpha_tex",false);
		emissivePink->SetShaderParameter("has_specular_tex",false);
		emissivePink->SetShaderParameter("has_normal_tex",false);
		emissivePink->SetShaderParameter("has_roughness_tex",false);

		float boxScale = 0.15f;

		boxBlue = CreateModel("Models/Primitives/box.yume",DirectX::XMFLOAT3(2,5,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(1,1,1));
		boxBlue->SetMaterial(emissiveBlue);
		boxBlue->SetScale(boxScale,boxScale,boxScale);

		boxRed = CreateModel("Models/Primitives/box.yume",DirectX::XMFLOAT3(2,16.2f,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(1,1,1));
		boxRed->SetMaterial(emissiveRed);
		boxRed->SetScale(boxScale,boxScale,boxScale);

		boxPink = CreateModel("Models/Primitives/box.yume",DirectX::XMFLOAT3(-7,8,5),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(1,1,1));
		boxPink->SetMaterial(emissivePink);
		boxPink->SetScale(boxScale,boxScale,boxScale);

		StaticModel* jeyjeyModel = CreateModel("Models/cornell/cornell-empty.yume");

		RenderPass* dp = renderer->GetDefaultPass();
		dp->Load("RenderCalls/Bloom.xml",true);
		dp->Load("RenderCalls/FXAA.xml",true);
		dp->Load("RenderCalls/LensDistortion.xml",true);
		dp->Load("RenderCalls/ShowGBuffer.xml",true);
		dp->DisableRenderCalls("ShowGBuffer");
		dp->DisableRenderCalls("Bloom");

		Light* dirLight = new Light;
		dirLight->SetName("DirLight");
		dirLight->SetType(LT_DIRECTIONAL);
		dirLight->SetPosition(DirectX::XMVectorSet(0,20,0,0));
		dirLight->SetDirection(DirectX::XMVectorSet(0,-1,0,0));
		dirLight->SetRotation(DirectX::XMVectorSet(-1,0,0,0));
		dirLight->SetColor(YumeColor(1,1,1,0));

		scene->AddNode(dirLight);
	}

	void GodRays::MoveCamera(float timeStep)
	{

	}

	void GodRays::HandleUpdate(float timeStep)
	{
		const float YOrbitRadius = 5.f;
		const float ZOrbitRadius = 5.f;
		const float XOrbitRadius = 8;
		angle1_ += M_PI * 0.1f * timeStep;
		updown1_ += M_PI * 0.8f * timeStep;
		leftRight1_ += M_PI * 0.34f * timeStep;

		if(updown1_ > M_PI * 2)
			updown1_ = 0.0f;

		DirectX::XMVECTOR blueRot = DirectX::XMVectorSet(-angle1_,angle1_,0,0);
		DirectX::XMVECTOR bluePos = DirectX::XMVectorAdd(DirectX::XMLoadFloat4(&boxBlue->GetInitialPosition()),DirectX::XMVectorSet(cosf(leftRight1_) * XOrbitRadius,0,sinf(leftRight1_) * ZOrbitRadius,0));

		boxBlue->SetRotation(blueRot);
		boxBlue->SetPosition(bluePos);

		DirectX::XMVECTOR redRot = DirectX::XMVectorSet(-angle1_,angle1_,0,0);
		DirectX::XMVECTOR redPos = DirectX::XMVectorAdd(DirectX::XMLoadFloat4(&boxRed->GetInitialPosition()),DirectX::XMVectorSet(cosf(updown1_) * YOrbitRadius,0,0,0));

		boxRed->SetRotation(redRot);
		boxRed->SetPosition(redPos);

		DirectX::XMVECTOR pinkRot = DirectX::XMVectorSet(-angle1_,angle1_,0,0);
		DirectX::XMVECTOR pinkPos = DirectX::XMVectorAdd(DirectX::XMLoadFloat4(&boxPink->GetInitialPosition()),DirectX::XMVectorSet(0,sinf(leftRight1_) * YOrbitRadius,0,0));

		boxPink->SetRotation(pinkRot);
		boxPink->SetPosition(pinkPos);
	}
	void GodRays::HandleRenderUpdate(float timeStep)
	{

	}

	void GodRays::Setup()
	{
		engineVariants_["GI"] = Dyn_Lpv;
		engineVariants_["WindowWidth"] = 1024;
		engineVariants_["WindowHeight"] = 768;

		BaseApplication::Setup();
	}
}

max_stars_repo_name: rodrigobmg/YumeEngine

max_issues_repo_name: rodrigobmg/YumeEngine

max_forks_repo_name: rodrigobmg/YumeEngine


text:
/*
 * Copyright (C) 2019 Open Source Robotics Foundation
 *
 * 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.
 *
 */

#ifndef IGNITION_GAZEBO_SYSTEMS_MULTICOPTERVELOCITYCONTROL_PARAMETERS_HH_
#define IGNITION_GAZEBO_SYSTEMS_MULTICOPTERVELOCITYCONTROL_PARAMETERS_HH_

#include <Eigen/Geometry>
#include <vector>

#include "ignition/gazebo/config.hh"

namespace ignition
{
namespace gazebo
{
// Inline bracket to help doxygen filtering.
inline namespace IGNITION_GAZEBO_VERSION_NAMESPACE {
namespace systems
{
namespace multicopter_control
{
  /// \brief A struct that holds various properties of a rotor
  struct Rotor
  {
    /// \brief The angle formed on the xy plane by the vector going from the
    /// the center of mass to the rotor. The angle is measured from the +x axis
    /// of the body frame.
    // cppcheck-suppress unusedStructMember
    double angle;
    /// \brief The length of the vector going from the center of mass to the
    /// rotor.
    // cppcheck-suppress unusedStructMember
    double armLength;
    /// \brief A constant that multiplies with the square of the rotor's
    /// velocity to compute its thrust.
    // cppcheck-suppress unusedStructMember
    double forceConstant;
    /// \brief A constant the multiplies with the rotor's thrust to compute its
    /// moment.
    // cppcheck-suppress unusedStructMember
    double momentConstant;
    /// \brief Direction of rotation of the rotor. +1 is counterclockwise and -1
    /// is clockwise.
    // cppcheck-suppress unusedStructMember
    int direction;
  };

  /// \brief A collection of Rotor objects
  using RotorConfiguration = std::vector<Rotor>;

  /// \brief A struct that holds properties of the vehicle such as mass,
  /// inertia and rotor configuration. Gravity is also included even though it's
  /// not a parameter unique to the vehicle
  struct VehicleParameters
  {
    /// \brief Total mass of the vehicle
    // cppcheck-suppress unusedStructMember
    double mass;
    /// \brief Moment of inertia matrix of the vehicle
    Eigen::Matrix3d inertia;
    /// \brief Gravity vector
    Eigen::Vector3d gravity;
    /// \brief A collection of Rotor objects that specifiy various properties of
    /// the rotors in the vehicle
    RotorConfiguration rotorConfiguration;
  };

  /// \brief Noise parameters used when computing frame data. These are all
  /// assumed to be gaussian.
  struct NoiseParameters
  {
    Eigen::Vector3d linearVelocityMean;
    Eigen::Vector3d linearVelocityStdDev;
    Eigen::Vector3d angularVelocityMean;
    Eigen::Vector3d angularVelocityStdDev;
  };

}  // namespace multicopter_control
}  // namespace systems
}  // namespace IGNITION_GAZEBO_VERSION_NAMESPACE
}  // namespace gazebo
}  // namespace ignition

#endif

ext: hh

max_stars_repo_name: mrushyendra/ign-gazebo

max_issues_repo_name: mrushyendra/ign-gazebo

max_forks_repo_name: mrushyendra/ign-gazebo


text:
// Warning! This file is autogenerated.
#ifndef BOOST_TEXT_DATA_OR_HPP
#define BOOST_TEXT_DATA_OR_HPP

#include <boost/text/string_view.hpp>

namespace boost { namespace text { namespace data { namespace or_ {

inline string_view standard_collation_tailoring()
{
    return string_view(
u8R"(
[normalization on]
[reorder Orya Deva Beng Guru Gujr Taml Telu Knda Mlym Sinh]
&ଔ<ଁ<ଂ<ଃ
&ହ<କ୍ଷ
&ଯ<<ୟ
  )");
}

}}}}

#endif

max_stars_repo_name: eightysquirrels/text

max_issues_repo_name: eightysquirrels/text

max_forks_repo_name: eightysquirrels/text


text:
#ifndef KA_MUTEX_HPP
#define KA_MUTEX_HPP
#pragma once
#include <mutex>
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/synchronized_value.hpp>
#include "typetraits.hpp"

namespace ka {
  namespace detail {
    template<typename M> struct IsMutex : false_t {};

    // Common mutexes that might be used in this library.
    template<> struct IsMutex<std::mutex>                   : true_t {};
    template<> struct IsMutex<std::recursive_mutex>         : true_t {};
#if !ANDROID
    template<> struct IsMutex<std::timed_mutex>             : true_t {};
    template<> struct IsMutex<std::recursive_timed_mutex>   : true_t {};
#endif
    template<> struct IsMutex<boost::mutex>                 : true_t {};
    template<> struct IsMutex<boost::recursive_mutex>       : true_t {};
    template<> struct IsMutex<boost::timed_mutex>           : true_t {};
    template<> struct IsMutex<boost::recursive_timed_mutex> : true_t {};
    template<> struct IsMutex<boost::shared_mutex>          : true_t {};
  } // namespace detail

  /// True if T is one of the commonly used mutex types:
  /// std::mutex, std::recursive_mutex, std::timed_mutex, std::recursive_timed_mutex, boost::mutex
  /// boost::recursive_mutex, boost::timed_mutex, boost::recursive_timed_mutex, boost::shared_mutex
  template<typename T>
  using IsMutex = typename detail::IsMutex<T>::type;
} // namespace ka

namespace std {
  /// model ScopeLockable M:
  /// Mutex M
  template<typename M, typename = ka::EnableIf<ka::IsMutex<M>::value>>
  std::unique_lock<M> scopelock(M& m) {
    return std::unique_lock<M>{ m };
  }
} // namespace std

namespace boost {
  /// model ScopeLockable M:
  /// Mutex M
  template<typename M, typename = ka::EnableIf<ka::IsMutex<M>::value>>
  std::unique_lock<M> scopelock(M& m) { // std::unique_lock works for boost mutexes
    return std::unique_lock<M>{ m };
  }

  /// model ScopeLockable boost::synchronized_value<T> const:
  template<typename T>
  auto scopelock(synchronized_value<T> const& sync_val)
      -> decltype(sync_val.synchronize()) { // TODO: Remove this when we can use C++14
    return sync_val.synchronize();
  }
} // namespace boost

#endif // QI_MUTEX_HPP

max_stars_repo_name: Maelic/libqi

max_issues_repo_name: Maelic/libqi

max_forks_repo_name: Maelic/libqi


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TRIGONOMETRIC_CONSTANTS_INV2PI_HPP_INCLUDED
#define NT2_TRIGONOMETRIC_CONSTANTS_INV2PI_HPP_INCLUDED

#include <nt2/include/functor.hpp>
#include <boost/simd/constant/hierarchy.hpp>
#include <boost/simd/constant/register.hpp>

namespace nt2
{
  namespace tag
  {
   /*!
     @brief Inv2pi generic tag

     Represents the Inv2pi constant in generic contexts.

     @par Models:
        Hierarchy
   **/
    BOOST_SIMD_CONSTANT_REGISTER( Inv2pi, double
                                  , 0, 0x3e22f983
                                  , 0x3fc45f306dc9c883ll
                                  )
  }
  namespace ext
  {
   template<class Site, class... Ts>
   BOOST_FORCEINLINE generic_dispatcher<tag::Inv2pi, Site> dispatching_Inv2pi(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
   {
     return generic_dispatcher<tag::Inv2pi, Site>();
   }
   template<class... Args>
   struct impl_Inv2pi;
  }
  /*!
    Constant \f$\frac1\pi\f$.

    @par Semantic:

    For type T0:

    @code
    T0 r = Inv2pi<T0>();
    @endcode

    is similar to:

    @code
    T0 r = rec(Two<T0>()*Pi<T0>());
    @endcode

    @return a value of type T0
  **/
  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Inv2pi, Inv2pi);
}

#endif