text:
/* boost random/xor_combine.hpp header file
 *
 * Copyright Jens Maurer 2002
 * Distributed under the Boost Software License, Version 1.0. (See
 * accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org for most recent version including documentation.
 *
 * $Id: xor_combine.hpp 53871 2009-06-13 17:54:06Z steven_watanabe $
 *
 */

#ifndef BOOST_RANDOM_XOR_COMBINE_HPP
#define BOOST_RANDOM_XOR_COMBINE_HPP

#include <iostream>
#include <cassert>
#include <algorithm> // for std::min and std::max
#include <boost/config.hpp>
#include <boost/limits.hpp>
#include <boost/static_assert.hpp>
#include <boost/cstdint.hpp>     // uint32_t
#include <boost/random/detail/config.hpp>

namespace boost {
namespace random {

#ifndef BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS
  #define BOOST_RANDOM_VAL_TYPE typename URNG1::result_type
#else
  #define BOOST_RANDOM_VAL_TYPE uint32_t
#endif

template<class URNG1, int s1, class URNG2, int s2, BOOST_RANDOM_VAL_TYPE val = 0>
class xor_combine
{
public:
  typedef URNG1 base1_type;
  typedef URNG2 base2_type;
  typedef typename base1_type::result_type result_type;

  BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
  BOOST_STATIC_CONSTANT(int, shift1 = s1);
  BOOST_STATIC_CONSTANT(int, shift2 = s2);

  xor_combine() : _rng1(), _rng2()
  { }
  xor_combine(const base1_type & rng1, const base2_type & rng2)
    : _rng1(rng1), _rng2(rng2) { }
  xor_combine(const result_type & v)
    : _rng1(v), _rng2(v) { }
  template<class It> xor_combine(It& first, It last)
    : _rng1(first, last), _rng2( /* advanced by other call */ first, last) { }
  void seed() { _rng1.seed(); _rng2.seed(); }
  void seed(const result_type & v) { _rng1.seed(v); _rng2.seed(v); }
  template<class It> void seed(It& first, It last)
  {
    _rng1.seed(first, last);
    _rng2.seed(first, last);
  }

  const base1_type& base1() { return _rng1; }
  const base2_type& base2() { return _rng2; }

  result_type operator()()
  {
    // MSVC fails BOOST_STATIC_ASSERT with std::numeric_limits at class scope
#if !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300)
    BOOST_STATIC_ASSERT(std::numeric_limits<typename base1_type::result_type>::is_integer);
    BOOST_STATIC_ASSERT(std::numeric_limits<typename base2_type::result_type>::is_integer);
    BOOST_STATIC_ASSERT(std::numeric_limits<typename base1_type::result_type>::digits >= std::numeric_limits<typename base2_type::result_type>::digits);
#endif
    return (_rng1() << s1) ^ (_rng2() << s2);
  }

  result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return std::min BOOST_PREVENT_MACRO_SUBSTITUTION((_rng1.min)(), (_rng2.min)()); }
  result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return std::max BOOST_PREVENT_MACRO_SUBSTITUTION((_rng1.min)(), (_rng2.max)()); }
  static bool validation(result_type x) { return val == x; }

#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE

#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
  template<class CharT, class Traits>
  friend std::basic_ostream<CharT,Traits>&
  operator<<(std::basic_ostream<CharT,Traits>& os, const xor_combine& s)
  {
    os << s._rng1 << " " << s._rng2 << " ";
    return os;
  }

  template<class CharT, class Traits>
  friend std::basic_istream<CharT,Traits>&
  operator>>(std::basic_istream<CharT,Traits>& is, xor_combine& s)
  {
    is >> s._rng1 >> std::ws >> s._rng2 >> std::ws;
    return is;
  }
#endif

  friend bool operator==(const xor_combine& x, const xor_combine& y)
  { return x._rng1 == y._rng1 && x._rng2 == y._rng2; }
  friend bool operator!=(const xor_combine& x, const xor_combine& y)
  { return !(x == y); }
#else
  // Use a member function; Streamable concept not supported.
  bool operator==(const xor_combine& rhs) const
  { return _rng1 == rhs._rng1 && _rng2 == rhs._rng2; }
  bool operator!=(const xor_combine& rhs) const
  { return !(*this == rhs); }
#endif

private:
  base1_type _rng1;
  base2_type _rng2;
};

#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
//  A definition is required even for integral static constants
template<class URNG1, int s1, class URNG2, int s2, BOOST_RANDOM_VAL_TYPE val>
const bool xor_combine<URNG1, s1, URNG2, s2, val>::has_fixed_range;
template<class URNG1, int s1, class URNG2, int s2, BOOST_RANDOM_VAL_TYPE val>
const int xor_combine<URNG1, s1, URNG2, s2, val>::shift1;
template<class URNG1, int s1, class URNG2, int s2, BOOST_RANDOM_VAL_TYPE val>
const int xor_combine<URNG1, s1, URNG2, s2, val>::shift2;
#endif

#undef BOOST_RANDOM_VAL_TYPE

} // namespace random
} // namespace boost

#endif // BOOST_RANDOM_XOR_COMBINE_HPP

max_stars_repo_name: EricBoittier/vina-carb-docker

max_issues_repo_name: EricBoittier/vina-carb-docker

max_forks_repo_name: EricBoittier/vina-carb-docker


text:
//
// asio.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)
//
//  See www.boost.org/libs/asio for documentation.
//

#ifndef BOOST_ASIO_HPP
#define BOOST_ASIO_HPP

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

#include <boost/asio/basic_datagram_socket.hpp>
#include <boost/asio/basic_deadline_timer.hpp>
#include <boost/asio/basic_io_object.hpp>
#include <boost/asio/basic_socket_acceptor.hpp>
#include <boost/asio/basic_socket_iostream.hpp>
#include <boost/asio/basic_socket_streambuf.hpp>
#include <boost/asio/basic_stream_socket.hpp>
#include <boost/asio/basic_streambuf.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/buffered_read_stream_fwd.hpp>
#include <boost/asio/buffered_read_stream.hpp>
#include <boost/asio/buffered_stream_fwd.hpp>
#include <boost/asio/buffered_stream.hpp>
#include <boost/asio/buffered_write_stream_fwd.hpp>
#include <boost/asio/buffered_write_stream.hpp>
#include <boost/asio/completion_condition.hpp>
#include <boost/asio/datagram_socket_service.hpp>
#include <boost/asio/deadline_timer_service.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/handler_alloc_hook.hpp>
#include <boost/asio/handler_invoke_hook.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/asio/ip/address_v6.hpp>
#include <boost/asio/ip/basic_endpoint.hpp>
#include <boost/asio/ip/basic_resolver.hpp>
#include <boost/asio/ip/basic_resolver_entry.hpp>
#include <boost/asio/ip/basic_resolver_iterator.hpp>
#include <boost/asio/ip/basic_resolver_query.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/multicast.hpp>
#include <boost/asio/ip/resolver_query_base.hpp>
#include <boost/asio/ip/resolver_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/ip/unicast.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/asio/is_read_buffered.hpp>
#include <boost/asio/is_write_buffered.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/socket_acceptor_service.hpp>
#include <boost/asio/socket_base.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/stream_socket_service.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/time_traits.hpp>
#include <boost/asio/version.hpp>
#include <boost/asio/write.hpp>

#endif // BOOST_ASIO_HPP

ext: hpp

max_stars_repo_name: foxostro/CheeseTesseract

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: foxostro/CheeseTesseract


