text:
#include <boost/format.hpp>

namespace osrm
{
namespace server
{
namespace service
{

const constexpr char PARAMETER_SIZE_MISMATCH_MSG[] =
    "Number of elements in %1% size %2% does not match coordinate size %3%";

template <typename ParamT>
bool constrainParamSize(const char *msg_template,
                        const char *name,
                        const ParamT &param,
                        const std::size_t target_size,
                        std::string &help)
{
    if (param.size() > 0 && param.size() != target_size)
    {
        help = (boost::format(msg_template) % name % param.size() % target_size).str();
        return true;
    }
    return false;
}
}
}
}

ext: hpp

max_stars_repo_name: jhermsmeier/osrm-backend

max_issues_repo_name: serarca/osrm-backend

max_forks_repo_name: serarca/osrm-backend


text:
#ifndef MSRP_GENERICPARSE_HXX
#define MSRP_GENERICPARSE_HXX

#include <sstream>
#include <stdexcept>

#include <boost/spirit.hpp>
#include <boost/spirit/actor.hpp>

#include <asio/buffer.hpp>

#include "ParseException.hxx"

namespace msrp
{

template<
   typename GrammarT,
   typename ResultT
   >
static inline void
Parse(ResultT& result, const asio::const_buffer& buf, const GrammarT& gr)
{
   using boost::spirit::parse_info;
   using boost::spirit::parse;

   try
   {
      parse_info<> info = parse(
            asio::buffer_cast<const char*>(buf),
            asio::buffer_cast<const char*>(buf) + buffer_size(buf),
            gr[boost::spirit::assign_a(result)]);

      if (!info.full)
      {
         std::stringstream ss;
         ss << "Parse failure (context: \"" << info.stop << "\")";

         throw ParseException(ss.str(), codeContext());
      }
   }
   catch (const ParseException& e)  // disambiguate from std::exception
   {
      throw e;
   }
   catch (const std::exception& e)
   {
      throw ParseException(e.what(), codeContext());
   }
}

}

#endif

// Copyright 2007 Chris Bond
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

ext: hxx

max_stars_repo_name: cbond/msrp

max_issues_repo_name: cbond/msrp

max_forks_repo_name: cbond/msrp


text:
/*
 * Software License Agreement (Modified BSD License)
 *
 *  Copyright (c) 2013, PAL Robotics, S.L.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * 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.
 *   * Neither the name of PAL Robotics, S.L. 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 OWNER 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.
 */

/** \author Paul Mathieu. */

#include "play_motion/play_motion_server.h"

#include <boost/foreach.hpp>

#include "play_motion/play_motion.h"
#include "play_motion/play_motion_helpers.h"
#include "play_motion/xmlrpc_helpers.h"

#include <diagnostic_msgs/DiagnosticArray.h>
#include <diagnostic_updater/DiagnosticStatusWrapper.h>

#define foreach BOOST_FOREACH

namespace play_motion
{
  PlayMotionServer::PlayMotionServer(const ros::NodeHandle& nh, const PlayMotionPtr& pm) :
    nh_(nh),
    pm_(pm),
    al_server_(nh_, "play_motion", false)
  {
    al_server_.registerGoalCallback(boost::bind(&PlayMotionServer::alGoalCb, this, _1));
    al_server_.registerCancelCallback(boost::bind(&PlayMotionServer::alCancelCb, this, _1));
    al_server_.start();

    list_motions_srv_ = ros::NodeHandle("~").advertiseService("list_motions",
                                                              &PlayMotionServer::listMotions,
                                                              this);

    diagnostic_pub_ = nh_.advertise<diagnostic_msgs::DiagnosticArray>("/diagnostics", 1);
    diagnostic_timer_ = nh_.createTimer(ros::Duration(1.0), &PlayMotionServer::publishDiagnostics,
                                        this);
  }

  PlayMotionServer::~PlayMotionServer()
  {}

  bool PlayMotionServer::findGoalId(AlServer::GoalHandle gh, PlayMotion::GoalHandle& goal_hdl)
  {
    typedef std::pair<PlayMotion::GoalHandle, AlServer::GoalHandle> goal_pair_t;
    foreach (const goal_pair_t& p, al_goals_)
      if (goal_hdl = p.first, p.second == gh)
        return true;

    return false;
  }

  void PlayMotionServer::playMotionCb(const PlayMotion::GoalHandle& goal_hdl)
  {
    PMR r;
    r.error_code = goal_hdl->error_code;
    r.error_string = goal_hdl->error_string;

    if (r.error_code == PMR::SUCCEEDED)
    {
      ROS_INFO("Motion played successfully.");
      al_goals_[goal_hdl].setSucceeded(r);
    }
    else
    {
      if (r.error_code == 0)
        ROS_ERROR("Motion ended with INVALID ERROR code %d and description '%s'", r.error_code, r.error_string.c_str());
      else
        ROS_WARN("Motion ended with an error code %d and description '%s'", r.error_code, r.error_string.c_str());
      al_goals_[goal_hdl].setAborted(r);
    }
    al_goals_.erase(goal_hdl);
  }

  void PlayMotionServer::alCancelCb(AlServer::GoalHandle gh)
  {
    PlayMotion::GoalHandle goal_hdl;
    if (findGoalId(gh, goal_hdl))
      goal_hdl->cancel(); //should not be needed
    else
      ROS_ERROR("Cancel request could not be fulfilled. Goal not running?.");

    al_goals_.erase(goal_hdl);
    gh.setCanceled();
  }

  void PlayMotionServer::alGoalCb(AlServer::GoalHandle gh)
  {
    AlServer::GoalConstPtr goal = gh.getGoal(); //XXX: can this fail? should we check it?
    ROS_INFO_STREAM("Received request to play motion '" << goal->motion_name << "'.");
    PlayMotion::GoalHandle goal_hdl;
    if (!pm_->run(goal->motion_name,
                  goal->skip_planning,
                  goal_hdl,
                  boost::bind(&PlayMotionServer::playMotionCb, this, _1)))
    {
      PMR r;
      r.error_code = goal_hdl->error_code;
      r.error_string = goal_hdl->error_string;
      if (!r.error_string.empty())
        ROS_ERROR_STREAM(r.error_string);
      ROS_ERROR_STREAM("Motion '" << goal->motion_name << "' could not be played.");
      gh.setRejected(r);
      return;
    }
    gh.setAccepted();
    al_goals_[goal_hdl] = gh;
  }

  bool PlayMotionServer::listMotions(play_motion_msgs::ListMotions::Request&  req,
                                     play_motion_msgs::ListMotions::Response& resp)
  {
    try
    {
      MotionNames motions;
      ros::NodeHandle pnh("~");
      getMotionIds(pnh, motions);
      foreach (const std::string& motion, motions)
      {
        play_motion_msgs::MotionInfo info;
        info.name = motion;
        getMotionJoints(pnh, motion, info.joints);
        getMotionDuration(pnh, motion);
        resp.motions.push_back(info);
      }
    }
    catch (const xh::XmlrpcHelperException& e)
    {
      ROS_ERROR_STREAM(e.what());
      return false;
    }
    return true;
  }

  void PlayMotionServer::publishDiagnostics(const ros::TimerEvent &) const
  {
  diagnostic_msgs::DiagnosticArray array;
  diagnostic_updater::DiagnosticStatusWrapper status;
  status.name = "Functionality: Play Motion";
  for (std::map<PlayMotion::GoalHandle, AlServer::GoalHandle>::const_iterator it = al_goals_.begin();
       it != al_goals_.end(); ++it)
  {
    const AlServer::GoalHandle &hdl = it->second;
    status.add("Executing motion", hdl.getGoal()->motion_name);
  }
  if (al_goals_.empty())
    status.mergeSummary(diagnostic_msgs::DiagnosticStatus::OK, "Not executing any motion");
  else
    status.mergeSummary(diagnostic_msgs::DiagnosticStatus::OK, "Executing motions");

  array.status.push_back(status);
  diagnostic_pub_.publish(array);
  }
}

ext: cpp


text:
// Copyright 2015-2019 Josh Pieper, jjp@pobox.com.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "mjlib/micro/persistent_config.h"

#include <cstring>

#include <boost/crc.hpp>

#include "mjlib/base/assert.h"
#include "mjlib/base/buffer_stream.h"
#include "mjlib/base/crc.h"
#include "mjlib/base/crc_stream.h"
#include "mjlib/base/null_stream.h"
#include "mjlib/base/tokenizer.h"

#include "mjlib/telemetry/format.h"

#include "mjlib/micro/flash.h"
#include "mjlib/micro/pool_map.h"

/// @file
///
/// The persistent storage is an unordered list of elements:
///
///   * Element
///     * pstring - name
///     * 32bit schema CRC
///     * pstring - data
///
/// It is terminated by an element with a 0 length name.
///
/// A pstring is a 32 byte unsigned integer followed by that many
/// bytes of data.

namespace mjlib {
namespace micro {
namespace {
constexpr int kMaxSize = 16;

class SizeCountingStream : public base::WriteStream {
 public:
  void write(const std::string_view& data) override {
    size_ += data.size();
  }

  size_t size() const { return size_; }

 private:
  size_t size_ = 0;
};
}

class PersistentConfig::Impl {
 public:
  Impl(Pool& pool, CommandManager& command_manager, FlashInterface& flash)
      : pool_(pool), flash_(flash), elements_(&pool, kMaxSize) {
    command_manager.Register("conf", [this](auto&& a, auto&& b) {
        this->Command(a, b);
      });
  }