text:
/*****************************************************************************/
/*  Copyright (c) 2015, Karl Pauwels                                         */
/*  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 <multi_rigid_detector.h>
#include <stdexcept>
#undef Success
#include <Eigen/Geometry>

namespace interface {

MultiRigidDetector::MultiRigidDetector(int image_width, int image_height,
                                       cv::Mat camera_matrix,
                                       std::vector<std::string> obj_filenames,
                                       int device_id, Parameters parameters)
    : image_width_(image_width), image_height_(image_height),
      parameters_(parameters) {
  double nodal_point_x = camera_matrix.at<double>(0, 2);
  double nodal_point_y = camera_matrix.at<double>(1, 2);
  double focal_length_x = camera_matrix.at<double>(0, 0);
  double focal_length_y = camera_matrix.at<double>(1, 1);

  d_multiple_rigid_pose_sparse_ =
      std::unique_ptr<pose::D_MultipleRigidPoseSparse>(
          new pose::D_MultipleRigidPoseSparse(
              image_width_, image_height_, nodal_point_x, nodal_point_y,
              focal_length_x, focal_length_y, device_id, parameters_.vec_size_,
              parameters_.num_iter_ransac_));

  for (auto &it : obj_filenames)
    d_multiple_rigid_pose_sparse_->addModel(it.c_str());
}

void MultiRigidDetector::estimatePose(const cv::Mat &image, int object_index,
                                      pose::TranslationRotation3D &pose) {
  if (image.type() != CV_8UC1)
    throw std::runtime_error(std::string(
        "MultiRigidDetector::updatePoses:: image must be CV_8UC1\n"));
  if ((image.rows != image_height_) || (image.cols != image_width_))
    throw std::runtime_error(std::string(
        "MultiRigidDetector::updatePoses:: incorrect image size\n"));
  if (object_index >= getNumberOfObjects())
    throw std::runtime_error(std::string(
        "MultiRigidDetector::updatePoses:: object index out of range\n"));

  pose = d_multiple_rigid_pose_sparse_->estimatePoseSpecificObject(
      image, object_index);
}

void MultiRigidDetector::estimatePose(const cv::Mat &image, int object_index,
                                      geometry_msgs::Pose &pose) {
  pose::TranslationRotation3D pose_tr;
  estimatePose(image, object_index, pose_tr);

  double t[3];
  pose_tr.getT(t);
  double x, y, z, w;
  pose_tr.getQuaternion(x, y, z, w);

  pose.position.x = t[0];
  pose.position.y = t[1];
  pose.position.z = t[2];
  pose.orientation.x = x;
  pose.orientation.y = y;
  pose.orientation.z = z;
  pose.orientation.w = w;
}

void MultiRigidDetector::setCameraMatrix(const cv::Mat &camera_matrix) {
  double nodal_point_x = camera_matrix.at<double>(0, 2);
  double nodal_point_y = camera_matrix.at<double>(1, 2);
  double focal_length_x = camera_matrix.at<double>(0, 0);
  double focal_length_y = camera_matrix.at<double>(1, 1);

  d_multiple_rigid_pose_sparse_->updateCalibration(
      image_width_, image_height_, nodal_point_x, nodal_point_y, focal_length_x,
      focal_length_y);
}

void MultiRigidDetector::setObjects(std::vector<std::string> obj_filenames) {
  d_multiple_rigid_pose_sparse_->removeAllModels();
  for (auto &it : obj_filenames)
    d_multiple_rigid_pose_sparse_->addModel(it.c_str());
}

int MultiRigidDetector::getNumberOfObjects() {
  return (d_multiple_rigid_pose_sparse_->getNumberOfObjects());
}
}

ext: cpp

max_stars_repo_name: carlo-/simtrack

max_issues_repo_name: carlo-/simtrack

max_forks_repo_name: carlo-/simtrack


text:
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
 All rights reserved.

 This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
 under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
 MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/

/**
 * \file     hypothesis_factor_graph.cpp
 * \author   Collin Johnson
 *
 * Definition of convert_hypothesis_graph_to_factor_graph.
 */

#include "hssh/local_topological/area_detection/labeling/hypothesis_factor_graph.h"
#include "hssh/local_topological/area_detection/labeling/boundary.h"
#include "hssh/local_topological/area_detection/labeling/boundary_classifier.h"
#include "hssh/local_topological/area_detection/labeling/hypothesis.h"
#include "hssh/local_topological/area_detection/labeling/hypothesis_classifier.h"
#include <boost/range/iterator_range.hpp>

namespace vulcan
{
namespace hssh
{

using VarVec = std::vector<Variable::Ptr>;
using FactVec = std::vector<Factor::Ptr>;
using EdgeVec = std::vector<FactorEdge::Ptr>;

struct ConstructionState
{
    int nextId = 0;
    VarVec vars;
    FactVec factors;
    EdgeVec edges;
    std::unordered_map<int, AreaHypothesisBoundary*> varToBoundary;
    std::unordered_map<int, AreaHypothesis*> varToHyp;
    std::unordered_map<AreaHypothesis*, Variable*> hypToVar;
    std::unordered_map<AreaHypothesisBoundary*, Variable*> bndToVar;
};

void add_area_variable(AreaHypothesis* hyp, const HypothesisClassifier& classifier, ConstructionState& state);
void add_gateway_variable(AreaHypothesisBoundary* boundary, ConstructionState& state);
void add_boundary_factor(AreaHypothesisBoundary* boundary,
                         const BoundaryClassifier& classifier,
                         ConstructionState& state);

HypothesisFactorGraph convert_hypothesis_graph_to_factor_graph(HypothesisGraph& hypGraph,
                                                               const HypothesisClassifier& hypClassifier,
                                                               const BoundaryClassifier& bndClassifier)
{
    ConstructionState state;

    // Create a factor for the type distribution for each area
    for (AreaHypothesis* hyp : boost::make_iterator_range(hypGraph.beginHypothesis(), hypGraph.endHypothesis())) {
        add_area_variable(hyp, hypClassifier, state);
    }

    // Create a factor for the gateway probability for each boundary
    for (AreaHypothesisBoundary* bnd : boost::make_iterator_range(hypGraph.beginBoundary(), hypGraph.endBoundary())) {
        add_gateway_variable(bnd, state);
    }

    // Create a factor for the type distribution for each boundary and its bounding areas
    for (AreaHypothesisBoundary* bnd : boost::make_iterator_range(hypGraph.beginBoundary(), hypGraph.endBoundary())) {
        add_boundary_factor(bnd, bndClassifier, state);
    }

    HypothesisFactorGraph hypFactorGraph;
    hypFactorGraph.graph = FactorGraph(state.vars, state.factors, state.edges);
    hypFactorGraph.varToHyp = state.varToHyp;
    hypFactorGraph.varToBoundary = state.varToBoundary;

    return hypFactorGraph;
}

void add_area_variable(AreaHypothesis* hyp, const HypothesisClassifier& classifier, ConstructionState& state)
{
    int id = state.nextId++;
    state.varToHyp[id] = hyp;

    auto hypVar = std::make_shared<Variable>(id, 3);
    std::vector<Variable*> hypVars;
    hypVars.push_back(hypVar.get());

    auto dist = classifier.calculateDistribution(hyp->features());

    std::vector<FactorStateProb> hypProbs;
    FactorStateProb pathProb;
    pathProb.states.emplace_back(id, kPathIdx);
    pathProb.prob = dist.path;
    hypProbs.push_back(pathProb);

    FactorStateProb decisionProb;
    decisionProb.states.emplace_back(id, kDecisionIdx);
    decisionProb.prob = dist.decision;
    hypProbs.push_back(decisionProb);

    FactorStateProb destProb;
    destProb.states.emplace_back(id, kDestIdx);
    destProb.prob = dist.destination;
    hypProbs.push_back(destProb);

    auto hypFactor = std::make_shared<Factor>(state.nextId++, hypVars, hypProbs);
    auto hypEdge = std::make_shared<FactorEdge>(hypVar->id(), hypFactor->id(), 3);
    hypVar->addEdge(hypEdge.get());
    hypFactor->addEdge(hypEdge.get());

    state.hypToVar[hyp] = hypVar.get();
    state.vars.push_back(hypVar);
    state.factors.push_back(hypFactor);
    state.edges.push_back(hypEdge);
}

void add_gateway_variable(AreaHypothesisBoundary* boundary, ConstructionState& state)
{
    int id = state.nextId++;
    state.varToBoundary[id] = boundary;

    auto bndVar = std::make_shared<Variable>(id, 2);
    std::vector<Variable*> bndVars;
    bndVars.push_back(bndVar.get());

    std::vector<FactorStateProb> bndProbs;
    FactorStateProb onProb;
    onProb.states.emplace_back(id, 1);
    onProb.prob = boundary->getGateway().probability();
    bndProbs.push_back(onProb);

    FactorStateProb offProb;
    offProb.states.emplace_back(id, 0);
    offProb.prob = 1.0 - onProb.prob;
    bndProbs.push_back(offProb);

    auto bndFactor = std::make_shared<Factor>(state.nextId++, bndVars, bndProbs);
    auto bndEdge = std::make_shared<FactorEdge>(bndVar->id(), bndFactor->id(), 2);
    bndVar->addEdge(bndEdge.get());
    bndFactor->addEdge(bndEdge.get());

    state.bndToVar[boundary] = bndVar.get();
    state.vars.push_back(bndVar);
    state.factors.push_back(bndFactor);
    state.edges.push_back(bndEdge);
}

void add_boundary_factor(AreaHypothesisBoundary* boundary,
                         const BoundaryClassifier& classifier,
                         ConstructionState& state)
{
    auto bndVar = state.bndToVar[boundary];

    std::array<Variable*, 2> hypVars;
    hypVars[0] = state.hypToVar[boundary->getHypotheses()[0]];
    hypVars[1] = state.hypToVar[boundary->getHypotheses()[1]];

    std::vector<Variable*> allVars;
    allVars.push_back(bndVar);
    allVars.push_back(hypVars[0]);
    allVars.push_back(hypVars[1]);

    std::vector<FactorStateProb> bndProbs;
    auto dist = classifier.boundaryDistribution();

    std::array<AreaHypothesis*, 2> hyps;
    hyps[0] = boundary->getHypotheses()[0];
    hyps[1] = boundary->getHypotheses()[1];

    std::array<int, 2> pathIdx;
    for (int n = 0; n < 2; ++n) {
        pathIdx[n] = hyps[n]->isEndGateway(boundary->getGateway().id()) ? kPathEndIdx : kPathIdx;
    }

    // Create a state probability for each combination of path/dest/decision for the areas and on/off for boundary
    for (int i = 0; i < 3; ++i) {
        int idxI = i == kPathIdx ? pathIdx[0] : i;

        for (int j = 0; j < 3; ++j) {
            int idxJ = j == kPathIdx ? pathIdx[1] : j;

            FactorStateProb onProb;
            onProb.states.emplace_back(hypVars[0]->id(), i);
            onProb.states.emplace_back(hypVars[1]->id(), j);
            onProb.states.emplace_back(bndVar->id(), 1);
            onProb.prob = dist.posModel(idxI, idxJ);
            bndProbs.push_back(onProb);

            FactorStateProb offProb;
            offProb.states.emplace_back(hypVars[0]->id(), i);
            offProb.states.emplace_back(hypVars[1]->id(), j);
            offProb.states.emplace_back(bndVar->id(), 0);
            offProb.prob = dist.negModel(idxI, idxJ);
            bndProbs.push_back(offProb);
        }
    }

    auto bndFactor = std::make_shared<Factor>(state.nextId++, allVars, bndProbs);
    auto edge1 = std::make_shared<FactorEdge>(hypVars[0]->id(), bndFactor->id(), 3);
    auto edge2 = std::make_shared<FactorEdge>(hypVars[1]->id(), bndFactor->id(), 3);
    auto edge3 = std::make_shared<FactorEdge>(bndVar->id(), bndFactor->id(), 2);

    bndFactor->addEdge(edge1.get());
    bndFactor->addEdge(edge2.get());
    bndFactor->addEdge(edge3.get());
    hypVars[0]->addEdge(edge1.get());
    hypVars[1]->addEdge(edge2.get());
    bndVar->addEdge(edge3.get());

    state.factors.push_back(bndFactor);
    state.edges.push_back(edge1);
    state.edges.push_back(edge2);
    state.edges.push_back(edge3);
}

}   // namespace hssh
}   // namespace vulcan