  void Command(const std::string_view& command,
               const CommandManager::Response& response) {
    base::Tokenizer tokenizer(command, " ");
    auto cmd = tokenizer.next();
    if (cmd == "enumerate") {
      Enumerate(tokenizer.remaining(), response);
    } else if (cmd == "list") {
      List(response);
    } else if (cmd == "get") {
      Get(tokenizer.remaining(), response);
    } else if (cmd == "set") {
      Set(tokenizer.remaining(), response);
    } else if (cmd == "load") {
      Load(response);
    } else if (cmd == "write") {
      Write(response);
    } else if (cmd == "default") {
      Default(response);
    } else {
      UnknownCommand(cmd, response);
    }
  }

  struct Element {
    SerializableHandlerBase* serializable = nullptr;
    base::inplace_function<void ()> updated;
    bool enumerate = true;
  };

  using ElementMap = PoolMap<std::string_view, Element>;

  void Enumerate(const std::string_view& maybe_field,
                 const CommandManager::Response& response) {
    current_response_ = response;
    if (maybe_field.size()) {
      // Look up this field.
      const auto element_it = elements_.find(maybe_field);
      if (element_it == elements_.end()) {
        WriteMessage("ERR unknown group\r\n", response);
        return;
      }
      current_enumerate_index_ = element_it - elements_.begin();
      end_enumerate_index_ = current_enumerate_index_ + 1;
    } else {
      current_enumerate_index_ = 0;
      end_enumerate_index_ = elements_.size();
    }

    EnumerateCallback({});
  }

  void EnumerateCallback(error_code error) {
    if (error) {
      current_response_.callback(error);
      return;
    }

    while (true) {
      const auto element_it = elements_.begin() + current_enumerate_index_;
      if (current_enumerate_index_ >= end_enumerate_index_ ||
          element_it == elements_.end()) {
        WriteOK(current_response_);
        return;
      }

      current_enumerate_index_++;

      if (!element_it->second.enumerate) {
        continue;
      }

      element_it->second.serializable->Enumerate(
          &this->enumerate_context_,
          this->send_buffer_,
          element_it->first,
          *current_response_.stream,
          [this](error_code err) { this->EnumerateCallback(err); });
      return;
    }
  }

  void List(const CommandManager::Response& response) {
    current_response_ = response;
    current_list_index_ = 0;
    ListCallback({});
  }

  void ListCallback(error_code error) {
    if (error) {
      current_response_.callback(error);
      return;
    }

    if (current_list_index_ >= elements_.size()) {
      WriteOK(current_response_);
      return;
    }

    auto element_it = elements_.begin() + current_list_index_;
    if (element_it == elements_.end()) {
      WriteOK(current_response_);
      return;
    }

    const auto& name = element_it->first;
    current_list_index_++;

    char *ptr = &send_buffer_[0];
    std::copy(name.begin(), name.end(), ptr);
    ptr += name.size();
    *ptr = '\r';
    ptr++;
    *ptr = '\n';
    ptr++;
    AsyncWrite(*current_response_.stream,
               std::string_view(send_buffer_, ptr - send_buffer_),
               [this](error_code ec) {
                 ListCallback(ec);
               });
  }

  void Get(const std::string_view& field,
           const CommandManager::Response& response) {
    base::Tokenizer tokenizer(field, ".");
    auto group = tokenizer.next();
    const auto element_it = elements_.find(group);
    if (element_it == elements_.end()) {
      WriteMessage("ERR unknown group\r\n", response);
    } else {
      current_response_ = response;
      auto& element = element_it->second;
      const int err =
          element.serializable->Read(
              tokenizer.remaining(),
              send_buffer_,
              *current_response_.stream,
              [this](error_code error) {
                if (error) {
                  this->current_response_.callback(error);
                  return;
                }
                WriteMessage("\r\n",
                             this->current_response_);
              });
      if (err) {
        WriteMessage("ERR error reading\r\n", response);
      }
    }
  }

  void Set(const std::string_view& command,
           const CommandManager::Response& response) {
    base::Tokenizer tokenizer(command, ".");
    auto group = tokenizer.next();
    const auto element_it = elements_.find(group);
    if (element_it == elements_.end()) {
      WriteMessage("ERR unknown group\r\n", response);
    } else {
      base::Tokenizer name_value(tokenizer.remaining(), " ");
      auto key = name_value.next();
      auto value = name_value.remaining();
      auto& element = element_it->second;
      const int result = element.serializable->Set(key, value);
      if (result == 0) {
        element.updated();
        WriteOK(response);
      } else {
        WriteMessage("ERR error setting\r\n", response);
      }
    }
  }

  void Load(const CommandManager::Response& response) {
    DoLoad();

    WriteOK(response);
  }

  void DoLoad() {
    auto info = flash_.GetInfo();
    base::BufferReadStream flash_stream(
        std::string_view(info.start, info.end - info.start));
    telemetry::ReadStream stream(flash_stream);

    while (true) {
      const auto maybe_name_size = stream.ReadVaruint();
      if (!maybe_name_size) {
        // Whoops, an error of some sort.
        break;
      }
      const auto name_size = *maybe_name_size;
      typedef telemetry::Format TF;
      if (name_size == 0 ||
          name_size >= static_cast<uint32_t>(TF::kMaxStringSize)) {
        break;
      }
      std::string_view name(flash_stream.position(), name_size);
      flash_stream.ignore(name_size);

      if (flash_stream.remaining() < 8) { break; }

      const auto maybe_expected_crc = stream.Read<uint32_t>();
      const auto maybe_data_size = stream.Read<uint32_t>();

      if (!maybe_expected_crc || !maybe_data_size) { break; }
      const auto expected_crc = *maybe_expected_crc;
      const auto data_size = *maybe_data_size;

      // We are now committed to reading the entirety of the data one
      // way or another.

      const auto element_it = elements_.find(name);
      if (element_it == elements_.end()) {
        // TODO jpieper: It would be nice to warn about situations
        // like this.
        flash_stream.ignore(data_size);
        continue;
      }

      auto& element = element_it->second;

      const uint32_t actual_crc = CalculateSchemaCrc(element.serializable);
      if (actual_crc != expected_crc) {
        // TODO jpieper: It would be nice to warn about situations like
        // this.
        flash_stream.ignore(data_size);
        continue;
      }

      if (element.serializable->ReadBinary(flash_stream)) {
        // It would be nice to let the caller know this failed.
      }
    }

    // Notify everyone that they have changed.
    for (auto& element: elements_) {
      element.second.updated();
    }
  }

  uint32_t CalculateSchemaCrc(SerializableHandlerBase* base) const {
    base::NullWriteStream null;
    base::CrcWriteStream<boost::crc_32_type> crc_stream(null);

    base->WriteSchema(crc_stream);

    return crc_stream.checksum();
  }

  void Write(const CommandManager::Response& response) {
    auto info = flash_.GetInfo();
    flash_.Unlock();
    flash_.Erase();
    FlashWriteStream flash_stream(flash_, info.start);
    telemetry::WriteStream stream(flash_stream);

    for (const auto& item_pair : elements_) {
      const auto& element = item_pair.second;

      stream.WriteString(item_pair.first);
      stream.Write(static_cast<uint32_t>(
                       CalculateSchemaCrc(element.serializable)));

      SizeCountingStream size_stream;
      element.serializable->WriteBinary(size_stream);
      const uint32_t data_size = size_stream.size();

      stream.Write(data_size);
      element.serializable->WriteBinary(flash_stream);
    }

    stream.Write(static_cast<uint32_t>(0));

    flash_.Lock();

    WriteOK(response);
  }

  void Default(const CommandManager::Response& response) {
    for (auto& item_pair : elements_) {
      item_pair.second.serializable->SetDefault();
    }
    WriteOK(response);
  }

  void WriteOK(const CommandManager::Response& response) {
    WriteMessage("OK\r\n", response);
  }

  void UnknownCommand(const std::string_view&,
                      const CommandManager::Response& response) {
    WriteMessage("ERR unknown subcommand\r\n", response);
  }

  void WriteMessage(const std::string_view& message,
                    const CommandManager::Response& response) {
    AsyncWrite(*response.stream, message, response.callback);
  }

  Pool& pool_;
  FlashInterface& flash_;

  ElementMap elements_;

  // TODO jpieper: This buffer could be shared with other things that
  // have the same output stream, as only one should be writing at a
  // time anyways.
  char send_buffer_[256] = {};
  std::size_t current_list_index_ = 0;

  CommandManager::Response current_response_;
  std::size_t current_enumerate_index_ = 0;
  std::size_t end_enumerate_index_ = 0;
  detail::EnumerateArchive::Context enumerate_context_;
};

PersistentConfig::PersistentConfig(
    Pool& pool, CommandManager& command_manager, FlashInterface& flash)
    : impl_(&pool, pool, command_manager, flash) {
}

PersistentConfig::~PersistentConfig() {
}

void PersistentConfig::Load() {
  impl_->DoLoad();
}

void PersistentConfig::RegisterDetail(
    const std::string_view& name, SerializableHandlerBase* base,
    base::inplace_function<void ()> updated,
    const RegisterOptions& options) {
  Impl::Element element;
  element.serializable = base;
  element.updated = updated;
  element.enumerate = options.enumerate;

  const auto result = impl_->elements_.insert({name, element});
  // We do not allow duplicate names.
  MJ_ASSERT(result.second == true);
}

Pool* PersistentConfig::pool() const { return &impl_->pool_; }

}
}

ext: cc


text:
// # playback at 0.1 speed realtime
// log_playback --loop=false --speed=0.1 --log= /tmp/farm-ng-event.log
// # playback realtime
// log_playback --loop=false --speed=1 --log= /tmp/farm-ng-event.log
// # playback realtime and loop
// log_playback --loop=true --speed=1 --log= /tmp/farm-ng-event.log
// # playback at 10x speed and publish on event bus, don't do this with robot
// not-estopped as this will send steering commands! log_playback --send
// --loop=true --speed=10 --log= /tmp/farm-ng-event.log

#include <gflags/gflags.h>
#include <google/protobuf/util/time_util.h>
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/optional.hpp>
#include <chrono>
#include <iostream>
#include <stdexcept>

#include "farm_ng/core/event_log_reader.h"
#include "farm_ng/core/init.h"
#include "farm_ng/core/ipc.h"
#include "farm_ng/core/log_playback.pb.h"

DEFINE_bool(interactive, false, "receive program args via eventbus");

DEFINE_string(
    log, "",
    "Path to log file, recorded with ipc_logger, relative to BLOBSTORE_ROOT");

DEFINE_bool(loop, false, "Loop?");

DEFINE_bool(send, false, "Send on event bus?");

DEFINE_double(speed, 1.0, "How fast to play log, multiple of realtime");

namespace farm_ng {
namespace core {

std::chrono::microseconds ToChronoDuration(
    google::protobuf::Duration duration) {
  return std::chrono::microseconds(
      google::protobuf::util::TimeUtil::DurationToMicroseconds(duration));
}

class IpcLogPlayback {
 public:
  IpcLogPlayback(EventBus& bus, const LogPlaybackConfiguration& configuration,
                 bool interactive)
      : io_service_(bus.get_io_service()),
        bus_(bus),
        status_timer_(bus.get_io_service()),
        log_timer_(bus.get_io_service()) {
    if (interactive) {
      status_.mutable_input_required_configuration()->CopyFrom(configuration);
    } else {
      set_configuration(configuration);
    }
    bus_.AddSubscriptions({bus_.GetName()});

    bus_.GetEventSignal()->connect(
        std::bind(&IpcLogPlayback::on_event, this, std::placeholders::_1));
    on_status_timer(boost::system::error_code());
  }

  void send_status() {
    status_.clear_message_stats();
    for (auto name_stats : message_stats_) {
      status_.add_message_stats()->CopyFrom(name_stats.second);
    }

    LOG(INFO) << status_.ShortDebugString();
    bus_.Send(MakeEvent(bus_.GetName() + "/status", status_));
  }

  void on_status_timer(const boost::system::error_code& error) {
    if (error) {
      LOG(WARNING) << "timer error: " << __PRETTY_FUNCTION__ << error;
      return;
    }
    status_timer_.expires_from_now(std::chrono::milliseconds(1000));
    status_timer_.async_wait(std::bind(&IpcLogPlayback::on_status_timer, this,
                                       std::placeholders::_1));

    send_status();
  }

  void on_event(const EventPb& event) {
    LogPlaybackConfiguration configuration;
    if (event.data().UnpackTo(&configuration)) {
      LOG(INFO) << configuration.ShortDebugString();
      set_configuration(configuration);
    }
  }

  void set_configuration(LogPlaybackConfiguration configuration) {
    configuration_ = configuration;
    status_.clear_input_required_configuration();
    status_.mutable_configuration()->CopyFrom(configuration_);
    send_status();
  }

  void log_read_and_send(const boost::system::error_code& error) {
    if (error) {
      std::cerr << "log_timer_ error: " << __PRETTY_FUNCTION__ << error
                << std::endl;
      return;
    }
    if (next_message_) {
      *next_message_->mutable_stamp() = MakeTimestampNow();
      status_.set_message_count(status_.message_count() + 1);
      status_.mutable_last_message_stamp()->CopyFrom(next_message_->stamp());
      MessageStats& stats = message_stats_[next_message_->name()];
      stats.set_name(next_message_->name());
      stats.set_type_url(next_message_->data().type_url());
      stats.set_count(stats.count() + 1);
      double delta_seconds =
          google::protobuf::util::TimeUtil::DurationToNanoseconds(
              (next_message_->stamp() - stats.last_stamp())) *
          1.0e-9;
      if (delta_seconds < 1.0e-9 || delta_seconds > 60 * 60 * 60) {
        stats.set_frequency(0.0);
      } else {
        if (stats.frequency() < 1.0e-9) {
          stats.set_frequency(1.0 / delta_seconds);
        } else {
          // Take a windowed rolling average, exponential decay of older samples
          double alpha = 0.1;
          stats.set_frequency((1.0 / delta_seconds) * alpha +
                              stats.frequency() * (1 - alpha));
        }
      }
      stats.mutable_last_stamp()->CopyFrom(next_message_->stamp());

      if (configuration_.send()) {
        if (!next_message_->data().Is<LoggingCommand>()) {
          next_message_->set_name(std::string("playback/") +
                                  next_message_->name());
          bus_.Send(*next_message_);
        }
      }
    }
    try {
      next_message_ = log_reader_->ReadNext();
      LOG(INFO) << next_message_->name();
    } catch (std::runtime_error& e) {
      if (configuration_.loop()) {
        log_reader_.reset(new EventLogReader(configuration_.log()));
        next_message_.reset();
        io_service_.post(
            [this] { this->log_read_and_send(boost::system::error_code()); });
        return;
      } else {
        throw;
      }
    }
    if (!last_message_stamp_) {
      last_message_stamp_ = next_message_->stamp();
    }

    log_timer_.expires_from_now(std::chrono::microseconds(

        int64_t(ToChronoDuration(next_message_->stamp() - *last_message_stamp_)
                    .count() /
                configuration_.speed())));
    log_timer_.async_wait(std::bind(&IpcLogPlayback::log_read_and_send, this,
                                    std::placeholders::_1));
    last_message_stamp_ = next_message_->stamp();
  }

  void run() {
    while (status_.has_input_required_configuration()) {
      bus_.get_io_service().run_one();
    }
    log_reader_.reset(new EventLogReader(configuration_.log()));
    log_read_and_send(boost::system::error_code());

    bus_.get_io_service().run();
  }

 private:
  boost::asio::io_service& io_service_;
  EventBus& bus_;
  boost::asio::steady_timer status_timer_;
  boost::asio::steady_timer log_timer_;

  LogPlaybackConfiguration configuration_;
  LogPlaybackStatus status_;
  std::unique_ptr<EventLogReader> log_reader_;
  boost::optional<google::protobuf::Timestamp> last_message_stamp_;
  boost::optional<farm_ng::core::Event> next_message_;
  std::map<std::string, MessageStats> message_stats_;
};

}  // namespace core
}  // namespace farm_ng

void Cleanup(farm_ng::core::EventBus& bus) {}

int Main(farm_ng::core::EventBus& bus) {
  farm_ng::core::LogPlaybackConfiguration configuration;
  configuration.set_loop(FLAGS_loop);
  configuration.mutable_log()->set_path(FLAGS_log);
  configuration.mutable_log()->set_content_type(
      "application/farm_ng.eventlog.v1");
  configuration.set_send(FLAGS_send);
  configuration.set_speed(FLAGS_speed);
  farm_ng::core::IpcLogPlayback playback(bus, configuration, FLAGS_interactive);
  playback.run();
  return EXIT_SUCCESS;
}

int main(int argc, char* argv[]) {
  return farm_ng::core::Main(argc, argv, &Main, &Cleanup);
}

max_stars_repo_name: ethanrublee/tractor

max_issues_repo_name: ethanrublee/tractor

max_forks_repo_name: ethanrublee/tractor


text:
#include "Server.h"
#include <ctime>
#include <iostream>
#include <string>
#include <boost/bind/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <deque>
#include "Connection.h"

using boost::asio::ip::tcp;

struct tcp_server::tcp_server_impl {

   tcp_server_impl(){}

   void init(){
       io_context = std::make_unique<boost::asio::io_context>();
       acceptor = std::make_unique<tcp::acceptor>(*io_context, tcp::endpoint(tcp::v4(), 65432));
   }

   std::unique_ptr<boost::asio::io_context> io_context;
   std::unique_ptr<tcp::acceptor> acceptor;
   std::vector<tcp_connection::pointer> connections;
   std::deque<tcp_connection::pointer> waiting_conns;
   std::mutex mutex;
   std::optional<channel_callback> on_new_connection_callback;

   void run(){
      init();
      start_accept();
      io_context->run();
   }

   void start_accept() {
       tcp_connection::pointer new_connection = tcp_connection::create(*io_context);
       acceptor->async_accept(new_connection->socket(),
           boost::bind(&tcp_server_impl::handle_accept, this, new_connection,
             boost::asio::placeholders::error));
   }

   void handle_accept(tcp_connection::pointer new_connection,
                      const boost::system::error_code& error) {
       if (!error) {
         new_connection->start();
         waiting_conns.push_back(new_connection);
       }
       start_accept();
   }

};

tcp_server::tcp_server(): impl(new tcp_server_impl()) {}

tcp_server::~tcp_server(){
    delete impl;
}

void tcp_server::start() {
  try {
    auto t = boost::thread([this]() {
        impl->run();
    });
    t.detach();
  }
  catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  }
}