max_stars_repo_name: anuranbaka/Vulcan

max_issues_repo_name: anuranbaka/Vulcan

max_forks_repo_name: anuranbaka/Vulcan


text:
#pragma once
#include <swizzle/ast/Node.hpp>
#include <swizzle/lexer/TokenInfo.hpp>

#include <boost/filesystem/path.hpp>

namespace swizzle { namespace ast {
    class VisitorInterface;
}}

namespace swizzle { namespace ast { namespace nodes {

    class Import : public Node
    {
    public:
        Import(const lexer::TokenInfo& info, const boost::filesystem::path& path);

        const lexer::TokenInfo& info() const;
        const boost::filesystem::path& path() const;

        void accept(VisitorInterface& visitor) override;

    private:
        const lexer::TokenInfo info_;
        const boost::filesystem::path importPath_;
    };
}}}

max_stars_repo_name: SenorAgosto/Swizzle

max_issues_repo_name: SenorAgosto/Swizzle

max_forks_repo_name: SenorAgosto/Swizzle


text:
//
// Copyright (c) 2020 Richard Hodges (hodges.r@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/madmongo1/webclient
//
// This project was made possible with the generous support of:
// The C++ Alliance (https://cppalliance.org/)
// Jetbrains (https://www.jetbrains.com/)
//
// Talk to us on Slack (https://cppalliance.org/slack/)
//
// Many thanks to Vinnie Falco for continuous mentoring and support
//

#ifndef BOOST_WEBCLIENT_ASIO__GET_OP_HPP
#define BOOST_WEBCLIENT_ASIO__GET_OP_HPP

#include <boost/asio/coroutine.hpp>
#include <boost/beast/core/flat_static_buffer.hpp>
#include <boost/beast/core/tcp_stream.hpp>
#include <boost/beast/http/empty_body.hpp>
#include <boost/beast/http/message.hpp>
#include <boost/beast/http/read.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/http/write.hpp>
#include <boost/beast/ssl/ssl_stream.hpp>
#include <boost/webclient/asio/basic_internet_session.hpp>
#include <boost/webclient/asio/config.hpp>
#include <boost/webclient/asio/has_error_code.hpp>
#include <boost/webclient/asio/has_resolver.hpp>
#include <boost/webclient/asio/has_timeout.hpp>
#include <boost/webclient/config.hpp>
#include <boost/webclient/polyfill/exchange.hpp>
#include <boost/webclient/polyfill/make_unique.hpp>
#include <boost/webclient/polyfill/optional.hpp>
#include <boost/webclient/polyfill/shared_composed_op.hpp>
#include <boost/webclient/uri/uri_impl.hpp>
#include <boost/asio/ssl/error.hpp>

namespace boost { namespace webclient { namespace asio {

struct get_op_state
{
    template < class Executor >
    get_op_state(basic_internet_session< Executor > &session, string_view uri)
    : session_(session.iface())
    , ssl_stream(session.get_executor(), session.ssl_context())
    , input_uri(uri.begin(), uri.end())
    , uri()
    , request()
    , read_buffer()
    , checkpoint_time(now())
    , response()
    , response_view(response.native_view())
    , ssl_involved(false)
    {
    }

    using tcp_stream_type  = boost::beast::tcp_stream;
    using ssl_stream_type  = boost::beast::ssl_stream< tcp_stream_type >;
    using request_type     = http::request< http::empty_body >;
    using response_type    = http::response< http::string_body >;
    using read_buffer_type = boost::beast::flat_static_buffer< 1024 * 1024 >;

    auto tcp_stream() -> tcp_stream_type & { return ssl_stream.next_layer(); }

    static auto now() -> std::chrono::system_clock::time_point { return std::chrono::system_clock::now(); }
    auto        elapsed() -> std::chrono::duration< double >
    {
        auto const n = now();
        return std::chrono::duration_cast< std::chrono::duration< double > >(n - polyfill::exchange(checkpoint_time, n));
    }

    internet_session_iface &              session_;
    ssl_stream_type                       ssl_stream;
    std::string                           input_uri;
    uri::uri_impl                         uri;
    request_type                          request;
    read_buffer_type                      read_buffer;
    std::chrono::system_clock::time_point checkpoint_time;

    unique_http_response               response;
    unique_http_response::native_type &response_view;
    bool                               ssl_involved = false;