void tcp_server::update() {
    const std::lock_guard<std::mutex> lock(impl->mutex);
    while (!impl->waiting_conns.empty()){
        auto connection = impl->waiting_conns.front();
        impl->connections.push_back(connection);
        impl->waiting_conns.pop_front();
        if (impl->on_new_connection_callback.has_value()){
            auto channel = connection->get_channel();
            impl->on_new_connection_callback.value()(channel);
        }
    }
    impl->connections.erase(std::remove_if(impl->connections.begin(),
                            impl->connections.end(),
                            [](tcp_connection::pointer conn_ptr){return !conn_ptr->is_alive();}),
                            impl->connections.end());
    for (auto conn : impl->connections){
        conn->update();
    }
}

void tcp_server::on_new_connection(channel_callback callback) {
    impl->on_new_connection_callback = callback;
}


text: #include <boost/smart_ptr/scoped_ptr.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "generator/mwm_diff/diff.hpp"

#include "base/assert.hpp"
#include "base/cancellable.hpp"

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wreorder"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-local-typedef"
#endif

#include "pyhelpers/module_version.hpp"

#include <boost/python.hpp>

#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#pragma GCC diagnostic pop

using namespace std;

namespace
{
// Applies the diff at |diffPath| to the mwm at |oldMwmPath|. The resulting
// mwm is stored at |newMwmPath|.
// It is assumed that the file at |oldMwmPath| is a valid mwm and the file
// at |diffPath| is a valid mwmdiff.
// Returns true on success and false on failure.
bool ApplyDiff(string const & oldMwmPath, string const & newMwmPath, string const & diffPath)
{
  base::Cancellable cancellable;
  auto const result = generator::mwm_diff::ApplyDiff(oldMwmPath, newMwmPath, diffPath, cancellable);

  switch (result)
  {
  case generator::mwm_diff::DiffApplicationResult::Ok:
    return true;
  case generator::mwm_diff::DiffApplicationResult::Failed:
    return false;
  case generator::mwm_diff::DiffApplicationResult::Cancelled:
    UNREACHABLE();
    break;
  }

  UNREACHABLE();
}
}  // namespace

BOOST_PYTHON_MODULE(pymwm_diff)
{
  using namespace boost::python;
  scope().attr("__version__") = PYBINDINGS_VERSION;

  def("make_diff", generator::mwm_diff::MakeDiff);
  def("apply_diff", ApplyDiff);
}

max_stars_repo_name: kudlav/organicmaps

max_issues_repo_name: mbrukman/omim

max_forks_repo_name: mbrukman/omim


text:
#ifndef LIBKRIGING_ORDINARYKRIGING_HPP
#define LIBKRIGING_ORDINARYKRIGING_HPP

#include <armadillo>

#include "libKriging/libKriging_exports.h"
// #include "covariance.h"

/** Ordinary kriging regression
 * @ingroup Regression
 */
class OrdinaryKriging {
 public:
  struct Parameters {
    double sigma2;
    bool has_sigma2;
    arma::vec theta;
    bool has_theta;
  };

  enum class RegressionModel { Constant, Linear, Quadratic };

  struct RegressionModelUtils {
    LIBKRIGING_EXPORT static RegressionModel fromString(const std::string & s);
    LIBKRIGING_EXPORT static std::string toString(const RegressionModel & m);
  };

  const arma::mat& X() const { return m_X; };
  const arma::rowvec& centerX() const { return m_centerX; };
  const arma::rowvec& scaleX() const { return m_scaleX; };
  const arma::colvec& y() const { return m_y; };
  const double& centerY() const { return m_centerY; };
  const double& scaleY() const { return m_scaleY; };
  const RegressionModel& regmodel() const { return m_regmodel; };
  const arma::mat& F() const { return m_F; };
  const arma::mat& T() const { return m_T; };
  const arma::mat& M() const { return m_M; };
  const arma::colvec& z() const { return m_z; };
  const arma::colvec& beta() const { return m_beta; };
  const arma::vec& theta() const { return m_theta; };
  const double& sigma2() const { return m_sigma2; };

 private:
  arma::mat m_X;
  arma::rowvec m_centerX;
  arma::rowvec m_scaleX;
  arma::colvec m_y;
  double m_centerY;
  double m_scaleY;
  RegressionModel m_regmodel;
  arma::mat m_F;
  arma::mat m_T;
  arma::mat m_M;
  arma::colvec m_z;
  arma::colvec m_beta;
  arma::vec m_theta;
  double m_sigma2;

  std::function<double(const arma::vec&, const arma::vec&)> CovNorm_fun;  // Covariance function on normalized data
  std::function<double(const arma::vec&, const arma::vec&, int)>
      CovNorm_deriv;  // Covariance function derivative vs. theta

  // returns distance matrix form Xp to X
  LIBKRIGING_EXPORT arma::mat Cov(const arma::mat& X, const arma::mat& Xp);
  LIBKRIGING_EXPORT arma::mat Cov(const arma::mat& X);
  //  // same for one point
  //  LIBKRIGING_EXPORT arma::colvec Cov(const arma::mat& X, const arma::rowvec& x, const arma::colvec& theta);

  // This will create the dist(xi,xj) function above. Need to parse "kernel".
  void make_Cov(const std::string& covType);

 public:
  struct OKModel {
    arma::colvec y;
    arma::mat X;
    arma::mat F;
    arma::mat T;
    arma::mat M;
    arma::colvec z;
    arma::colvec beta;
    std::function<double(const arma::vec&, const arma::vec&)> covnorm_fun;
    std::function<double(const arma::vec&, const arma::vec&, int)> covnorm_deriv;
  };

  // LIBKRIGING_EXPORT double fit_ofn(const arma::vec& theta, arma::vec* grad_out, OKModel* okm_data);

  // at least, just call make_dist(kernel)
  LIBKRIGING_EXPORT OrdinaryKriging();  // const std::string & covType);

  /** Fit the kriging object on (X,y):
   * @param y is n length column vector of output
   * @param X is n*d matrix of input
   * @param regmodel is the regression model to be used for the GP mean (choice between contant, linear, quadratic)
   * @param parameters is starting value for hyper-parameters
   * @param optim_method is an optimizer name from OptimLib, or 'none' to keep parameters unchanged
   * @param optim_objective is 'loo' or 'loglik'. Ignored if optim_method=='none'.
   */
  LIBKRIGING_EXPORT void fit(const arma::colvec& y,
                             const arma::mat& X,
                             const RegressionModel& regmodel = RegressionModel::Constant,
                             bool normalize = false);  //,
  // const Parameters& parameters,
  // const std::string& optim_method,
  // const std::string& optim_objective);

  LIBKRIGING_EXPORT double logLikelihood(const arma::vec& theta);
  LIBKRIGING_EXPORT arma::vec logLikelihoodGrad(const arma::vec& theta);
  LIBKRIGING_EXPORT double loofun(const arma::vec& theta);
  LIBKRIGING_EXPORT arma::vec loofungrad(const arma::vec& theta);

  /** Compute the prediction for given points X'
   * @param Xp is m*d matrix of points where to predict output
   * @param std is true if return also stdev column vector
   * @param cov is true if return also cov matrix between Xp
   * @return output prediction: m means, [m standard deviations], [m*m full covariance matrix]
   */
  LIBKRIGING_EXPORT std::tuple<arma::colvec, arma::colvec, arma::mat> predict(const arma::mat& Xp,
                                                                              bool withStd,
                                                                              bool withCov);

  /** Draw sample trajectories of kriging at given points X'
   * @param Xp is m*d matrix of points where to simulate output
   * @param nsim is number of simulations to draw
   * @return output is m*nsim matrix of simulations at Xp
   */
  LIBKRIGING_EXPORT arma::mat simulate(const int nsim, const arma::mat& Xp, bool cond = true);

  /** Add new conditional data points to previous (X,y)
   * @param newy is m length column vector of new output
   * @param newX is m*d matrix of new input
   * @param optim_method is an optimizer name from OptimLib, or 'none' to keep previously estimated parameters unchanged
   * @param optim_objective is 'loo' or 'loglik'. Ignored if optim_method=='none'.
   */
  LIBKRIGING_EXPORT void update(const arma::vec& newy,
                                const arma::mat& newX,
                                const std::string& optim_method,
                                const std::string& optim_objective);
};

#endif  // LIBKRIGING_ORDINARYKRIGING_HPP

max_stars_repo_name: SebastienDaVeiga/libKriging

max_issues_repo_name: SebastienDaVeiga/libKriging

max_forks_repo_name: SebastienDaVeiga/libKriging


text:
/*
 * libfscp - C++ portable OpenSSL cryptographic wrapper library.
 * Copyright (C) 2010-2011 Julien Kauffmann <julien.kauffmann@freelan.org>
 *
 * This file is part of libfscp.
 *
 * libfscp is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * libfscp 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 GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In addition, 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 two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  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 here.
 *
 * If you intend to use libfscp in a commercial software, please
 * contact me : we may arrange this for a small fee or no fee at all,
 * depending on the nature of your project.
 */

/**
 * \file shared_buffer.hpp
 * \author Julien Kauffmann <julien.kauffmann@freelan.org>
 * \brief A shared buffer class.
 */

#pragma once

#include <boost/asio.hpp>
#include <boost/shared_array.hpp>
#include <boost/function.hpp>

#include <cmath>
#include <stdint.h>

namespace fscp
{
	class SharedBuffer;

	boost::asio::mutable_buffers_1 buffer(const SharedBuffer&);
	boost::asio::mutable_buffers_1 buffer(const SharedBuffer&, size_t);
	template <typename Type> Type buffer_cast(const SharedBuffer&);
	size_t buffer_size(const SharedBuffer&);

	class SharedBuffer
	{
		public:
			SharedBuffer(size_t size) :
				m_size(size),
				m_data(new uint8_t[size])
			{}

			template <typename Handler>
			SharedBuffer(const SharedBuffer& buffer, Handler handler) :
				m_buffer(new SharedBuffer(buffer), [handler] (SharedBuffer* buf) {
					handler(*buf);

					delete buf;
				})
			{
			}

		private:
			size_t m_size;
			boost::shared_array<uint8_t> m_data;
			boost::shared_ptr<SharedBuffer> m_buffer;

			friend inline boost::asio::mutable_buffers_1 buffer(const SharedBuffer& buf)
			{
				if (buf.m_buffer)
				{
					return buffer(*(buf.m_buffer));
				}
				else
				{
					return boost::asio::buffer(buf.m_data.get(), buf.m_size);
				}
			}

			friend inline boost::asio::mutable_buffers_1 buffer(const SharedBuffer& buf, size_t size)
			{
				if (buf.m_buffer)
				{
					return buffer(*(buf.m_buffer), size);
				}
				else
				{
					return boost::asio::buffer(buf.m_data.get(), std::min(size, buf.m_size));
				}
			}

			template <typename Type>
			friend inline Type buffer_cast(const SharedBuffer& buf)
			{
				if (buf.m_buffer)
				{
					return buffer_cast<Type>(*(buf.m_buffer));
				}
				else
				{
					return boost::asio::buffer_cast<Type>(buffer(buf));
				}
			}

			friend inline size_t buffer_size(const SharedBuffer& buf)
			{
				if (buf.m_buffer)
				{
					return buffer_size((*buf.m_buffer));
				}
				else
				{
					return boost::asio::buffer_size(buffer(buf));
				}
			}
	};

	template <typename Handler>
	class SharedBufferHandler
	{
		public:

			typedef void result_type;

			SharedBufferHandler(SharedBuffer buf, Handler handler) :
				m_buffer(buf),
				m_handler(handler)
			{}

			result_type operator()()
			{
				m_handler();
			}

			template <typename Arg1>
			result_type operator()(Arg1 arg1)
			{
				m_handler(arg1);
			}

			template <typename Arg1, typename Arg2>
			result_type operator()(Arg1 arg1, Arg2 arg2)
			{
				m_handler(arg1, arg2);
			}

		private:

			SharedBuffer m_buffer;
			Handler m_handler;
	};

	template <typename Handler>
	inline SharedBufferHandler<Handler> make_shared_buffer_handler(SharedBuffer buf, Handler handler)
	{
		return SharedBufferHandler<Handler>(buf, handler);
	}
}

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL


text:
/*
	This file is part of solidity.

	solidity is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	solidity 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
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2015
 * Tests for a fixed fee registrar contract.
 */

#include <string>
#include <tuple>
#include <boost/test/unit_test.hpp>
#include <test/libsolidity/SolidityExecutionFramework.h>

using namespace std;
using namespace dev::test;

namespace dev
{
namespace solidity
{
namespace test
{

namespace
{

static char const* registrarCode = R"DELIMITER(
pragma solidity ^0.4.0;

contract NameRegister {
	function addr(string _name) constant returns (address o_owner);
	function name(address _owner) constant returns (string o_name);
}

contract Registrar is NameRegister {
	event Changed(string indexed name);
	event PrimaryChanged(string indexed name, address indexed addr);

	function owner(string _name) constant returns (address o_owner);
	function addr(string _name) constant returns (address o_address);
	function subRegistrar(string _name) constant returns (address o_subRegistrar);
	function content(string _name) constant returns (bytes32 o_content);

	function name(address _owner) constant returns (string o_name);
}

contract AuctionSystem {
	event AuctionEnded(string indexed _name, address _winner);
	event NewBid(string indexed _name, address _bidder, uint _value);

	/// Function that is called once an auction ends.
	function onAuctionEnd(string _name) internal;

	function bid(string _name, address _bidder, uint _value) internal {
		var auction = m_auctions[_name];
		if (auction.endDate > 0 && now > auction.endDate)
		{
			AuctionEnded(_name, auction.highestBidder);
			onAuctionEnd(_name);
			delete m_auctions[_name];
			return;
		}
		if (msg.value > auction.highestBid)
		{
			// new bid on auction
			auction.secondHighestBid = auction.highestBid;
			auction.sumOfBids += _value;
			auction.highestBid = _value;
			auction.highestBidder = _bidder;
			auction.endDate = now + c_biddingTime;

			NewBid(_name, _bidder, _value);
		}
	}

	uint constant c_biddingTime = 7 days;

	struct Auction {
		address highestBidder;
		uint highestBid;
		uint secondHighestBid;
		uint sumOfBids;
		uint endDate;
	}
	mapping(string => Auction) m_auctions;
}

contract GlobalRegistrar is Registrar, AuctionSystem {
	struct Record {
		address owner;
		address primary;
		address subRegistrar;
		bytes32 content;
		uint renewalDate;
	}

	uint constant c_renewalInterval = 1 years;
	uint constant c_freeBytes = 12;

	function Registrar() {
		// TODO: Populate with hall-of-fame.
	}

	function onAuctionEnd(string _name) internal {
		var auction = m_auctions[_name];
		var record = m_toRecord[_name];
		var previousOwner = record.owner;
		record.renewalDate = now + c_renewalInterval;
		record.owner = auction.highestBidder;
		Changed(_name);
		if (previousOwner != 0) {
			if (!record.owner.send(auction.sumOfBids - auction.highestBid / 100))
				throw;
		} else {
			if (!auction.highestBidder.send(auction.highestBid - auction.secondHighestBid))
				throw;
		}
	}

	function reserve(string _name) external payable {
		if (bytes(_name).length == 0)
			throw;
		bool needAuction = requiresAuction(_name);
		if (needAuction)
		{
			if (now < m_toRecord[_name].renewalDate)
				throw;
			bid(_name, msg.sender, msg.value);
		} else {
			Record record = m_toRecord[_name];
			if (record.owner != 0)
				throw;
			m_toRecord[_name].owner = msg.sender;
			Changed(_name);
		}
	}

	function requiresAuction(string _name) internal returns (bool) {
		return bytes(_name).length < c_freeBytes;
	}

	modifier onlyrecordowner(string _name) { if (m_toRecord[_name].owner == msg.sender) _; }

	function transfer(string _name, address _newOwner) onlyrecordowner(_name) {
		m_toRecord[_name].owner = _newOwner;
		Changed(_name);
	}

	function disown(string _name) onlyrecordowner(_name) {
		if (stringsEqual(m_toName[m_toRecord[_name].primary], _name))
		{
			PrimaryChanged(_name, m_toRecord[_name].primary);
			m_toName[m_toRecord[_name].primary] = "";
		}
		delete m_toRecord[_name];
		Changed(_name);
	}

	function setAddress(string _name, address _a, bool _primary) onlyrecordowner(_name) {
		m_toRecord[_name].primary = _a;
		if (_primary)
		{
			PrimaryChanged(_name, _a);
			m_toName[_a] = _name;
		}
		Changed(_name);
	}
	function setSubRegistrar(string _name, address _registrar) onlyrecordowner(_name) {
		m_toRecord[_name].subRegistrar = _registrar;
		Changed(_name);
	}
	function setContent(string _name, bytes32 _content) onlyrecordowner(_name) {
		m_toRecord[_name].content = _content;
		Changed(_name);
	}

	function stringsEqual(string storage _a, string memory _b) internal returns (bool) {
		bytes storage a = bytes(_a);
		bytes memory b = bytes(_b);
		if (a.length != b.length)
			return false;
		// @todo unroll this loop
		for (uint i = 0; i < a.length; i ++)
			if (a[i] != b[i])
				return false;
		return true;
	}

	function owner(string _name) constant returns (address) { return m_toRecord[_name].owner; }
	function addr(string _name) constant returns (address) { return m_toRecord[_name].primary; }
	function subRegistrar(string _name) constant returns (address) { return m_toRecord[_name].subRegistrar; }
	function content(string _name) constant returns (bytes32) { return m_toRecord[_name].content; }
	function name(address _addr) constant returns (string o_name) { return m_toName[_addr]; }

	mapping (address => string) m_toName;
	mapping (string => Record) m_toRecord;
}
)DELIMITER";

static unique_ptr<bytes> s_compiledRegistrar;

class AuctionRegistrarTestFramework: public SolidityExecutionFramework
{
protected:
	void deployRegistrar()
	{
		if (!s_compiledRegistrar)
		{
			m_compiler.reset(false);
			m_compiler.addSource("", registrarCode);
			m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns);
			BOOST_REQUIRE_MESSAGE(m_compiler.compile(), "Compiling contract failed");
			s_compiledRegistrar.reset(new bytes(m_compiler.object("GlobalRegistrar").bytecode));
		}
		sendMessage(*s_compiledRegistrar, true);
		BOOST_REQUIRE(!m_output.empty());
	}