    // temmporary state
    net::ip::tcp::resolver::results_type::const_iterator current_resolve_result;
};

struct get_op
: boost::asio::coroutine
, has_error_code
, has_resolver< get_op >
, has_timeout< get_op >
{
    using resolver_type         = has_resolver::resolver_type;
    using resolver_results_type = resolver_type::results_type;
    using ssl_stream_type       = get_op_state::ssl_stream_type;

    using has_resolver< get_op >::operator();
    using has_timeout< get_op >:: operator();

    template < class Executor >
    get_op(basic_internet_session< Executor > &session, string_view uri)
    : has_error_code()
    , has_resolver(session.get_executor())
    , has_timeout(session.get_executor())
    , state_(polyfill::make_unique< get_op_state >(session, uri))
    {
    }

    void on_timeout()
    {
        this->cancel_resolver();
        log("Timeout");
    }

    void on_resolved(error_code const &ec)
    {
        this->cancel_timeout();
        log("Resolve complete: ", ec);
    }

    template < class... Args >
    void log(Args const &... args)
    {
        auto &state = *(this->state_);
        auto  ct    = state.checkpoint_time;   // argument order
        state.response.log(ct, " : ", args..., " : after ", state.elapsed());
    }

    template < class Self >
    void operator()(Self &self, error_code ec = {}, std::size_t bytes_transferred = 0)
    {
        using boost::beast::bind_front_handler;
        using webclient::polyfill::share;

        auto &state = *state_;
#include <boost/asio/yield.hpp>
        reenter(this) for (;;)
        {
            state.uri.parse(state.input_uri, ec);
            log("Parse URI: ", ec);
            if (this->set_error(ec))
            {
                yield net::post(std::move(self));
                goto finish;
            }

            state.uri.normalise_target(ec);
            log("Normalise target: ", ec);
            if (this->set_error(ec))
                goto finish;

            yield share(self);

            // deduce the port
            yield
            {
                this->initiate_resolve(share(self), state.uri.hostname(), deduce_http_service(state.uri));
                this->initiate_timout(share(self), state.session_.resolve_timeout());
            }

            while (this->resolving() || this->timeout_outstanding())
                yield;
            if (this->error)
                goto finish;

            // connect the socket

            state.current_resolve_result = this->resolved_endpoints().begin();
            while (state.current_resolve_result != this->resolved_endpoints().end())
            {
                state.tcp_stream().expires_after(state.session_.connect_timeout());
                yield state.tcp_stream().async_connect(state.current_resolve_result->endpoint(), share(self));
                log("Connect to: ", state.current_resolve_result->endpoint(), " result: ", ec);
                // if the connect is successful, we can exit the loop early.
                if (!ec)
                    goto connected;
                ++state.current_resolve_result;
            }
            // if we leave the loop, make sure there is an error of some kind
            this->set_error(ec);
            goto finish;

        connected:

            //
            // deduce whether SSL is involved
            //

            state.ssl_involved =
                secure_transport_indicated(state.uri, state.tcp_stream().socket().local_endpoint().port());

            //
            // connect ssl
            //

            if (state.ssl_involved)
            {
                // Set SNI Hostname (many hosts need this to handshake successfully)
                if (!SSL_set_tlsext_host_name(state.ssl_stream.native_handle(), state.uri.hostname().c_str()))
                    this->set_error(error_code(static_cast< int >(::ERR_get_error()), net::error::get_ssl_category()));

                log("Set TLS host name: ", this->error);

                if (this->error)
                    goto finish;

                yield state.ssl_stream.async_handshake(ssl_stream_type::client, share(self));
                log("SSL Handshake: ", ec);
                if (this->set_error(ec))
                    goto finish;
            }

            //
            // send the request
            //
            state.request.version(11);
            state.request.keep_alive(true);
            state.request.target(state.uri.target_as_string(ec));
            log("Encoding target: ", ec, " yields target [", state.request.target(), ']');
            if (this->set_error(ec))
                goto finish;
            state.request.set("host", state.uri.hostname());
            state.request.method(http::verb::get);

            if (state.ssl_involved)
                yield http::async_write(state.ssl_stream, state.request, share(self));
            else
                yield http::async_write(state.tcp_stream(), state.request, share(self));
            log("Write: ", ec);
            if (ec)
                return self.complete(ec, std::move(state.response));

            //
            // receive the header
            //

            // (todo? resolve chunked bodies?)
        read_again:
            state.tcp_stream().expires_after(std::chrono::seconds(30));
            state.response_view.body().clear();
            state.response_view.clear();
            if (state.ssl_involved)
                yield http::async_read(state.ssl_stream, state.read_buffer, state.response_view, share(self));
            else
                yield http::async_read(state.tcp_stream(), state.read_buffer, state.response_view, share(self));
            log("Read : ",
                ec,
                "[response ",
                state.response_view.result_int(),
                " - ",
                state.response_view.reason(),
                ']');
            if (this->set_error(ec))
                goto finish;

            //
            // class 100 responses
            //
            if (state.response_view.result() == http::status::continue_)
                goto read_again;
            else if (state.response_view.result() == http::status::switching_protocols)
                goto finish;
            else if (state.response_view.result() == http::status::processing)
                goto read_again;
            else if (state.response_view.result_int() >= 200 and state.response_view.result_int() < 300)
                goto finish;
            else if (state.response_view.result_int() >= 400)
                goto finish;
            //
            // redirect class. Some redirects might be possible within this connection,
            // but for now, let's ignore redirects
            //

        finish:
            log("Get complete: ", this->error);
            return self.complete(this->error, std::move(state.response));
        }
#include <boost/asio/unyield.hpp>
    }

    std::unique_ptr< get_op_state > state_;
};
}}}   // namespace boost::webclient::asio

#endif   // BOOST_WEBCLIENT_ASIO__BASIC_GET_OP_HPP


text:
/*
 * Copyright (c) 2017-2018 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#ifndef PKMN_POKEMON_BOX_GBIMPL_IPP
#define PKMN_POKEMON_BOX_GBIMPL_IPP

#include "exception_internal.hpp"

#include "pksav/pksav_call.hpp"

#include <pkmn/exception.hpp>

#include <pksav/gen1/text.h>
#include <pksav/gen2/text.h>
#include <pksav/math/endian.h>

#include <boost/thread/lock_guard.hpp>

#include <cstring>
#include <iostream>
#include <stdexcept>
#include <type_traits>

namespace pkmn {

    POKEMON_BOX_GBIMPL_TEMPLATE
    POKEMON_BOX_GBIMPL_CLASS::pokemon_box_gbimpl(
        int game_id,
        const list_type* p_native
    ): pokemon_box_impl(game_id)
    {
        if(p_native != nullptr)
        {
            _pksav_box = *p_native;
        }
        else
        {
            std::memset(
                &_pksav_box,
                0,
                sizeof(_pksav_box)
            );
            std::memset(
                _pksav_box.nicknames,
                0x50,
                sizeof(_pksav_box.nicknames)
            );
            std::memset(
                _pksav_box.otnames,
                0x50,
                sizeof(_pksav_box.otnames)
            );

            _pksav_box.species[get_capacity()-1] = 0xFF;
        }

        _p_native = &_pksav_box;

        _from_native();
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    std::string POKEMON_BOX_GBIMPL_CLASS::get_name()
    {
        if(std::is_same<list_type, struct pksav_gen1_pokemon_box>::value)
        {
            throw pkmn::feature_not_in_game_error("Box names", "Generation I");
        }
        else
        {
            boost::lock_guard<POKEMON_BOX_GBIMPL_CLASS> lock(*this);

            return _box_name;
        }
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    void POKEMON_BOX_GBIMPL_CLASS::set_name(
        const std::string& name
    )
    {
        if(std::is_same<list_type, struct pksav_gen1_pokemon_box>::value)
        {
            throw pkmn::feature_not_in_game_error("Box names", "Generation I");
        }
        else
        {
            pkmn::enforce_string_length(
                "Box name",
                name,
                0,
                PKSAV_GEN2_POKEMON_BOX_NAME_LENGTH
            );

            boost::lock_guard<POKEMON_BOX_GBIMPL_CLASS> lock(*this);

            _box_name = name;
        }
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    int POKEMON_BOX_GBIMPL_CLASS::get_num_pokemon()
    {
        boost::lock_guard<POKEMON_BOX_GBIMPL_CLASS> lock(*this);

        return int(_pksav_box.count);
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    int POKEMON_BOX_GBIMPL_CLASS::get_capacity()
    {
        return int(sizeof(_pksav_box.entries)/sizeof(_pksav_box.entries[0]));
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    void POKEMON_BOX_GBIMPL_CLASS::set_pokemon(
        int index,
        const pkmn::pokemon::sptr& new_pokemon
    )
    {
        int num_pokemon = get_num_pokemon();
        int capacity = get_capacity();
        int max_index = std::min<int>(capacity-1, num_pokemon);

        pkmn::enforce_bounds("Box index", index, 0, max_index);

        if((index < (num_pokemon-1)) && (new_pokemon->get_species() == pkmn::e_species::NONE))
        {
            throw std::invalid_argument("Generation I-II boxes store Pokémon contiguously.");
        }

        boost::lock_guard<POKEMON_BOX_GBIMPL_CLASS> lock(*this);

        // If the given Pokémon isn't from this box's game, convert it if we can.
        pkmn::pokemon::sptr actual_new_pokemon;
        if(_game_id == new_pokemon->get_database_entry().get_game_id())
        {
            actual_new_pokemon = new_pokemon;
        }
        else
        {
            actual_new_pokemon = new_pokemon->to_game(get_game());
        }

        // Make sure no one else is using the new Pokémon variable.
        libpkmn_pokemon_type* p_new_pokemon = dynamic_cast<libpkmn_pokemon_type*>(
                                                  actual_new_pokemon.get()
                                              );
        BOOST_ASSERT(p_new_pokemon != nullptr);
        boost::lock_guard<libpkmn_pokemon_type> new_pokemon_lock(*p_new_pokemon);

        // Copy the underlying memory to the box. At the end of this process,
        // all existing variables will correspond to the same Pokémon, even if
        // their underlying memory has changed.
        //
        // Note: as we control the implementation, we know the PC data points
        // to the whole Pokémon data structure.
        rcast_equal<pksav_pc_pokemon_type>(
            actual_new_pokemon->get_native_pc_data(),
            &_pksav_box.entries[index]
        );

        _pokemon_list[index] = std::make_shared<libpkmn_pokemon_type>(
                                   &_pksav_box.entries[index],
                                   _game_id
                               );

        // Don't set empty names.
        std::string new_pokemon_nickname = actual_new_pokemon->get_nickname();
        std::string new_pokemon_trainer_name = actual_new_pokemon->get_original_trainer_name();
        if(new_pokemon_nickname.size() == 0)
        {
            new_pokemon_nickname = "None";
        }
        if(new_pokemon_trainer_name.size() == 0)
        {
            new_pokemon_trainer_name = "None";
        }

        _pokemon_list[index]->set_nickname(new_pokemon_nickname);
        _pokemon_list[index]->set_original_trainer_name(new_pokemon_trainer_name);

        // Update the number of Pokémon in the box if needed.
        pkmn::e_species new_species = actual_new_pokemon->get_species();
        if((index == num_pokemon) && (new_species != pkmn::e_species::NONE))
        {
            ++(_pksav_box.count);
        }
        else if((index == (num_pokemon-1)) && (new_species == pkmn::e_species::NONE))
        {
            --(_pksav_box.count);
        }

        // In Generation II, whether or not a Pokémon is in an egg is
        // stored in the list that stores it, not the Pokémon struct itself.
        if(std::is_same<list_type, struct pksav_gen2_pokemon_box>::value and actual_new_pokemon->is_egg())
        {
            _pksav_box.species[index] = GEN2_EGG_ID;
        }
        else
        {
            _pksav_box.species[index] = uint8_t(actual_new_pokemon->get_database_entry().get_pokemon_index());
        }

        if(_generation == 1)
        {
            PKSAV_CALL(
                pksav_gen1_export_text(
                    actual_new_pokemon->get_nickname().c_str(),
                    _pksav_box.nicknames[index],
                    10
                );
            )
            PKSAV_CALL(
                pksav_gen1_export_text(
                    actual_new_pokemon->get_original_trainer_name().c_str(),
                    _pksav_box.otnames[index],
                    7
                );
            )
        }
        else
        {
            PKSAV_CALL(
                pksav_gen2_export_text(
                    actual_new_pokemon->get_nickname().c_str(),
                    _pksav_box.nicknames[index],
                    10
                );
            )
            PKSAV_CALL(
                pksav_gen2_export_text(
                    actual_new_pokemon->get_original_trainer_name().c_str(),
                    _pksav_box.otnames[index],
                    7
                );
            )
        }

        // If this box is part of a save, set the Pokédex to have both
        // seen and caught the Pokémon.
        if(_pokedex.get())
        {
            pkmn::e_species species = new_pokemon->get_species();

            if((species != pkmn::e_species::NONE) && !new_pokemon->is_egg())
            {
                _pokedex->set_has_seen(species, true);
                _pokedex->set_has_caught(species, true);
            }
        }
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    std::string POKEMON_BOX_GBIMPL_CLASS::get_wallpaper()
    {
        throw pkmn::feature_not_in_game_error("Box wallpaper", "Generation I-II");
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    void POKEMON_BOX_GBIMPL_CLASS::set_wallpaper(const std::string&)
    {
        throw pkmn::feature_not_in_game_error("Box wallpaper", "Generation I-II");
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    void POKEMON_BOX_GBIMPL_CLASS::_from_native()
    {
        int capacity = get_capacity();

        // This shouldn't resize if the vector is populated.
        _pokemon_list.resize(capacity);

        char nickname[11] = {0};
        char otname[8] = {0};

        int num_pokemon = get_num_pokemon();

        /*
         * Unfortuately, the count field may not be reliable, so we need to check
         * ourselves and fix it if it's wrong.
         */
        if((num_pokemon > 0) && (_pksav_box.entries[num_pokemon-1].species == 0))
        {
            for(int i = 0; i < num_pokemon; ++i)
            {
                if(_pksav_box.entries[i].species == 0)
                {
                    _pksav_box.count = i;
                    break;
                }
            }
        }

        for(int i = 0; i < capacity; ++i)
        {
            /*
             * Memory is not necessarily zeroed-out past the num_pokemon point,
             * so we'll do it ourselves.
             */
            if((i >= num_pokemon) && (_pksav_box.entries[i].species > 0))
            {
                _pksav_box.species[i] = 0;
                std::memset(&_pksav_box.entries[i], 0, sizeof(pksav_pc_pokemon_type));
                std::memset(_pksav_box.nicknames[i], 0x50, sizeof(_pksav_box.nicknames[i]));
                std::memset(_pksav_box.otnames[i], 0x50, sizeof(_pksav_box.otnames[i]));
            }

            _pokemon_list[i] = std::make_shared<libpkmn_pokemon_type>(
                                   &_pksav_box.entries[i],
                                   _game_id
                               );

            // In Generation II, whether or not a Pokémon is in an egg is
            // stored in the list that stores it, not the Pokémon struct itself.
            if(std::is_same<list_type, struct pksav_gen2_pokemon_box>::value)
            {
                _pokemon_list[i]->set_is_egg(
                    (_pksav_box.species[i] == GEN2_EGG_ID)
                );
            }

            PKSAV_CALL(
                pksav_gen1_import_text(
                    _pksav_box.nicknames[i],
                    nickname,
                    10
                );
            )
            if(std::strlen(nickname) > 0)
            {
                _pokemon_list[i]->set_nickname(nickname);
            }

            PKSAV_CALL(
                pksav_gen1_import_text(
                    _pksav_box.otnames[i],
                    otname,
                    7
                );
            )
            if(std::strlen(otname) > 0)
            {
                _pokemon_list[i]->set_original_trainer_name(otname);
            }
        }
    }

    POKEMON_BOX_GBIMPL_TEMPLATE
    void POKEMON_BOX_GBIMPL_CLASS::_to_native()
    {
        BOOST_ASSERT(static_cast<size_t>(get_capacity()) == _pokemon_list.size());

        std::memset(
            _pksav_box.otnames,
            0x50,
            sizeof(_pksav_box.otnames)
        );
        std::memset(
            _pksav_box.nicknames,
            0x50,
            sizeof(_pksav_box.nicknames)
        );

        for(size_t pokemon_index = 0;
            pokemon_index < _pokemon_list.size();
            ++pokemon_index)
        {
            pkmn::rcast_equal<pksav_pc_pokemon_type>(
                _pokemon_list[pokemon_index]->get_native_pc_data(),
                &_pksav_box.entries[pokemon_index]
            );

            // In Generation II, whether or not a Pokémon is in an egg is
            // stored in the list that stores it, not the Pokémon struct itself.
            if(std::is_same<list_type, struct pksav_gen2_pokemon_box>::value &&
               _pokemon_list[pokemon_index]->is_egg())
            {
                _pksav_box.species[pokemon_index] = GEN2_EGG_ID;
            }
            else
            {
                _pksav_box.species[pokemon_index] =
                    static_cast<uint8_t>(
                        _pokemon_list[pokemon_index]->get_database_entry().get_pokemon_index()
                    );
            }

            // Even though this function is meant to update the native representation,
            // the native count should have been updated along the way.
            if(pokemon_index < _pksav_box.count)
            {
                if(std::is_same<list_type, struct pksav_gen1_pokemon_box>::value)
                {
                    PKSAV_CALL(
                        pksav_gen1_export_text(
                            _pokemon_list[pokemon_index]->get_original_trainer_name().c_str(),
                            _pksav_box.otnames[pokemon_index],
                            PKSAV_GEN1_POKEMON_OTNAME_LENGTH
                        );
                    )
                    PKSAV_CALL(
                        pksav_gen1_export_text(
                            _pokemon_list[pokemon_index]->get_nickname().c_str(),
                            _pksav_box.nicknames[pokemon_index],
                            PKSAV_GEN1_POKEMON_NICKNAME_LENGTH
                        );
                    )
                }
                else
                {
                    PKSAV_CALL(
                        pksav_gen2_export_text(
                            _pokemon_list[pokemon_index]->get_original_trainer_name().c_str(),
                            _pksav_box.otnames[pokemon_index],
                            PKSAV_GEN2_POKEMON_OTNAME_LENGTH
                        );
                    )
                    PKSAV_CALL(
                        pksav_gen2_export_text(
                            _pokemon_list[pokemon_index]->get_nickname().c_str(),
                            _pksav_box.nicknames[pokemon_index],
                            PKSAV_GEN2_POKEMON_NICKNAME_LENGTH
                        );
                    )
                }
            }
        }
    }
}

#endif /* PKMN_POKEMON_BOX_GBIMPL_IPP */

ext: ipp

max_stars_repo_name: ncorgan/libpkmn

max_issues_repo_name: PMArkive/libpkmn

max_forks_repo_name: PMArkive/libpkmn


text:
#ifndef GDBPLZ_GDB_VERSION_HPP_87147F33047942B582333D9FC419213C
#define GDBPLZ_GDB_VERSION_HPP_87147F33047942B582333D9FC419213C

#include <boost/operators.hpp>
#include <string>

namespace gdbplz
{
	struct gdb_version : boost::totally_ordered<gdb_version>
	{
		unsigned major;
		unsigned minor;
		unsigned patch;
		std::string others;

		bool operator<(const gdb_version& other) const;
		bool operator==(const gdb_version& other) const;
		gdb_version(unsigned major, unsigned minor);
		gdb_version(unsigned major, unsigned minor, unsigned patch);
		gdb_version(unsigned major, unsigned minor, unsigned patch, std::string others);
	};
}

#endif

max_stars_repo_name: milleniumbug/gdbplz