	using ContractInterface = SolidityExecutionFramework::ContractInterface;
	class RegistrarInterface: public ContractInterface
	{
	public:
		RegistrarInterface(SolidityExecutionFramework& _framework): ContractInterface(_framework) {}
		void reserve(string const& _name)
		{
			callString("reserve", _name);
		}
		u160 owner(string const& _name)
		{
			return callStringReturnsAddress("owner", _name);
		}
		void setAddress(string const& _name, u160 const& _address, bool _primary)
		{
			callStringAddressBool("setAddress", _name, _address, _primary);
		}
		u160 addr(string const& _name)
		{
			return callStringReturnsAddress("addr", _name);
		}
		string name(u160 const& _addr)
		{
			return callAddressReturnsString("name", _addr);
		}
		void setSubRegistrar(string const& _name, u160 const& _address)
		{
			callStringAddress("setSubRegistrar", _name, _address);
		}
		u160 subRegistrar(string const& _name)
		{
			return callStringReturnsAddress("subRegistrar", _name);
		}
		void setContent(string const& _name, h256 const& _content)
		{
			callStringBytes32("setContent", _name, _content);
		}
		h256 content(string const& _name)
		{
			return callStringReturnsBytes32("content", _name);
		}
		void transfer(string const& _name, u160 const& _target)
		{
			return callStringAddress("transfer", _name, _target);
		}
		void disown(string const& _name)
		{
			return callString("disown", _name);
		}
	};

	size_t const m_biddingTime = size_t(7 * 24 * 3600);
	size_t const m_renewalInterval = size_t(365 * 24 * 3600);
};

}

/// This is a test suite that tests optimised code!
BOOST_FIXTURE_TEST_SUITE(SolidityAuctionRegistrar, AuctionRegistrarTestFramework)

BOOST_AUTO_TEST_CASE(creation)
{
	deployRegistrar();
}

BOOST_AUTO_TEST_CASE(reserve)
{
	// Test that reserving works for long strings
	deployRegistrar();
	vector<string> names{"abcabcabcabcabc", "defdefdefdefdef", "ghighighighighighighighighighighighighighighi"};

	RegistrarInterface registrar(*this);

	// should not work
	registrar.reserve("");
	BOOST_CHECK_EQUAL(registrar.owner(""), u160(0));

	for (auto const& name: names)
	{
		registrar.reserve(name);
		BOOST_CHECK_EQUAL(registrar.owner(name), u160(m_sender));
	}
}

BOOST_AUTO_TEST_CASE(double_reserve_long)
{
	// Test that it is not possible to re-reserve from a different address.
	deployRegistrar();
	string name = "abcabcabcabcabcabcabcabcabcabca";
	RegistrarInterface registrar(*this);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), m_sender);

	sendEther(account(1), u256(10) * ether);
	m_sender = account(1);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), account(0));
}

BOOST_AUTO_TEST_CASE(properties)
{
	// Test setting and retrieving  the various properties works.
	deployRegistrar();
	RegistrarInterface registrar(*this);
	string names[] = {"abcaeouoeuaoeuaoeu", "defncboagufra,fui", "ghagpyajfbcuajouhaeoi"};
	size_t addr = 0x9872543;
	size_t count = 1;
	for (string const& name: names)
	{
		m_sender = account(0);
		sendEther(account(count), u256(20) * ether);
		m_sender = account(count);
		auto sender = m_sender;
		addr += count;
		// setting by sender works
		registrar.reserve(name);
		BOOST_CHECK_EQUAL(registrar.owner(name), sender);
		registrar.setAddress(name, addr, true);
		BOOST_CHECK_EQUAL(registrar.addr(name), u160(addr));
		registrar.setSubRegistrar(name, addr + 20);
		BOOST_CHECK_EQUAL(registrar.subRegistrar(name), u160(addr + 20));
		registrar.setContent(name, h256(u256(addr + 90)));
		BOOST_CHECK_EQUAL(registrar.content(name), h256(u256(addr + 90)));

		// but not by someone else
		m_sender = account(count - 1);
		BOOST_CHECK_EQUAL(registrar.owner(name), sender);
		registrar.setAddress(name, addr + 1, true);
		BOOST_CHECK_EQUAL(registrar.addr(name), u160(addr));
		registrar.setSubRegistrar(name, addr + 20 + 1);
		BOOST_CHECK_EQUAL(registrar.subRegistrar(name), u160(addr + 20));
		registrar.setContent(name, h256(u256(addr + 90 + 1)));
		BOOST_CHECK_EQUAL(registrar.content(name), h256(u256(addr + 90)));
		count++;
	}
}

BOOST_AUTO_TEST_CASE(transfer)
{
	deployRegistrar();
	string name = "abcaoeguaoucaeoduceo";
	RegistrarInterface registrar(*this);
	registrar.reserve(name);
	registrar.setContent(name, h256(u256(123)));
	registrar.transfer(name, u160(555));
	BOOST_CHECK_EQUAL(registrar.owner(name), u160(555));
	BOOST_CHECK_EQUAL(registrar.content(name), h256(u256(123)));
}

BOOST_AUTO_TEST_CASE(disown)
{
	deployRegistrar();
	string name = "abcaoeguaoucaeoduceo";

	RegistrarInterface registrar(*this);
	registrar.reserve(name);
	registrar.setContent(name, h256(u256(123)));
	registrar.setAddress(name, u160(124), true);
	registrar.setSubRegistrar(name, u160(125));
	BOOST_CHECK_EQUAL(registrar.name(u160(124)), name);

	// someone else tries disowning
	sendEther(account(1), u256(10) * ether);
	m_sender = account(1);
	registrar.disown(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), account(0));

	m_sender = account(0);
	registrar.disown(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), 0);
	BOOST_CHECK_EQUAL(registrar.addr(name), 0);
	BOOST_CHECK_EQUAL(registrar.subRegistrar(name), 0);
	BOOST_CHECK_EQUAL(registrar.content(name), h256());
	BOOST_CHECK_EQUAL(registrar.name(u160(124)), "");
}

BOOST_AUTO_TEST_CASE(auction_simple)
{
	deployRegistrar();
	string name = "x";

	RegistrarInterface registrar(*this);
	// initiate auction
	registrar.setNextValue(8);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), 0);
	// "wait" until auction end
	m_rpc.test_modifyTimestamp(currentTimestamp() + m_biddingTime + 10);
	// trigger auction again
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), m_sender);
}

BOOST_AUTO_TEST_CASE(auction_bidding)
{
	deployRegistrar();
	string name = "x";

	unsigned startTime = 0x776347e2;
	m_rpc.test_modifyTimestamp(startTime);

	RegistrarInterface registrar(*this);
	// initiate auction
	registrar.setNextValue(8);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), 0);
	// overbid self
	m_rpc.test_modifyTimestamp(startTime + m_biddingTime - 10);
	registrar.setNextValue(12);
	registrar.reserve(name);
	// another bid by someone else
	sendEther(account(1), 10 * ether);
	m_sender = account(1);
	m_rpc.test_modifyTimestamp(startTime + 2 * m_biddingTime - 50);
	registrar.setNextValue(13);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), 0);
	// end auction by first bidder (which is not highest) trying to overbid again (too late)
	m_sender = account(0);
	m_rpc.test_modifyTimestamp(startTime + 4 * m_biddingTime);
	registrar.setNextValue(20);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), account(1));
}

BOOST_AUTO_TEST_CASE(auction_renewal)
{
	deployRegistrar();

	string name = "x";
	RegistrarInterface registrar(*this);
	size_t startTime = currentTimestamp();
	// register name by auction
	registrar.setNextValue(8);
	registrar.reserve(name);
	m_rpc.test_modifyTimestamp(startTime + 4 * m_biddingTime);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), m_sender);

	// try to re-register before interval end
	sendEther(account(1), 10 * ether);
	m_sender = account(1);
	m_rpc.test_modifyTimestamp(currentTimestamp() + m_renewalInterval - 1);
	registrar.setNextValue(80);
	registrar.reserve(name);
	m_rpc.test_modifyTimestamp(currentTimestamp() + m_biddingTime);
	// if there is a bug in the renewal logic, this would transfer the ownership to account(1),
	// but if there is no bug, this will initiate the auction, albeit with a zero bid
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), account(0));

	registrar.setNextValue(80);
	registrar.reserve(name);
	BOOST_CHECK_EQUAL(registrar.owner(name), account(1));
}

BOOST_AUTO_TEST_SUITE_END()

}
}
} // end namespaces

max_stars_repo_name: jansenbarabona/NFT-Game-Development

max_issues_repo_name: jansenbarabona/NFT-Game-Development

max_forks_repo_name: jansenbarabona/NFT-Game-Development


text:
//
//  Created by Robert Binna
//
#include <iostream>
#include <map>
#include <typeinfo>

#include <boost/test/unit_test.hpp>

#include <idx/contenthelpers/IdentityKeyExtractor.hpp>

#include <idx/maphelpers/MapValueExtractor.hpp>

namespace idx { namespace maphelpers {

BOOST_AUTO_TEST_SUITE(MapValueExtractorTest)

BOOST_AUTO_TEST_CASE(testExtractValueForIdentityMapExtractor) {
	MapValueExtractor<uint64_t, idx::contenthelpers::IdentityKeyExtractor> extractValue;

	uint64_t extractedValue = extractValue(0ul);

	BOOST_REQUIRE(extractedValue == 0ul);
}

BOOST_AUTO_TEST_CASE(testExtractValueFromPair) {
	MapValueExtractor<std::pair<uint64_t, int32_t>, idx::contenthelpers::PairKeyExtractor> extractValue;

	BOOST_REQUIRE_EQUAL(extractValue({ 42u, -34 }), -34);
	BOOST_REQUIRE_EQUAL(extractValue({ 42u, 22 }), 22);
}

BOOST_AUTO_TEST_CASE(testExtractValueFromPionterPair) {
	MapValueExtractor<std::pair<uint64_t, int32_t>*, idx::contenthelpers::PairPointerKeyExtractor> extractValue;

	std::pair<uint64_t, int32_t> firstPair = { 42u, -815 };
	std::pair<uint64_t, int32_t> secondPair = { 13u, 10 };

	BOOST_REQUIRE_EQUAL(extractValue(&firstPair), &firstPair);
	BOOST_REQUIRE_EQUAL(extractValue(&secondPair), &secondPair);
}

BOOST_AUTO_TEST_SUITE_END()

}}

max_stars_repo_name: yishayahu/hot

max_issues_repo_name: SheldonZhong/hot

max_forks_repo_name: SheldonZhong/hot


text:
#include <stdio.h>
#include <unistd.h>
#include <cstdlib>
#include <assert.h>
#include <iostream>

#include <boost/filesystem.hpp>

FILE * FopenNN(const std::string & aName,const char * aMode)
{
   FILE * aFp = fopen(aName.c_str(),aMode);
   assert(aFp!=0);
   return aFp;
}

using namespace boost::filesystem;

int main(int,char **)
{
   char aSep = path::preferred_separator;
   char Buf[1024];
   getcwd(Buf,1000);
   FILE * aFp =FopenNN("../src/ResultInstall/ResultInstall.cpp","w");
   fprintf(aFp,"#include <string> \n ");
   fprintf(aFp,"namespace MMVII {\n ");
   fprintf(aFp,"  const std::string DirBin2007=\"%s%c\";\n",Buf,aSep);
   fprintf(aFp,"};\n");
   fclose(aFp);

   return EXIT_SUCCESS;
}

/*
#include "memory.h"
#include <memory>
#include <fstream>
#include <string>
#include <typeinfo>
#include <vector>
#include <list>
*/

/*
void StrSystem(const std::string & aCom)
{
   int Ok = system(aCom.c_str());
   assert(Ok==EXIT_SUCCESS);
}

std::string GetLineFromFile(const std::string & aName)
{
   std::string aRes;
   FILE * aFp = FopenNN(aName);
   bool cont=true;
   while(cont)
   {
       int aC = fgetc(aFp);
       if(isspace(aC) || isblank(aC) || aC==EOF)
         cont = false;
       else
          aRes += aC;
   }
   fclose(aFp);
   return aRes;
}

std::string GetPWD()
{
   std::string PDWFile="PWD.txt";
   StrSystem("pwd >"+PDWFile);
   std::string PWDLine = GetLineFromFile(PDWFile);
   return PWDLine;
}
*/

max_stars_repo_name: kikislater/micmac

max_issues_repo_name: kikislater/micmac

max_forks_repo_name: kikislater/micmac


text:
#include <algorithm>
#include <boost/asio/dispatch.hpp>
#include <boost/asio/strand.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/config.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>

#include "experimental/network/mime.hpp"
#include "experimental/network/url.hpp"

namespace beast = boost::beast;
namespace asio = boost::asio;

// This function produces an HTTP response for the given request. The type of
// the response object depends on the contents of the request, so the interface
// requires the caller to pass a generic lambda for receiving the response.
template <class Body, class Allocator, class Send>
void handle_request(
    beast::string_view doc_root,
    beast::http::request<Body, beast::http::basic_fields<Allocator>> &&req,
    Send &&send) {
  namespace http = beast::http;

  // Returns a bad request response.
  const auto bad_request = [&req](beast::string_view why) {
    http::response<http::string_body> res{http::status::bad_request,
                                          req.version()};
    res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
    res.set(http::field::content_type, "text/html");
    res.keep_alive(req.keep_alive());
    res.body() = std::string(why);
    res.prepare_payload();
    return res;
  };

  // Return a not found response.
  const auto not_found = [&req](beast::string_view target) {
    http::response<http::string_body> res{http::status::not_found,
                                          req.version()};
    res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
    res.set(http::field::content_type, "text/html");
    res.keep_alive(req.keep_alive());
    res.body() = "The resource '" + std::string(target) + "' was not found.";
    res.prepare_payload();
    return res;
  };

  // Returns a server error response.
  const auto server_error = [&req](beast::string_view what) {
    http::response<http::string_body> res{http::status::internal_server_error,
                                          req.version()};
    res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
    res.set(http::field::content_type, "text/html");
    res.keep_alive(req.keep_alive());
    res.body() = "An error occurred '" + std::string(what) + "'";
    res.prepare_payload();
    return res;
  };

  // Make sure we can handle the method.
  if (req.method() != http::verb::get && req.method() != http::verb::head) {
    return send(bad_request("Unknown HTTP-method"));
  }

  // Request path must be absolute and not contain "..".
  if (req.target().empty() || req.target()[0] != '/' ||
      req.target().find("..") != beast::string_view::npos) {
    return send(bad_request("Illegal request-target"));
  }

  // Build the path to het requested file.
  std::string path = net::http::url::path_cat(doc_root, req.target());
  if (req.target().back() == '/') {
    path.append("index.html");
  }

  // Attempt to open the file.
  beast::error_code ec;
  http::file_body::value_type body;
  body.open(path.c_str(), beast::file_mode::scan, ec);

  // Handle the case where the file doesn't exist.
  if (ec == beast::errc::no_such_file_or_directory) {
    return send(not_found(req.target()));
  }
  if (ec) {
    return send(server_error(ec.message()));
  }

  // Cache the size since we need it after the move.
  const auto size = body.size();

  // Responsed to HEAD request.
  if (req.method() == http::verb::head) {
    http::response<http::empty_body> res{http::status::ok, req.version()};
    res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
    res.set(http::field::content_type, net::http::mime::type(path));
    res.keep_alive(req.keep_alive());
    return send(std::move(res));
  }

  // Response to GET request.
  http::response<http::file_body> res{
      std::piecewise_construct, std::make_tuple(std::move(body)),
      std::make_tuple(http::status::ok, req.version())};
  res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  res.content_length(size);
  res.keep_alive(req.keep_alive());
  return send(std::move(res));
}

// Report a failure.
void fail(beast::error_code ec, const char *what) {
  std::cerr << what << ": " << ec.message() << "\n";
}

// Handles an HTTP server connection.
class session : public std::enable_shared_from_this<session> {
public:
  // Take ownership of the stream.
  session(asio::ip::tcp::socket &&socket,
          const std::shared_ptr<const std::string> &doc_root)
      : stream_(std::move(socket)), doc_root_(doc_root), lambda_(*this) {}

  // Start the asynchronous operation.
  void run() {
    // We need to be executing within a strand to perform async operations on
    // the I/O objects in this session. Althrough not strictly necessary for
    // single-threaded contexts. this exaple code is written to be thread-safe
    // by default.
    asio::dispatch(
        stream_.get_executor(),
        beast::bind_front_handler(&session::do_read, shared_from_this()));
  }

  void do_read() {
    //  Make the request empty before reading.
    // otherwise the operation behavior is undefined.
    req_ = {};

    // Set te timeout.
    stream_.expires_after(std::chrono::seconds(30));

    // Read a request.
    beast::http::async_read(
        stream_, buffer_, req_,
        beast::bind_front_handler(&session::on_read, shared_from_this()));
  }

  void on_read(beast::error_code ec, std::size_t bytes_trasferred) {
    boost::ignore_unused(bytes_trasferred);

    // This means they closed the connection.
    if (ec == beast::http::error::end_of_stream) {
      return do_close();
    }
    if (ec) {
      return fail(ec, "read");
    }

    // Send the response.
    handle_request(*doc_root_, std::move(req_), lambda_);
  }

  void on_write(bool close, beast::error_code ec,
                std::size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);

    if (ec) {
      return fail(ec, "write");
    }
    if (close) {
      // This means we should close the connection, usually because the response
      // indicated the "Connection: close" semantic.
      return do_close();
    }

    // We're done with the response so delete it.
    res_ = nullptr;

    // Read another request.
    do_read();
  }

  void do_close() {
    // Send a TCP shutdown
    beast::error_code ec;
    stream_.socket().shutdown(asio::ip::tcp::socket::shutdown_send, ec);

    // At this point the connection is closed gracefully.
  }

private:
  // This is C++11 equivalent of a generic lambda.
  // The function object is used to send an HTTP message.
  struct send_lambda {
    session &self_;

    explicit send_lambda(session &self) : self_(self) {}

    template <bool isRequest, class Body, class Fields>
    void operator()(beast::http::message<isRequest, Body, Fields> &&msg) const {
      // The lifetime of the message has to extend for the duration of the async
      // operation so we use a shared_ptr to manage it.
      auto sp = std::make_shared<beast::http::message<isRequest, Body, Fields>>(
          std::move(msg));

      // Store a type-erased version of the shared pointer in the class to keep
      // it alive.
      self_.res_ = sp;

      // Write the response.
      beast::http::async_write(
          self_.stream_, *sp,
          beast::bind_front_handler(&session::on_write,
                                    self_.shared_from_this(), sp->need_eof()));
    }
  };

  beast::tcp_stream stream_;
  beast::flat_buffer buffer_;
  std::shared_ptr<const std::string> doc_root_;
  beast::http::request<beast::http::string_body> req_;
  std::shared_ptr<void> res_;
  send_lambda lambda_;
};