max_issues_repo_name: milleniumbug/gdbplz

max_forks_repo_name: milleniumbug/gdbplz


text:
#include <string>
#include <iostream>
#include "TcpAsyncSender.h"
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/make_unique.hpp>

TcpAsyncSenderElement::TcpAsyncSenderElement() : m_onSuccessfulSendCallbackByIoServiceThreadPtr(NULL) {}
TcpAsyncSenderElement::~TcpAsyncSenderElement() {}

void TcpAsyncSenderElement::DoCallback(const boost::system::error_code& error, std::size_t bytes_transferred) {
    if(m_onSuccessfulSendCallbackByIoServiceThreadPtr && (*m_onSuccessfulSendCallbackByIoServiceThreadPtr)) {
        (*m_onSuccessfulSendCallbackByIoServiceThreadPtr)(error, bytes_transferred);
    }
}

TcpAsyncSender::TcpAsyncSender(boost::shared_ptr<boost::asio::ip::tcp::socket> & tcpSocketPtr, boost::asio::io_service & ioServiceRef) :
    m_ioServiceRef(ioServiceRef),
    m_tcpSocketPtr(tcpSocketPtr),
    m_writeInProgress(false)
{

}

TcpAsyncSender::~TcpAsyncSender() {

}

void TcpAsyncSender::AsyncSend_NotThreadSafe(TcpAsyncSenderElement * senderElementNeedingDeleted) {
    m_queueTcpAsyncSenderElements.push(std::unique_ptr<TcpAsyncSenderElement>(senderElementNeedingDeleted));
    if (!m_writeInProgress) {
        m_writeInProgress = true;
        boost::asio::async_write(*m_tcpSocketPtr, senderElementNeedingDeleted->m_constBufferVec,
            boost::bind(&TcpAsyncSender::HandleTcpSend, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
    }
}

void TcpAsyncSender::AsyncSend_ThreadSafe(TcpAsyncSenderElement * senderElementNeedingDeleted) {
    boost::asio::post(m_ioServiceRef, boost::bind(&TcpAsyncSender::AsyncSend_NotThreadSafe, this, senderElementNeedingDeleted));
}

void TcpAsyncSender::HandleTcpSend(const boost::system::error_code& error, std::size_t bytes_transferred) {
    m_queueTcpAsyncSenderElements.front()->DoCallback(error, bytes_transferred);
    m_queueTcpAsyncSenderElements.pop();
    if (error) {
        std::cerr << "error in TcpAsyncSender::HandleTcpSend: " << error.message() << std::endl;
    }
    else if (m_queueTcpAsyncSenderElements.empty()) {
        m_writeInProgress = false;
    }
    else {
        boost::asio::async_write(*m_tcpSocketPtr, m_queueTcpAsyncSenderElements.front()->m_constBufferVec,
            boost::bind(&TcpAsyncSender::HandleTcpSend, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
    }
}

#ifdef OPENSSL_SUPPORT_ENABLED
TcpAsyncSenderSsl::TcpAsyncSenderSsl(ssl_stream_sharedptr_t & sslStreamSharedPtr, boost::asio::io_service & ioServiceRef) :
    m_ioServiceRef(ioServiceRef),
    m_sslStreamSharedPtr(sslStreamSharedPtr),
    m_writeInProgress(false)
{

}

TcpAsyncSenderSsl::~TcpAsyncSenderSsl() {

}

void TcpAsyncSenderSsl::AsyncSendSecure_NotThreadSafe(TcpAsyncSenderElement * senderElementNeedingDeleted) {
    m_queueTcpAsyncSenderElements.push(std::unique_ptr<TcpAsyncSenderElement>(senderElementNeedingDeleted));
    if (!m_writeInProgress) {
        m_writeInProgress = true;
        boost::asio::async_write(*m_sslStreamSharedPtr, senderElementNeedingDeleted->m_constBufferVec,
            boost::bind(&TcpAsyncSenderSsl::HandleTcpSendSecure, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
    }
}

void TcpAsyncSenderSsl::AsyncSendSecure_ThreadSafe(TcpAsyncSenderElement * senderElementNeedingDeleted) {
    boost::asio::post(m_ioServiceRef, boost::bind(&TcpAsyncSenderSsl::AsyncSendSecure_NotThreadSafe, this, senderElementNeedingDeleted));
}

void TcpAsyncSenderSsl::HandleTcpSendSecure(const boost::system::error_code& error, std::size_t bytes_transferred) {
    m_queueTcpAsyncSenderElements.front()->DoCallback(error, bytes_transferred);
    m_queueTcpAsyncSenderElements.pop();
    if (error) {
        std::cerr << "error in TcpAsyncSenderSsl::HandleTcpSendSecure: " << error.message() << std::endl;
    }
    else if (m_queueTcpAsyncSenderElements.empty()) {
        m_writeInProgress = false;
    }
    else {
        boost::asio::async_write(*m_sslStreamSharedPtr, m_queueTcpAsyncSenderElements.front()->m_constBufferVec,
            boost::bind(&TcpAsyncSenderSsl::HandleTcpSendSecure, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
    }
}

void TcpAsyncSenderSsl::AsyncSendUnsecure_NotThreadSafe(TcpAsyncSenderElement * senderElementNeedingDeleted) {
    m_queueTcpAsyncSenderElements.push(std::unique_ptr<TcpAsyncSenderElement>(senderElementNeedingDeleted));
    if (!m_writeInProgress) {
        m_writeInProgress = true;
        //lowest_layer does not compile https://stackoverflow.com/a/32584870
        boost::asio::async_write(m_sslStreamSharedPtr->next_layer(), senderElementNeedingDeleted->m_constBufferVec, //https://stackoverflow.com/a/4726475
            boost::bind(&TcpAsyncSenderSsl::HandleTcpSendUnsecure, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
    }
}

void TcpAsyncSenderSsl::AsyncSendUnsecure_ThreadSafe(TcpAsyncSenderElement * senderElementNeedingDeleted) {
    boost::asio::post(m_ioServiceRef, boost::bind(&TcpAsyncSenderSsl::AsyncSendUnsecure_NotThreadSafe, this, senderElementNeedingDeleted));
}

void TcpAsyncSenderSsl::HandleTcpSendUnsecure(const boost::system::error_code& error, std::size_t bytes_transferred) {
    m_queueTcpAsyncSenderElements.front()->DoCallback(error, bytes_transferred);
    m_queueTcpAsyncSenderElements.pop();
    if (error) {
        std::cerr << "error in TcpAsyncSenderSsl::HandleTcpSendUnsecure: " << error.message() << std::endl;
    }
    else if (m_queueTcpAsyncSenderElements.empty()) {
        m_writeInProgress = false;
    }
    else {
        boost::asio::async_write(m_sslStreamSharedPtr->next_layer(), m_queueTcpAsyncSenderElements.front()->m_constBufferVec,
            boost::bind(&TcpAsyncSenderSsl::HandleTcpSendUnsecure, this,
                boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred));
    }
}
#endif


text:
//
// Copyright 2012 Christian Henning
//
// 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_GIL_IO_GET_READ_DEVICE_HPP
#define BOOST_GIL_IO_GET_READ_DEVICE_HPP

#include <boost/gil/io/device.hpp>
#include <boost/gil/io/path_spec.hpp>

#include <boost/mpl/and.hpp>

#include <type_traits>

namespace boost { namespace gil {

template< typename T
        , typename FormatTag
        , class Enable = void
        >
struct get_read_device
{};

template <typename Device, typename FormatTag>
struct get_read_device
<
    Device,
    FormatTag,
    typename std::enable_if
    <
        mpl::and_
        <
            detail::is_adaptable_input_device<FormatTag, Device>,
            is_format_tag<FormatTag>
        >::type::value
    >::type
>
{
    using type = typename detail::is_adaptable_input_device
        <
            FormatTag,
            Device
        >::device_type;
};

template <typename String, typename FormatTag>
struct get_read_device
<
    String,
    FormatTag,
    typename std::enable_if
    <
        mpl::and_
        <
            detail::is_supported_path_spec<String>,
            is_format_tag<FormatTag>
        >::type::value
    >::type
>
{
    using type = detail::file_stream_device<FormatTag>;
};

} // namespace gil
} // namespace boost

#endif


text:
// -----------------------------------------------------------------------
// RTToolbox - DKFZ radiotherapy quantitative evaluation library
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See rttbCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.  See the above copyright notices for more information.
//
//------------------------------------------------------------------------

// this file defines the rttbCoreTests for the test driver
// and all it expects is that you have a function called RegisterTests

#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>

#include "litCheckMacros.h"

#include "rttbBaseType.h"
#include "rttbDVH.h"
#include "rttbDVHSet.h"
#include "rttbDVHXMLFileReader.h"
#include "rttbDVHXMLFileWriter.h"
#include "rttbInvalidParameterException.h"
#include "rttbNullPointerException.h"

#include "../../core/DummyDVHGenerator.h"

#include "CompareDVH.h"

namespace rttb
{

	namespace testing
	{

		/*! @brief DVHXMLIOTest - test the IO for DVH xml data
		1) test writing dvh to xml file
		2) test reading DVH from xml file
		*/

		int DVHXMLIOTest(int argc, char* argv[])
		{
			typedef core::DVH::Pointer DVHPointer;

			PREPARE_DEFAULT_TEST_REPORTING;

			/* generate dummy DVH */
			const IDType structureIDPrefix = "myStructure";
			const IDType doseID = "myDose";

			DummyDVHGenerator dvhGenerator;

			DVHPointer spMyDVH = boost::make_shared<core::DVH>(dvhGenerator.generateDVH(structureIDPrefix,
			                     doseID));

			// 1) test writing DVH to xml file
			DVHType typeCum = {DVHType::Cumulative};
			DVHType typeDiff = {DVHType::Differential};
			FileNameString fN1 = "test.xml";
			CHECK_NO_THROW(io::other::DVHXMLFileWriter(fN1, typeDiff));
			CHECK_NO_THROW(io::other::DVHXMLFileWriter(fN1, typeCum));

			io::other::DVHXMLFileWriter dvhWriter(fN1, typeCum);

			CHECK_EQUAL(fN1, dvhWriter.getFileName());

			FileNameString fN2 = "otherFile.xml";
			CHECK_NO_THROW(dvhWriter.setFileName(fN2));
			CHECK_EQUAL(fN2, dvhWriter.getFileName());

			CHECK_EQUAL(DVHType::Cumulative, dvhWriter.getDVHType().Type);
			CHECK_NO_THROW(dvhWriter.setDVHType(typeDiff));
			CHECK_EQUAL(DVHType::Differential, dvhWriter.getDVHType().Type);

			DVHPointer emptyDvh;
			CHECK_THROW_EXPLICIT(dvhWriter.writeDVH(emptyDvh), core::NullPointerException);
			//CHECK_THROW_EXPLICIT(dvhWriter.writeDVH(spMyDVH), core::InvalidParameterException);
			CHECK_NO_THROW(dvhWriter.setDVHType(typeDiff));
			CHECK_NO_THROW(dvhWriter.writeDVH(spMyDVH));

			// 2) test reading DVH from xml file
			io::other::DVHXMLFileReader dvhReader(fN2);

			DVHPointer importedDVH = dvhReader.generateDVH();

			CHECK_EQUAL(*importedDVH, *spMyDVH);

			RETURN_AND_REPORT_TEST_SUCCESS;
		}

	}//testing
}//rttb

max_stars_repo_name: MIC-DKFZ/RTTB

max_issues_repo_name: MIC-DKFZ/RTTB

max_forks_repo_name: MIC-DKFZ/RTTB


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

#include "mongo/platform/basic.h"

#include "mongo/db/sessions_collection_rs.h"

#include <boost/optional.hpp>
#include <memory>
#include <utility>

#include "mongo/bson/bsonobj.h"
#include "mongo/client/authenticate.h"
#include "mongo/client/connection_string.h"
#include "mongo/client/query.h"
#include "mongo/client/read_preference.h"
#include "mongo/client/remote_command_targeter_factory_impl.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/repl_set_config.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/util/assert_util.h"

namespace mongo {

auto SessionsCollectionRS::_makePrimaryConnection(OperationContext* opCtx) {
    // Find the primary
    if (stdx::lock_guard lk(_mutex); !_targeter) {
        // There is an assumption here that for the lifetime of a given process, the
        // ReplicationCoordiation will only return configs for a single replica set
        auto coord = mongo::repl::ReplicationCoordinator::get(opCtx);
        auto config = coord->getConfig();
        uassert(ErrorCodes::NotYetInitialized,
                "Replication has not yet been configured",
                config.isInitialized());

        RemoteCommandTargeterFactoryImpl factory;
        _targeter = factory.create(config.getConnectionString());
    }

    auto res = uassertStatusOK(
        _targeter->findHost(opCtx, ReadPreferenceSetting(ReadPreference::PrimaryOnly)));

    auto conn = std::make_unique<ScopedDbConnection>(res.toString());

    // Make a connection to the primary, auth, then send
    if (auth::isInternalAuthSet()) {
        uassertStatusOK(conn->get()->authenticateInternalUser());
    }

    return conn;
}

bool SessionsCollectionRS::_isStandaloneOrPrimary(const NamespaceString& ns,
                                                  OperationContext* opCtx) {
    ShouldNotConflictWithSecondaryBatchApplicationBlock noPBWMBlock(opCtx->lockState());
    Lock::DBLock lk(opCtx, ns.db(), MODE_IS);
    Lock::CollectionLock lock(opCtx, NamespaceString::kLogicalSessionsNamespace, MODE_IS);

    auto coord = mongo::repl::ReplicationCoordinator::get(opCtx);

    return coord->canAcceptWritesForDatabase(opCtx, ns.db());
}

template <typename LocalCallback, typename RemoteCallback>
auto SessionsCollectionRS::_dispatch(const NamespaceString& ns,
                                     OperationContext* opCtx,
                                     LocalCallback&& localCallback,
                                     RemoteCallback&& remoteCallback)
    -> CommonResultT<LocalCallback, RemoteCallback> {
    if (_isStandaloneOrPrimary(ns, opCtx)) {
        return std::forward<LocalCallback>(localCallback)();
    }

    // There is a window here where we may transition from Primary to Secondary after we release
    // the locks we take in _isStandaloneOrPrimary(). In this case, the callback we run below
    // may throw a NotWritablePrimary error, or a stale read. However, this is preferable to running
    // the callback while we hold locks, since that can lead to a deadlock.

    auto conn = _makePrimaryConnection(opCtx);
    DBClientBase* client = conn->get();
    ScopeGuard guard([&] { conn->done(); });
    try {
        return std::forward<RemoteCallback>(remoteCallback)(client);
    } catch (...) {
        guard.dismiss();
        conn->kill();
        throw;
    }
}

void SessionsCollectionRS::setupSessionsCollection(OperationContext* opCtx) {
    _dispatch(
        NamespaceString::kLogicalSessionsNamespace,
        opCtx,
        [&] {
            try {
                checkSessionsCollectionExists(opCtx);
            } catch (const DBException& ex) {

                DBDirectClient client(opCtx);
                BSONObj cmd;

                if (ex.code() == ErrorCodes::IndexOptionsConflict) {
                    cmd = generateCollModCmd();
                } else {
                    // Creating the TTL index will auto-generate the collection.
                    cmd = generateCreateIndexesCmd();
                }

                BSONObj info;
                if (!client.runCommand(
                        NamespaceString::kLogicalSessionsNamespace.db().toString(), cmd, info)) {
                    uassertStatusOK(getStatusFromCommandResult(info));
                }
            }
        },
        [&](DBClientBase*) { checkSessionsCollectionExists(opCtx); });
}

void SessionsCollectionRS::checkSessionsCollectionExists(OperationContext* opCtx) {
    DBDirectClient client(opCtx);

    const bool includeBuildUUIDs = false;
    const int options = 0;
    auto indexes = client.getIndexSpecs(
        NamespaceString::kLogicalSessionsNamespace, includeBuildUUIDs, options);

    uassert(ErrorCodes::NamespaceNotFound,
            str::stream() << NamespaceString::kLogicalSessionsNamespace << " does not exist",
            indexes.size() != 0u);

    auto index = std::find_if(indexes.begin(), indexes.end(), [](const BSONObj& index) {
        return index.getField("name").String() == kSessionsTTLIndex;
    });

    uassert(ErrorCodes::IndexNotFound,
            str::stream() << NamespaceString::kLogicalSessionsNamespace
                          << " does not have the required TTL index",
            index != indexes.end());

    uassert(ErrorCodes::IndexOptionsConflict,
            str::stream() << NamespaceString::kLogicalSessionsNamespace
                          << " currently has the incorrect timeout for the TTL index",
            index->hasField("expireAfterSeconds") &&
                index->getField("expireAfterSeconds").Int() ==
                    (localLogicalSessionTimeoutMinutes * 60));
}

void SessionsCollectionRS::refreshSessions(OperationContext* opCtx,
                                           const LogicalSessionRecordSet& sessions) {
    const std::vector<LogicalSessionRecord> sessionsVector(sessions.begin(), sessions.end());

    _dispatch(NamespaceString::kLogicalSessionsNamespace,
              opCtx,
              [&] {
                  DBDirectClient client(opCtx);
                  _doRefresh(
                      NamespaceString::kLogicalSessionsNamespace,
                      sessionsVector,
                      makeSendFnForBatchWrite(NamespaceString::kLogicalSessionsNamespace, &client));
              },
              [&](DBClientBase* client) {
                  _doRefresh(
                      NamespaceString::kLogicalSessionsNamespace,
                      sessionsVector,
                      makeSendFnForBatchWrite(NamespaceString::kLogicalSessionsNamespace, client));
              });
}

void SessionsCollectionRS::removeRecords(OperationContext* opCtx,
                                         const LogicalSessionIdSet& sessions) {
    const std::vector<LogicalSessionId> sessionsVector(sessions.begin(), sessions.end());

    _dispatch(
        NamespaceString::kLogicalSessionsNamespace,
        opCtx,
        [&] {
            DBDirectClient client(opCtx);
            _doRemove(NamespaceString::kLogicalSessionsNamespace,
                      sessionsVector,
                      makeSendFnForBatchWrite(NamespaceString::kLogicalSessionsNamespace, &client));
        },
        [&](DBClientBase* client) {
            _doRemove(NamespaceString::kLogicalSessionsNamespace,
                      sessionsVector,
                      makeSendFnForBatchWrite(NamespaceString::kLogicalSessionsNamespace, client));
        });
}

LogicalSessionIdSet SessionsCollectionRS::findRemovedSessions(OperationContext* opCtx,
                                                              const LogicalSessionIdSet& sessions) {
    const std::vector<LogicalSessionId> sessionsVector(sessions.begin(), sessions.end());

    return _dispatch(
        NamespaceString::kLogicalSessionsNamespace,
        opCtx,
        [&] {
            DBDirectClient client(opCtx);
            return _doFindRemoved(
                NamespaceString::kLogicalSessionsNamespace,
                sessionsVector,
                makeFindFnForCommand(NamespaceString::kLogicalSessionsNamespace, &client));
        },
        [&](DBClientBase* client) {
            return _doFindRemoved(
                NamespaceString::kLogicalSessionsNamespace,
                sessionsVector,
                makeFindFnForCommand(NamespaceString::kLogicalSessionsNamespace, client));
        });
}

}  // namespace mongo

max_stars_repo_name: benety/mongo

max_issues_repo_name: benety/mongo

max_forks_repo_name: benety/mongo


text:
/*-----------------------------------------------------------------------------+
Copyright (c) 2010-2010: Joachim Faulhaber
+------------------------------------------------------------------------------+
   Distributed under the Boost Software License, Version 1.0.
      (See accompanying file LICENCE.txt or copy at
           http://www.boost.org/LICENSE_1_0.txt)
+-----------------------------------------------------------------------------*/
#ifndef BOOST_ICL_CONCEPT_INTERVAL_SET_VALUE_HPP_JOFA_100924
#define BOOST_ICL_CONCEPT_INTERVAL_SET_VALUE_HPP_JOFA_100924

#include <boost/utility/enable_if.hpp>
#include <boost/icl/type_traits/is_interval_container.hpp>
#include <boost/icl/concept/interval.hpp>

namespace boost{ namespace icl
{

//==============================================================================
//= AlgoUnifiers<Set>
//==============================================================================
template<class Type, class Iterator>
inline typename enable_if<is_interval_set<Type>, typename Type::codomain_type>::type
co_value(Iterator value_)
{
    typedef typename Type::codomain_type codomain_type;
    return icl::is_empty(*value_)? codomain_type() : (*value_).lower();
}

}} // namespace boost icl

#endif

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#include <iostream>
#include <cstring>
#include <boost/range/adaptor/map.hpp>
#include "../headers/Client.h"

Client::Client() {
    this->udpSocket = new UDPClientSocket();
}

Client::Client(std::string _hostname, int _port) {
    this->udpSocket = new UDPClientSocket();
    this->udpSocket->initializeClient(_hostname, _port);
}

bool Client::connectToServer(const std::string &_hostname, int _port) {
    return this->udpSocket->initializeClient(_hostname, _port);
}

bool Client::initBroadcast(std::string _broadcastAddress, int _broadcastPort) {
    return this->udpSocket->initializeBroadcastClient(_broadcastAddress, _broadcastPort);
}

Message *Client::execute(Message *_message) {
    send(_message);
    return receiveWithBlock();
}

Client::~Client() {
}

bool Client::send(Message *_message) {
    std::string marshalled = _message->marshal();
    if (Message::verifyFragmentation(marshalled)) {
        std::vector<Message *> msgs = _message->fragment(marshalled);
        int i = 0;
        do {
            std::string fragment_marshalled = msgs[i]->marshal();
            this->udpSocket->writeToSocket(&fragment_marshalled[0], fragment_marshalled.length());
            bool isAcknowledged = awaitAck();
            if (isAcknowledged)
                i++;
        } while (i < msgs.size());
        for (auto frag: msgs) {
            delete frag;
        }
        return true;
    } else {
        this->udpSocket->writeToSocket(&marshalled[0], marshalled.length());
        return true;
    }
}

bool Client::awaitAck() {
    char *reply = static_cast<char *>(malloc(MAX_READ_MESSAGE_SIZE));
    this->udpSocket->readSocketWithTimeout(reply, MAX_READ_MESSAGE_SIZE, 0, 500);
    std::cout << std::strlen(reply) << std::endl;
    std::cout << reply << std::endl;
    if (strcmp(reply, "Server Timed Out!") == 0) {
        std::cout << "Server timed out" << std::endl;
        return false;
    } else {
        auto *message = new Message(reply);
        if (message->getOperation() == Message::OperationType::ACK) {
            std::cout << "ACK RECEIVED" << std::endl;
            delete message;
            return true;
        } else {
            delete message;
            return awaitAck();
        }
    }
}

void Client::ack(const Message::RPC_ID &rpcId) {
    Ack acknowledgment = Ack();
    acknowledgment.setMessageId(rpcId.getMessageId());
    acknowledgment.setFragmentId(rpcId.getFragmentId());
    auto *request = this->saveAndGetMessage(acknowledgment, Message::MessageType ::Reply, Message::OperationType::ACK);
    this->send(request);
    std::cout << "ACK Transmitted" << std::endl;
}

Message::RPC_ID *Client::constructRPC() {
    return new Message::RPC_ID(this->udpSocket->getFilterAddress(), this->udpSocket->getMyPort());
}

bool Client::broadcast(Message *_message) {
    std::string marshalled = _message->marshal();
    this->udpSocket->writeBroadcastToSocket(&marshalled[0], marshalled.length());
    return true;
}

Message *Client::receiveWithBlock() {
    std::map<int, Message *> msgs;
    Message *fragment = nullptr;
    char *reply = static_cast<char *>(malloc(MAX_READ_MESSAGE_SIZE));

    do {
        this->udpSocket->readFromSocketWithBlock(reply, MAX_READ_MESSAGE_SIZE);
        fragment = new Message(reply);
        msgs[fragment->getRPCId().getFragmentId()] = fragment;
        if (fragment->getRPCId().isFragmented()) {
            std::cout << "Fragment ID: " << fragment->getRPCId().getFragmentId() << std::endl;
            std::cout << "Fragment Size: " << fragment->getMessage().length() << std::endl;
            ack(fragment->getRPCId());
        }
    } while (fragment->getRPCId().isFragmented() && (msgs.size() * MAX_MESSAGE_SIZE) < fragment->getMessageSize());

    if (msgs.size() > 1) {
        std::string stringHolder;
        for (auto &msg : msgs) {
            stringHolder += msg.second->getMessage();
        }
        for (auto* frag: msgs | boost::adaptors::map_values) {
            delete frag;
        }
        return new Message(&stringHolder[0]);
    } else {
        return msgs[0];
    }
}

Message *Client::receiveWithTimeout() {
    std::map<int, Message *> msgs;
    char *reply = static_cast<char *>(malloc(MAX_READ_MESSAGE_SIZE));
    bool timedOut = false;
    Message *fragment = nullptr;
    do {
        this->udpSocket->readSocketWithTimeout(reply, MAX_READ_MESSAGE_SIZE, 0, 1000);
        if(strcmp(reply, "Server Timed Out!") == 0) {
            timedOut = true;
            break;
        }
        fragment = new Message(reply);
        msgs[fragment->getRPCId().getFragmentId()] = fragment;
        if (fragment->getRPCId().isFragmented()) {
            std::cout << "Fragment ID: " << fragment->getRPCId().getFragmentId() << std::endl;
            std::cout << "Fragment Size: " << fragment->getMessage().length() << std::endl;
            ack(fragment->getRPCId());
        }
    } while (fragment->getRPCId().isFragmented() && (msgs.size() * MAX_MESSAGE_SIZE) < fragment->getMessageSize());
    if(timedOut) {
        return nullptr;
    }
    if (msgs.size() > 1) {
        std::string stringHolder;
        for (auto &msg : msgs) {
            stringHolder += msg.second->getMessage();
        }
        for (auto* frag: msgs | boost::adaptors::map_values) {
            delete frag;
        }
        return new Message(&stringHolder[0]);
    } else {
        return msgs[0];
    }
}