// Accepts incoming connections and launches the sessions.
class listener : public std::enable_shared_from_this<listener> {
public:
  listener(asio::io_context &ioc, asio::ip::tcp::endpoint endpoint,
           const std::shared_ptr<const std::string> &doc_root)
      : ioc_(ioc), acceptor_(asio::make_strand(ioc)), doc_root_(doc_root) {
    beast::error_code ec;

    // Open the acceptor.
    acceptor_.open(endpoint.protocol(), ec);
    if (ec) {
      fail(ec, "open");
      return;
    }

    // Allow addres reuse.
    acceptor_.set_option(asio::socket_base::reuse_address(true), ec);
    if (ec) {
      fail(ec, "set_option");
      return;
    }

    // Bind to the server address.
    acceptor_.bind(endpoint, ec);
    if (ec) {
      fail(ec, "bind");
      return;
    }

    // Start listening for connections.
    acceptor_.listen(asio::socket_base::max_listen_connections, ec);
    if (ec) {
      fail(ec, "listen");
      return;
    }
  }

  // Start accepting incomming connections.
  void run() { do_accept(); }

private:
  void do_accept() {
    // The new connection gets ots own strand.
    acceptor_.async_accept(
        asio::make_strand(ioc_),
        beast::bind_front_handler(&listener::on_accept, shared_from_this()));
  }

  void on_accept(beast::error_code ec, asio::ip::tcp::socket socket) {
    if (ec) {
      fail(ec, "accept");
    } else {
      // Create the session and run it.
      std::make_shared<session>(std::move(socket), doc_root_)->run();
    }

    // Accept another connection.
    do_accept();
  }

  asio::io_context &ioc_;
  asio::ip::tcp::acceptor acceptor_;
  std::shared_ptr<const std::string> doc_root_;
};

int main(int argc, const char *argv[]) {
  // Check command line arguments.
  if (argc != 5) {
    std::cerr << "Usage: beast_http_server_async <address> <port> <doc_root> "
                 "<threads>\n"
              << "Example:\n"
              << " beast_http_server_sync 0.0.0.0 8080 . 1" << std::endl;
    return EXIT_FAILURE;
  }
  const auto address = asio::ip::make_address(argv[1]);
  const auto port = static_cast<std::uint16_t>(std::atoi(argv[2]));
  const auto doc_root = std::make_shared<std::string>(argv[3]);
  const auto threads = std::max<int>(1, std::atoi(argv[4]));

  // The io_context is required for all I/O.
  asio::io_context ioc{threads};

  // Create and launch a listening port.
  std::make_shared<listener>(ioc, asio::ip::tcp::endpoint{address, port},
                             doc_root)
      ->run();

  // Run the I/O service on the requestetd number of threads.
  std::vector<std::thread> v;
  v.reserve(threads - 1);
  for (auto i = threads - 1; i > 0; i--) {
    v.emplace_back([&ioc] { ioc.run(); });
  }
  ioc.run();
  return EXIT_SUCCESS;
}

max_stars_repo_name: mnrn/game-memo

max_issues_repo_name: mnrn/game-memo

max_forks_repo_name: mnrn/game-memo


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

#include <cstdlib>
#include <iostream>

#include <boost/program_options.hpp>

#include <rafi/common.h>

#include "CommandLineOption.h"

namespace po = boost::program_options;

namespace rafi { namespace emu {

namespace {

class CommandLineOptionException
{
public:
    explicit CommandLineOptionException(const char *pArgument)
        : CommandLineOptionException(pArgument, nullptr)
    {
    }

    CommandLineOptionException(const char *pArgument, const char* pMessage)
        : m_pArgument(pArgument)
        , m_pMessage(pMessage)
    {
    }

    virtual void PrintMessage() const
    {
        std::cout << "[CommandLineOptionException] " << m_pArgument;
        if (m_pMessage != nullptr)
        {
            std::cout << " (" << m_pMessage << ")";
        }
        std::cout << std::endl;
    }

private:
    const char* m_pArgument;
    const char* m_pMessage;
};

}

LoadOption::LoadOption(const std::string& arg)
{
    const auto delimPos = arg.find(':');

    if (delimPos == std::string::npos)
    {
        throw CommandLineOptionException(arg.c_str(), "Failed to parse <file:address> pair.");
    }

    m_Path = arg.substr(0, delimPos);

    try
    {
        m_Address = std::strtoull(arg.substr(delimPos + 1).c_str(), nullptr, 16);
    }
    catch (std::out_of_range&)
    {
        throw CommandLineOptionException(arg.c_str(), "Failed to parse address.");
    }

    if (m_Address == 0)
    {
        throw CommandLineOptionException(arg.c_str(), "Failed to parse address or address is 0.");
    }
}

const std::string& LoadOption::GetPath() const
{
    return m_Path;
}

uint64_t LoadOption::GetAddress() const
{
    return m_Address;
}

CommandLineOption::CommandLineOption(int argc, char** argv)
{
    po::options_description desc("options");
    desc.add_options()
        ("cycle", po::value<int>(&m_Cycle)->default_value(0), "number of emulation cycles")
        ("dump-path", po::value<std::string>(), "path of dump file")
        ("dump-skip-cycle", po::value<int>(&m_DumpSkipCycle)->default_value(0), "number of cycles to skip dump")
        ("enable-dump-csr", "output csr contents to dump file")
        ("enable-dump-fp-reg", "output fp register contents to dump file")
        ("enable-dump-memory", "output memory contents to dump file")
        ("gdb", po::value<int>(&m_GdbPort), "enable gdb and specify tcp port")
        ("load", po::value<std::vector<std::string>>(), "path of binary file which is loaded to memory")
        ("help", "show help")
        ("host-io-addr", po::value<std::string>(), "host io address (hex)")
        ("dtb-addr", po::value<std::string>(), "dtb address (hex)")
        ("pc", po::value<std::string>(), "initial program counter value (hex)")
        ("ram-size", po::value<size_t>(&m_RamSize)->default_value(DefaultRamSize), "ram size (byte)")
        ("xlen", po::value<int>(), "XLEN");

    po::variables_map variables;
    try
    {
        po::store(po::parse_command_line(argc, argv, desc), variables);
        po::notify(variables);
    }
    catch (const boost::program_options::error_with_option_name& e)
    {
        std::cout << e.what() << std::endl;
        std::exit(1);
    }

    if (variables.count("help"))
    {
        std::cout << desc << std::endl;
        std::exit(0);
    }

    m_GdbEnabled = variables.count("gdb") > 0;
    m_HostIoEnabled = variables.count("host-io-addr") > 0;

    if (variables.count("dump-path"))
    {
        m_TraceLoggerConfig.enabled = true;
        m_TraceLoggerConfig.enableDumpIntReg = true;
        m_TraceLoggerConfig.enableDumpCsr = variables.count("enable-dump-csr") > 0;
        m_TraceLoggerConfig.enableDumpFpReg = variables.count("enable-dump-fp-reg") > 0;
        m_TraceLoggerConfig.enableDumpCsr = variables.count("enable-memory-csr") > 0;
        m_TraceLoggerConfig.enableDumpMemory = false;
        m_TraceLoggerConfig.enableDumpHostIo = m_HostIoEnabled;
        m_TraceLoggerConfig.path = variables["dump-path"].as<std::string>();
    }
    else
    {
        m_TraceLoggerConfig.enabled = false;
    }

    if (variables.count("dtb-addr"))
    {
        m_DtbAddress = strtoull(variables["dtb-addr"].as<std::string>().c_str(), 0, 16);
    }
    if (variables.count("host-io-addr"))
    {
        m_HostIoAddress = strtoull(variables["host-io-addr"].as<std::string>().c_str(), 0, 16);
    }
    if (variables.count("pc"))
    {
        m_Pc = strtoull(variables["pc"].as<std::string>().c_str(), 0, 16);
    }

    try
    {
        for (auto& str: variables["load"].as<std::vector<std::string>>())
        {
            m_LoadOptions.emplace_back(str);
        }
    }
    catch (CommandLineOptionException e)
    {
        e.PrintMessage();
        exit(1);
    }

    if (variables.count("xlen"))
    {
        switch (variables["xlen"].as<int>())
        {
        case 32:
            m_XLEN = XLEN::XLEN32;
            break;
        case 64:
            m_XLEN = XLEN::XLEN64;
            break;
        default:
            std::cout << "--xlen must be 32 or 64." << std::endl;
            std::exit(0);
            break;
        }
    }
}

bool CommandLineOption::IsHostIoEnabled() const
{
    return m_HostIoEnabled;
}

bool CommandLineOption::IsGdbEnabled() const
{
    return m_GdbEnabled;
}

const TraceLoggerConfig& CommandLineOption::GetTraceLoggerConfig() const
{
    return m_TraceLoggerConfig;
}

const std::vector<LoadOption>& CommandLineOption::GetLoadOptions() const
{
    return m_LoadOptions;
}

XLEN CommandLineOption::GetXLEN() const
{
    return m_XLEN;
}

int CommandLineOption::GetCycle() const
{
    return m_Cycle;
}

int CommandLineOption::GetGdbPort() const
{
    return m_GdbPort;
}

int CommandLineOption::GetDumpSkipCycle() const
{
    return m_DumpSkipCycle;
}

size_t CommandLineOption::GetRamSize() const
{
    return m_RamSize;
}

uint64_t CommandLineOption::GetDtbAddress() const
{
    return m_DtbAddress;
}

uint64_t CommandLineOption::GetHostIoAddress() const
{
    return m_HostIoAddress;
}

uint64_t CommandLineOption::GetPc() const
{
    return m_Pc;
}

}}