text:
#include <completion/CompletionPrinter.h>
#include <support/StringExtras.h>
#include <boost/lexical_cast.hpp>
#include <boost/range/algorithm/transform.hpp>
#include <boost/algorithm/string/join.hpp>
#include <clang/Sema/Sema.h>

using namespace llvm;
using namespace clang;

template <unsigned Kind>
const StringRef getNameImpl(CodeCompletionResult Result);

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Declaration>(CodeCompletionResult Result) {
  auto declaration = Result.Declaration;
  if (!declaration->getIdentifier()) return "";
  return declaration->getIdentifier()->getName();
}

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Keyword>(CodeCompletionResult Result) {
  return Result.Keyword;
}

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Macro>(CodeCompletionResult Result) {
  return Result.Macro->getName();
}

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Pattern>(CodeCompletionResult Result) {
  return Result.Pattern->getAsString();
}

const StringRef getName(CodeCompletionResult Result) {
  switch (Result.Kind) {
  case CodeCompletionResult::RK_Declaration:
    return getNameImpl<CodeCompletionResult::RK_Declaration>(Result);
  case CodeCompletionResult::RK_Keyword:
    return getNameImpl<CodeCompletionResult::RK_Keyword>(Result);
  case CodeCompletionResult::RK_Macro:
    return getNameImpl<CodeCompletionResult::RK_Macro>(Result);
  case CodeCompletionResult::RK_Pattern:
    return getNameImpl<CodeCompletionResult::RK_Pattern>(Result);
  }
  llvm_unreachable("Unknown code completion result Kind.");
}

bool isCompletionAvailable(CodeCompletionResult Result) {
  return Result.Availability == CXAvailability_Available ||
    Result.Availability == CXAvailability_Deprecated;
}

bool CompletionPrinter::isResultFilteredOut(StringRef Filter,
                                            CodeCompletionResult Result) {
  return !isCompletionAvailable(Result) && getName(Result).startswith(Filter);
}

class CompletionCandidate {
public:
  template <class T>
  using PlaceholdersTy = llvm::SmallVector<T, 4>;
  struct Postcompletion {
    std::string PlaceholdersText;
    PlaceholdersTy<unsigned> Positions;
  };
  void setTypedText(const char *value) { addStringValue(TypedText, value); }
  void setResultType(const char *value) { addStringValue(ResultType, value); }
  void setBriefComment(const char *value) { addStringValue(BriefComment, value); }
  void addArgumentToSignature(const char *value) {
    auto sizeBefore = PostcompletionInfo.PlaceholdersText.size();
    addToSignature(value);
    auto sizeAfter = PostcompletionInfo.PlaceholdersText.size();
    if (sizeAfter != sizeBefore)
      addPlaceholderRange(sizeBefore, sizeAfter);
  }
  void addTypedTextToSignature(const char *value) {
    addToSignature(value);
  }
  void addToPostcompletion(const char* value) {
    addStringValue(PostcompletionInfo.PlaceholdersText, value);
  }
  void setPriority(unsigned value) { Priority = value; }
  void addPlaceholderRange(unsigned begin, unsigned end) {
    PostcompletionInfo.Positions.push_back(begin);
    PostcompletionInfo.Positions.push_back(end);
  }

  const std::string &getTypedText() { return TypedText; }
  const std::string &getResultType() { return ResultType; }
  const std::string &getBriefComment() { return BriefComment; }
  const std::string &getSignature() { return Signature; }
  const Postcompletion &getPostcompletion() { return PostcompletionInfo; }
  unsigned getPriority() { return Priority; }
  unsigned getAnnotation() { return TypedText.size(); }
  static CompletionCandidate createOutOf(CodeCompletionString &CCS);
private:
  void addToSignature(const char *value) {
    addStringValue(Signature, value);
    if (TypedTextSet) addToPostcompletion(value);
    TypedTextSet = true;
  }
  void addStringValue(std::string &dst, const char *src) {
    if (src) dst += src;
  }

  bool TypedTextSet = false;
  std::string TypedText      = "",
              ResultType     = "",
              BriefComment   = "",
              Signature      = "";
  unsigned Priority = 0, Annotation = 0;
  Postcompletion PostcompletionInfo;
};

void print(llvm::raw_ostream &OS, const std::string &value) {
  OS << "\"" << value << "\"" << " ";
}

void print(llvm::raw_ostream &OS, unsigned value) {
  OS << value << " ";
}

CompletionCandidate CompletionCandidate::createOutOf(CodeCompletionString &CCS) {
  CompletionCandidate result;
  result.setTypedText(CCS.getTypedText());
  result.setPriority(CCS.getPriority());
  result.setBriefComment(CCS.getBriefComment());
  for (auto chunk : CCS) {
    switch (chunk.Kind) {
    case CodeCompletionString::CK_ResultType:
      result.setResultType(chunk.Text);
      break;
    case CodeCompletionString::CK_Optional:
      break;
    case CodeCompletionString::CK_Placeholder:
      result.addArgumentToSignature(chunk.Text);
      break;
    default:
      result.addTypedTextToSignature(chunk.Text);
    }
  }
  return std::move(result);
}

namespace print {
  auto adapt(const std::string &value) {
    return wrap(value);
  }

  auto adapt(unsigned value) {
    return boost::lexical_cast<std::string>(value);
  }

  template <class Ty>
  auto adapt(const CompletionCandidate::PlaceholdersTy<Ty> &value) {
      CompletionCandidate::PlaceholdersTy<std::string> adaptedValue;
      boost::range::transform(value, std::back_inserter(adaptedValue),
                              [](auto x) { return adapt(x); });
      return boost::algorithm::join(adaptedValue, " ");
  }

  void print(llvm::raw_ostream &OS, const CompletionCandidate::Postcompletion &arg) {
    OS << "(" << adapt(arg.PlaceholdersText);
    auto positions = adapt(arg.Positions);
    OS << (!positions.empty() ? " " : "") << positions << ")";
  }

  template <class ProcessedArgTy, class ...ArgsTy>
  void print(llvm::raw_ostream &OS, ProcessedArgTy arg, ArgsTy... args) {
    OS << adapt(arg) << " ";
    print(OS, args...);
  }
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, CompletionCandidate &candidate) {
  print::print(OS, candidate.getTypedText(),
               candidate.getPriority(),
               candidate.getResultType(),
               candidate.getBriefComment(),
               candidate.getSignature(),
               candidate.getAnnotation(),
               candidate.getPostcompletion());
  return OS;
}

void
CompletionPrinter::ProcessCodeCompleteResults(Sema &SemaRef,
                                              CodeCompletionContext Context,
                                              CodeCompletionResult *Results,
                                              unsigned NumResults) {
  std::stable_sort(Results, Results + NumResults);

  // Print the results.
  OS << "(\n";
  for (unsigned I = 0; I != NumResults; ++I) {
    CompletionCandidate candidate;
    if (CodeCompletionString *CCS
        = Results[I].CreateCodeCompletionString(SemaRef, Context,
                                                    getAllocator(),
                                                    CCTUInfo,
                                                    includeBriefComments())) {
      candidate = CompletionCandidate::createOutOf(*CCS);
    }
  OS << "(" << candidate << ")\n";
  }
  OS << ")\n";
}

static std::string getOverloadAsString(const CodeCompletionString &CCS) {
  std::string Result;
  llvm::raw_string_ostream OS(Result);

  for (auto &C : CCS) {
    switch (C.Kind) {
    case CodeCompletionString::CK_Informative:
    case CodeCompletionString::CK_ResultType:
      OS << "[#" << C.Text << "#]";
      break;

    case CodeCompletionString::CK_CurrentParameter:
      OS << "<#" << C.Text << "#>";
      break;

    default: OS << C.Text; break;
    }
  }
  return OS.str();
}

void
CompletionPrinter::ProcessOverloadCandidates(Sema &SemaRef,
                                             unsigned CurrentArg,
                                             OverloadCandidate *Candidates,
                                             unsigned NumCandidates) {
  for (unsigned I = 0; I != NumCandidates; ++I) {
    if (CodeCompletionString *CCS
          = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
                                                getAllocator(), CCTUInfo,
                                                includeBriefComments())) {
      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
    }
  }
}

max_stars_repo_name: SavchenkoValeriy/rooster

max_issues_repo_name: SavchenkoValeriy/rooster

max_forks_repo_name: SavchenkoValeriy/rooster


text:
#include <string>
#include <vector>
#include <map>
#include <stdexcept>
#include <math.h>
#include <algorithm>
#include <cctype>

#include <fstream>
#include <iostream>
#include <sstream>
#include <iterator>

#include "thermodynamics.h"
#include "unitsets.h"

#include <Eigen/Dense>

using namespace std;
using namespace Thermodynamics::Types;

using namespace Thermodynamics::UOM::SI;

namespace Thermodynamics
{

    void Database::scan_database_file()
    {
        ifstream infile;
        infile.open(this->filename);
        if (infile.fail())
        { // oops the file did not exist for reading?
            cout << "Opening Property database file " << this->filename << " failed." << endl;
            exit(1);
        }

        string line;
        while (getline(infile, line))
        { //read data from file object and put it into string.
            std::istringstream iss(line);
            std::vector<std::string> results((std::istream_iterator<std::string>(iss)),
                                             std::istream_iterator<std::string>());

            if (results[0] == "SYST")
            {
                auto maxComp = stoi(results[3]);
                this->NC = maxComp;
                for (int i = 0; i < maxComp; i++)
                {
                    this->known_components.push_back(Substance());
                }
            }
            if (results[0] == "SHOR")
            {
                auto index = stoi(results[1]) - 1;
                this->known_components[index].identifier = results[2];
                this->component_names.push_back(results[2]);
            }
            if (results[0] == "NAME")
            {
                auto index = stoi(results[1]) - 1;
                this->known_components[index].name = results[2];
            }
            if (results[0] == "CASN")
            {
                auto index = stoi(results[1]) - 1;
                this->known_components[index].casNo = results[2];
            }

            if (results[0] == "MOLW")
            {
                auto index = stoi(results[1]) - 1;
                auto value = stod(results[3]);
                this->known_components[index].constants.insert(
                    {MolecularProperties::MolarWeight,
                     Quantity(results[0], results[0], value, kg / kmol)});
            }

            if (results[0] == "PC")
            {
                auto index = stoi(results[1]) - 1;
                auto value = stod(results[3]);
                this->known_components[index].constants.insert(
                    {MolecularProperties::CriticalPressure,
                     Quantity(results[0], results[0], value, Pa)});
            }
            if (results[0] == "TC")
            {
                auto index = stoi(results[1]) - 1;
                auto value = stod(results[3]);
                this->known_components[index].constants.insert(
                    {MolecularProperties::CriticalTemperature,
                     Quantity(results[0], results[0], value, K)});
            }
            if (results[0] == "AC")
            {
                auto index = stoi(results[1]) - 1;
                auto value = stod(results[3]);
                this->known_components[index].constants.insert(
                    {MolecularProperties::AcentricFactor,
                     Quantity(results[0], results[0], value, none)});
            }

            if (results[0] == "VP")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::VaporPressure;
                this->known_components[index].functions.insert(
                    {PureProperties::VaporPressure,
                     function});
            }

            if (results[0] == "CPID")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::IdealGasHeatCapacity;
                this->known_components[index].functions.insert(
                    {PureProperties::IdealGasHeatCapacity,
                     function});
            }
            if (results[0] == "HVAP")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::HeatOfVaporization;
                this->known_components[index].functions.insert(
                    {PureProperties::HeatOfVaporization,
                     function});
            }
            if (results[0] == "DENL")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::LiquidDensity;
                this->known_components[index].functions.insert(
                    {PureProperties::LiquidDensity,
                     function});
            }
            if (results[0] == "ST")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::SurfaceTension;
                this->known_components[index].functions.insert(
                    {PureProperties::SurfaceTension,
                     function});
            }
            if (results[0] == "CL")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::LiquidHeatCapacity;
                this->known_components[index].functions.insert(
                    {PureProperties::LiquidHeatCapacity,
                     function});
            }

            if (results[0] == "KLIQ")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::LiquidHeatConductivity;
                this->known_components[index].functions.insert(
                    {PureProperties::LiquidHeatConductivity,
                     function});
            }
            if (results[0] == "KVAP")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::VaporHeatConductivity;
                this->known_components[index].functions.insert(
                    {PureProperties::VaporHeatConductivity,
                     function});
            }
            if (results[0] == "VISL")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::LiquidViscosity;
                this->known_components[index].functions.insert(
                    {PureProperties::LiquidViscosity,
                     function});
            }
            if (results[0] == "VISV")
            {
                auto index = stoi(results[1]) - 1;
                auto function = this->parse_function(infile, results);
                function.property = PureProperties::VaporViscosity;
                this->known_components[index].functions.insert(
                    {PureProperties::VaporViscosity,
                     function});
            }
            if (results[0] == "LVEQ")
            {
                if (results[2] == "NRTL")
                {
                    this->binaryparameters.insert({"NRTL", BinaryParameterSet("NRTL", this->NC)});
                }
            }

            if (results[0] == "NRTL")
            {
                auto matrix = results[1];
                auto i = stoi(results[2]) - 1;
                auto j = stoi(results[3]) - 1;
                auto kij = stod(results[4]);
                auto kji = stod(results[5]);

                this->binaryparameters.at("NRTL").set_value(matrix, i, j, kij);
                this->binaryparameters.at("NRTL").set_value(matrix, j, i, kji);
            }
        }
        std::cout.flush();
        infile.close();
    }

    PureFunction Database::parse_function(ifstream &infile, vector<string> &results)
    {
        auto function = PureFunction();

        function.tmin = stod(results[5]);
        function.tmax = stod(results[6]);

        string paramline;
        getline(infile, paramline);
        std::istringstream iss2(paramline);
        std::vector<std::string> parameters((std::istream_iterator<std::string>(iss2)), std::istream_iterator<std::string>());

        function.c = Eigen::VectorXd(parameters.size());

        for (size_t i = 0; i < parameters.size(); i++)
        {
            /* code */
            function.c(i) = stod(parameters[i]);
        }

        function.xUnit= SI::K;
        if (Thermodynamics::Types::NameToCorrelation.count(results[3]) > 0)
            function.correlation = Thermodynamics::Types::NameToCorrelation[results[3]];
        else
            function.correlation = Thermodynamics::Types::PureCorrelations::None;

        return function;
    }

    Substance Database::find_component(std::string name)
    {

        for (auto comp : this->known_components)
        {
            if (comp.identifier == name || comp.name == name)
                return comp;
        }

        Substance comp;
        comp.name = "ERROR";
        comp.identifier = "ERROR";
        return comp;
    }

    void Database::fill_binary_parameters(ThermodynamicSystem *system)
    {
        auto nrtlsys = BinaryParameterSet("NRTL", system->NC);
        auto nrtldb = this->binaryparameters.at("NRTL");
        auto matrices = {"A", "B", "C", "D", "E", "F"};

        for (int i = 0; i < system->NC; i++)
        {
            for (int j = 0; j < system->NC; j++)
            {
                if (i == j)
                    continue;

                auto name_i = system->substances[i].identifier;
                auto name_j = system->substances[j].identifier;

                auto idb = find(this->component_names.begin(), this->component_names.end(), name_i);
                int ii = distance(this->component_names.begin(), idb);
                auto jdb = find(this->component_names.begin(), this->component_names.end(), name_j);
                int jj = distance(this->component_names.begin(), jdb);

                for (auto matrix : matrices)
                {
                    auto aij = nrtldb.get_value(matrix, ii, jj);
                    auto aji = nrtldb.get_value(matrix, jj, ii);
                    nrtlsys.set_value(matrix, i, j, aij);
                    nrtlsys.set_value(matrix, j, i, aji);
                }
            }
            system->binaryparameters.insert({"NRTL", nrtlsys});
        }
    }

    std::vector<string> Database::get_component_list()
    {
        return this->component_names;
    }

} // namespace Thermodynamics

ext: cpp


text:
// This file is part of the dune-xt-common project:
//   https://github.com/dune-community/dune-xt-common
// Copyright 2009-2018 dune-xt-common developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   René Fritze    (2018)
//   Tobias Leibner (2018)

#ifndef DUNE_XT_COMMON_COORDINATES_HH
#define DUNE_XT_COMMON_COORDINATES_HH

#include <dune/xt/common/disable_warnings.hh>
#include <boost/geometry.hpp>
#include <dune/xt/common/reenable_warnings.hh>

#include <dune/xt/common/fvector.hh>

namespace Dune {
namespace XT {
namespace Common {

/** Converts from (x, y, z) to (theta, phi) on the unit sphere s.t.
 * (x, y, z) = (sin(theta) cos(phi), sin(theta) sin(phi), cos(theta))
 * with 0 \leq \theta \leq \pi and 0 \leq \varphi < 2\pi. **/
template <class DomainFieldType>
class CoordinateConverter
{
  typedef typename boost::geometry::model::point<DomainFieldType, 3, typename boost::geometry::cs::cartesian>
      BoostCartesianCoordType;
  typedef typename boost::geometry::model::
      point<DomainFieldType, 2, typename boost::geometry::cs::spherical<boost::geometry::radian>>
          BoostSphericalCoordType;

public:
  typedef FieldVector<DomainFieldType, 3> CartesianCoordType;
  typedef FieldVector<DomainFieldType, 2> SphericalCoordType;

  static SphericalCoordType to_spherical(const CartesianCoordType& x)
  {
    BoostCartesianCoordType x_boost(x[0], x[1], x[2]);
    BoostSphericalCoordType x_spherical_boost;
    boost::geometry::transform(x_boost, x_spherical_boost);
    return SphericalCoordType{boost::geometry::get<1>(x_spherical_boost), boost::geometry::get<0>(x_spherical_boost)};
  }

  static CartesianCoordType to_cartesian(const SphericalCoordType& x_spherical, bool first_is_cosine = false)
  {
    // if first_is_cosine, the first coordinate is not theta but rather cos(theta)
    if (first_is_cosine) {
      const auto& mu = x_spherical[0];
      const auto& phi = x_spherical[1];
      return CartesianCoordType{
          std::sqrt(1 - std::pow(mu, 2)) * std::cos(phi), std::sqrt(1 - std::pow(mu, 2)) * std::sin(phi), mu};
    } else {
      BoostSphericalCoordType x_spherical_boost(x_spherical[1], x_spherical[0]);
      BoostCartesianCoordType x_boost;
      boost::geometry::transform(x_spherical_boost, x_boost);
      return CartesianCoordType{
          boost::geometry::get<0>(x_boost), boost::geometry::get<1>(x_boost), boost::geometry::get<2>(x_boost)};
    }
  }
};

} // namespace Common
} // namespace XT
} // namespace Dune

#endif // DUNE_XT_COMMON_COORDINATES_HH

ext: hh

max_stars_repo_name: ftschindler-work/dune-xt-common

max_issues_repo_name: ftschindler-work/dune-xt-common

max_forks_repo_name: ftschindler-work/dune-xt-common


text:
//
// Copyright (c) 2012-2016 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//<-
#include <memory>
//->
#include <boost/di.hpp>

namespace di = boost::di;

struct I {
  virtual ~I() noexcept = default;
  virtual void dummy() = 0;
};
struct Impl : I {
  void dummy() override {}
};

auto module = [] {
  // clang-format off
  return di::make_injector(
    // di::bind<I>.to<Impl>()
  );
  // clang-format on
};

int main() {
  auto injector = di::make_injector(module());
  std::unique_ptr<I> object{injector.create<I *>()};
  object->dummy();
}

// clang-format off
/**
 * di.cpp:32:38: warning: 'create<I *, 0>' is deprecated: creatable constraint not satisfied
 *   std::unique_ptr<I> object{injector.create<I *>()};
 *                                      ^
 * boost/di.hpp:2420:3: note: 'create<I *, 0>' has been explicitly marked deprecated here
 *   create
 *   ^
 * boost/di.hpp:871:2: error: 'boost::di::v1_0_0::concepts::abstract_type<I>::is_not_bound::error'
 *  error(_ = "type is not bound, did you forget to add: 'di::bind<interface>.to<implementation>()'?");
 *  ^
 */
// clang-format on

max_stars_repo_name: robhendriks/city-defence

max_issues_repo_name: robhendriks/city-defence

max_forks_repo_name: robhendriks/city-defence


text:
//<boost/asio/ip/tcp.hpp> must be first to prevent "WinSock.h has already been included" error
#include <boost/asio/ip/tcp.hpp>
#include <wx/wx.h>
#include <wx/stdpaths.h>
#include <fstream>
#include <get_file_names_from_path.h>
#include <http_get_video_files.h>
#include <boost/filesystem/path.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <HttpGet.h>
#include <get_play_request_json.h>
#include <Config.h>
#include <cmake_conf.h>
#include <get_stop_request_json.h>
#include <get_pause_request_json.h>
#include <format_time.h>
#include <http_get_player_percentage.h>
#include <parse_json_percentage.h>
#include <get_time_request_json.h>
#include <parse_json_time.h>
#include "MainExecutablePanelMain.h"

MainExecutablePanelMain::MainExecutablePanelMain( wxWindow* parent )
:
PanelMain( parent )
{
    auto config_dir = ::wxStandardPaths::Get().GetUserConfigDir();
        Config::read(config_dir.ToStdString(), (std::string) APP_NAME);
        auto videofiles_full_path = http_get_video_files(Config::setting["videoDir"], Config::httpConf);
        if (videofiles_full_path.size() > 0) {
            boost::filesystem::path p(videofiles_full_path[0]);
            video_files_path = p.parent_path();
            auto videofiles = get_file_names_from_path(videofiles_full_path);
            for (auto file: videofiles) {
                m_listBox2->Append(file);
                timer_enabled = true;
            }
        }
}

void MainExecutablePanelMain::open_video() const {
    auto index = m_listBox2->GetSelection();
    if(index<0)
        return;
    wxString selectedValue = m_listBox2->GetString((unsigned int) index);

    boost::filesystem::path filename(selectedValue);
    auto fullpath = video_files_path / filename;
    string fullpath_str = fullpath.string();
    boost::algorithm::replace_all(fullpath_str, "\\", "/");

    auto request_str = get_play_request_json(fullpath_str);
    HttpGet::execute(request_str, Config::httpConf);
}

void MainExecutablePanelMain::set_percentage(double value) {
    m_slider1->SetValue((int) std::round(value));
}

void MainExecutablePanelMain::btnStopClick(wxCommandEvent &event) {
    m_toggleBtnPlayPause->SetValue(false);
    m_toggleBtnPlayPause->SetLabelText("|> vaata");
    auto request_str = get_stop_request_json();
    HttpGet::execute(request_str, Config::httpConf);
}

void MainExecutablePanelMain::set_time_label(wxString timeLabel) {
    m_staticTextTime->SetLabelText(timeLabel);
}

void MainExecutablePanelMain::toggleBtnPlayPauseClick(wxCommandEvent &event) {
    auto index = m_listBox2->GetSelection();
    if(index<0) {
        m_toggleBtnPlayPause->SetValue(false);
        return;
    }
    if(m_toggleBtnPlayPause->GetValue()){
        m_toggleBtnPlayPause->SetLabelText("|| peata");
        if(time_zero())
        {
            open_video();
        }
        else {
            pause_video();
        }
    }
    else {
        m_toggleBtnPlayPause->SetLabelText("|> vaata");
        pause_video();
    }
}

void MainExecutablePanelMain::pause_video() const {
    auto request_str = get_pause_request_json();
    HttpGet::execute(request_str, Config::httpConf);
}

void MainExecutablePanelMain::timer_tick() {
    if(!timer_enabled)
        return;
    auto json = http_get_player_percentage(Config::httpConf);
//    wxMessageBox(json);
    auto percentage = parse_json_percentage(json);
    set_percentage(percentage);

    auto request_url = get_time_request_json();

    auto result = HttpGet::execute(request_url, Config::httpConf);
//    std::cout << result.body << std::endl;
    auto times = parse_json_time(result.body);
    time = times["time"];
    totaltime = times["totaltime"];
//    std::cout << time.hours << ":"  << time.minutes << ":" << time.seconds << std::endl;

    wxString timeLabelText = format_time(time) + "/" + format_time(totaltime);
    set_time_label(timeLabelText);
}

bool MainExecutablePanelMain::time_zero() {
    return totaltime.hours == 0 && totaltime.milliseconds == 0 && totaltime.minutes == 0 && totaltime.seconds == 0 && time.milliseconds == 0 && time.seconds == 0 && time.minutes == 0 && time.hours == 0;
}

void MainExecutablePanelMain::btnExitClick(wxCommandEvent &event) {
    m_parent->Close(true);
}

max_stars_repo_name: asjadenet/videoplayer

max_issues_repo_name: asjadenet/videoplayer

max_forks_repo_name: asjadenet/videoplayer


text:
#ifndef LOAD_EXTRINSIC_HPP_
#define LOAD_EXTRINSIC_HPP_

#include <Eigen/Core>
#include <Eigen/Geometry>
#include <yaml-cpp/yaml.h>

inline bool loadExtrinsic(const std::string &file_path, Eigen::Isometry3d &extrinsic) {
  YAML::Node config = YAML::LoadFile(file_path);
  if (config["transform"]) {
    if (config["transform"]["matrix"]) {
      const YAML::Node &matrix = config["transform"]["matrix"];
      Eigen::Matrix4d m4d;
      if (matrix.size() != 16) {
        std::cout << "Transform::Matrix error" << matrix.size();
      }

      m4d << matrix[0].as<double>(), matrix[1].as<double>(),
          matrix[2].as<double>(), matrix[3].as<double>(),
          matrix[4].as<double>(), matrix[5].as<double>(),
          matrix[6].as<double>(), matrix[7].as<double>(),
          matrix[8].as<double>(), matrix[9].as<double>(),
          matrix[10].as<double>(), matrix[11].as<double>(),
          matrix[12].as<double>(), matrix[13].as<double>(),
          matrix[14].as<double>(), matrix[15].as<double>();

      extrinsic.matrix() = m4d;
      return true;
    }
  }
  return false;
}
#endif // LOAD_EXTRINSIC_HPP_

ext: hpp

max_stars_repo_name: autonomy-lab-cooper/CooperMapper

max_issues_repo_name: autonomy-lab-cooper/CooperMapper

max_forks_repo_name: autonomy-lab-cooper/CooperMapper


text:
//=======================================================================
// Copyright (c) 2014 Andrzej Pacuk
//
// 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)
//=======================================================================
/**
 * @file performance_measures.hpp
 * @brief
 * @author Andrzej Pacuk
 * @version 1.0
 * @date 2014-10-22
 */
#ifndef PALL_PERFORMANCE_MEASURES_HPP
#define PALL_PERFORMANCE_MEASURES_HPP

#include <boost/range/combine.hpp>
#include <boost/range/empty.hpp>
#include <boost/range/size.hpp>
#include <boost/tuple/tuple.hpp>

#include <algorithm>
#include <cmath>
#include <utility>

namespace paal {

/**
 * @brief
 *
 * @tparam FloatType
 * @tparam Probs
 * @tparam TestResults
 *
 * @param probs
 * @param test_results
 */
template<typename FloatType = double,
         typename Probs, typename TestResults>
FloatType log_loss(Probs &&probs, TestResults &&test_results) {
    assert(boost::size(probs) == boost::size(test_results));
    assert(!boost::empty(probs));

    FloatType loss{};
    static FloatType EPSILON{1e-6};
    for(auto prob_result : boost::combine(probs, test_results)) {
        FloatType prob, result;
        boost::tie(prob, result) = prob_result;
        loss -= std::log(std::max(result ? prob : 1 - prob,
                                  EPSILON));
    }

    return loss / boost::size(probs);
}

/**
 * @brief
 *
 * @tparam FloatType
 * @param log_loss
 *
 * @return
 */
template<typename FloatType>
FloatType likelihood_from_log_loss(FloatType log_loss) {
    return std::exp(-log_loss);
}

/**
 * @brief
 *
 * @tparam FloatType
 * @tparam Probs
 * @tparam TestResults
 *
 * @param probs
 * @param test_results
 */
template<typename FloatType = double,
         typename Probs, typename TestResults>
FloatType likelihood(Probs &&probs, TestResults &&test_results) {
    return likelihood_from_log_loss(log_loss<FloatType>(std::forward<Probs>(probs),
                                    std::forward<TestResults>(test_results)));
}

/**
 * @brief
 *
 * @tparam FloatType
 * @tparam Probs
 * @tparam TestResults
 *
 * @param probs
 * @param test_results
 */
template<typename FloatType = double,
typename Probs, typename TestResults>
FloatType mean_absolute_error(Probs &&probs, TestResults &&test_results) {
    assert(boost::size(probs) == boost::size(test_results));
    assert(!boost::empty(probs));

    FloatType loss{};
    for(auto prob_result : boost::combine(probs, test_results)) {
        FloatType prob, result;
        boost::tie(prob, result) = prob_result;
        loss += std::abs(prob - result);
    }

    return loss / boost::size(probs);
}

} //! paal

#endif /* PALL_PERFORMANCE_MEASURES_HPP */

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
#include "gtfs/schedule.hpp"
#include "gtfs/constructor.hpp"

#include <algorithm>
#include <boost/assert.hpp>
#include <utility>

namespace nepomuk
{
namespace gtfs
{
bool checkWeeklyScheduleCSVHeader(std::map<std::string, std::size_t> const &header)
{
    return header.count("service_id") && header.count("monday") && header.count("tuesday") &&
           header.count("wednesday") && header.count("thursday") && header.count("friday") &&
           header.count("saturday") && header.count("sunday") && header.count("start_date") &&
           header.count("end_date");
}

WeeklySchedule makeWeeklySchedule(std::map<std::string, std::size_t> const &header,
                                  std::vector<std::string> &values)
{
    std::bitset<7> schedule;
    auto const is_set = [](std::string const &value) {
        BOOST_ASSERT(value == "0" || value == "1");
        return value == "1";
    };
    const constexpr char *weekdays[7] = {
        "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};
    for (std::size_t i = 0; i < 7; ++i)
    {
        schedule[i] = is_set(construct<std::string>(weekdays[i], forward, header, values));
    }

    return {construct<ServiceID>("service_id", stringToID<ServiceID>, header, values),
            std::move(schedule),
            construct<Date>("start_date", constructFromString<Date>, header, values),
            construct<Date>("end_date", constructFromString<Date>, header, values)};
}
} // namespace gtfs
} // namespace nepomuk

max_stars_repo_name: mapbox/nepomuk

max_issues_repo_name: mapbox/nepomuk

max_forks_repo_name: mapbox/nepomuk


text:
/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Clifford Wolf <clifford@symbioticeda.com>
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *
 *  Simulated annealing implementation based on arachne-pnr
 *  Copyright (C) 2015-2018 Cotton Seed
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "placer1.h"
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <cmath>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <ostream>
#include <queue>
#include <set>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "log.h"
#include "place_common.h"
#include "timing.h"
#include "util.h"

NEXTPNR_NAMESPACE_BEGIN

class SAPlacer
{
  public:
    SAPlacer(Context *ctx, Placer1Cfg cfg) : ctx(ctx), cfg(cfg)
    {
        int num_bel_types = 0;
        for (auto bel : ctx->getBels()) {
            IdString type = ctx->getBelType(bel);
            if (bel_types.find(type) == bel_types.end()) {
                bel_types[type] = std::tuple<int, int>(num_bel_types++, 1);
            } else {
                std::get<1>(bel_types.at(type))++;
            }
        }
        for (auto bel : ctx->getBels()) {
            Loc loc = ctx->getBelLocation(bel);
            IdString type = ctx->getBelType(bel);
            int type_idx = std::get<0>(bel_types.at(type));
            int type_cnt = std::get<1>(bel_types.at(type));
            if (type_cnt < cfg.minBelsForGridPick)
                loc.x = loc.y = 0;
            if (int(fast_bels.size()) < type_idx + 1)
                fast_bels.resize(type_idx + 1);
            if (int(fast_bels.at(type_idx).size()) < (loc.x + 1))
                fast_bels.at(type_idx).resize(loc.x + 1);
            if (int(fast_bels.at(type_idx).at(loc.x).size()) < (loc.y + 1))
                fast_bels.at(type_idx).at(loc.x).resize(loc.y + 1);
            max_x = std::max(max_x, loc.x);
            max_y = std::max(max_y, loc.y);
            fast_bels.at(type_idx).at(loc.x).at(loc.y).push_back(bel);
        }
        diameter = std::max(max_x, max_y) + 1;

        costs.resize(ctx->nets.size());
        old_udata.reserve(ctx->nets.size());
        decltype(NetInfo::udata) n = 0;
        for (auto &net : ctx->nets) {
            old_udata.emplace_back(net.second->udata);
            net.second->udata = n++;
        }
    }

    ~SAPlacer()
    {
        for (auto &net : ctx->nets)
            net.second->udata = old_udata[net.second->udata];
    }

    bool place()
    {
        log_break();
        ctx->lock();

        size_t placed_cells = 0;
        // Initial constraints placer
        for (auto &cell_entry : ctx->cells) {
            CellInfo *cell = cell_entry.second.get();
            auto loc = cell->attrs.find(ctx->id("BEL"));
            if (loc != cell->attrs.end()) {
                std::string loc_name = loc->second;
                BelId bel = ctx->getBelByName(ctx->id(loc_name));
                if (bel == BelId()) {
                    log_error("No Bel named \'%s\' located for "
                              "this chip (processing BEL attribute on \'%s\')\n",
                              loc_name.c_str(), cell->name.c_str(ctx));
                }

                IdString bel_type = ctx->getBelType(bel);
                if (bel_type != cell->type) {
                    log_error("Bel \'%s\' of type \'%s\' does not match cell "
                              "\'%s\' of type \'%s\'\n",
                              loc_name.c_str(), bel_type.c_str(ctx), cell->name.c_str(ctx), cell->type.c_str(ctx));
                }
                if (!ctx->isValidBelForCell(cell, bel)) {
                    log_error("Bel \'%s\' of type \'%s\' is not valid for cell "
                              "\'%s\' of type \'%s\'\n",
                              loc_name.c_str(), bel_type.c_str(ctx), cell->name.c_str(ctx), cell->type.c_str(ctx));
                }

                auto bound_cell = ctx->getBoundBelCell(bel);
                if (bound_cell) {
                    log_error("Cell \'%s\' cannot be bound to bel \'%s\' since it is already bound to cell \'%s\'\n",
                              cell->name.c_str(ctx), loc_name.c_str(), bound_cell->name.c_str(ctx));
                }

                ctx->bindBel(bel, cell, STRENGTH_USER);
                locked_bels.insert(bel);
                placed_cells++;
            }
        }
        int constr_placed_cells = placed_cells;
        log_info("Placed %d cells based on constraints.\n", int(placed_cells));
        ctx->yield();

        // Sort to-place cells for deterministic initial placement
        std::vector<CellInfo *> autoplaced;
        for (auto &cell : ctx->cells) {
            CellInfo *ci = cell.second.get();
            if (ci->bel == BelId()) {
                autoplaced.push_back(cell.second.get());
            }
        }
        std::sort(autoplaced.begin(), autoplaced.end(), [](CellInfo *a, CellInfo *b) { return a->name < b->name; });
        ctx->shuffle(autoplaced);

        // Place cells randomly initially
        log_info("Creating initial placement for remaining %d cells.\n", int(autoplaced.size()));

        for (auto cell : autoplaced) {
            place_initial(cell);
            placed_cells++;
            if ((placed_cells - constr_placed_cells) % 500 == 0)
                log_info("  initial placement placed %d/%d cells\n", int(placed_cells - constr_placed_cells),
                         int(autoplaced.size()));
        }
        if ((placed_cells - constr_placed_cells) % 500 != 0)
            log_info("  initial placement placed %d/%d cells\n", int(placed_cells - constr_placed_cells),
                     int(autoplaced.size()));
        if (ctx->slack_redist_iter > 0)
            assign_budget(ctx);
        ctx->yield();

        log_info("Running simulated annealing placer.\n");

        // Calculate metric after initial placement
        curr_metric = 0;
        curr_tns = 0;
        for (auto &net : ctx->nets) {
            wirelen_t wl = get_net_metric(ctx, net.second.get(), MetricType::COST, curr_tns);
            costs[net.second->udata] = CostChange{wl, -1};
            curr_metric += wl;
        }

        int n_no_progress = 0;
        wirelen_t min_metric = curr_metric;
        double avg_metric = curr_metric;
        temp = 10000;

        // Main simulated annealing loop
        for (int iter = 1;; iter++) {
            n_move = n_accept = 0;
            improved = false;

            if (iter % 5 == 0 || iter == 1)
                log_info("  at iteration #%d: temp = %f, cost = "
                         "%.0f, est tns = %.02fns\n",
                         iter, temp, double(curr_metric), curr_tns);

            for (int m = 0; m < 15; ++m) {
                // Loop through all automatically placed cells
                for (auto cell : autoplaced) {
                    // Find another random Bel for this cell
                    BelId try_bel = random_bel_for_cell(cell);
                    // If valid, try and swap to a new position and see if
                    // the new position is valid/worthwhile
                    if (try_bel != BelId() && try_bel != cell->bel)
                        try_swap_position(cell, try_bel);
                }
            }

            if (curr_metric < min_metric) {
                min_metric = curr_metric;
                improved = true;
            }

            // Heuristic to improve placement on the 8k
            if (improved)
                n_no_progress = 0;
            else
                n_no_progress++;

            if (temp <= 1e-3 && n_no_progress >= 5) {
                if (iter % 5 != 0)
                    log_info("  at iteration #%d: temp = %f, cost = %f\n", iter, temp, double(curr_metric));
                break;
            }

            double Raccept = double(n_accept) / double(n_move);

            int M = std::max(max_x, max_y) + 1;

            double upper = 0.6, lower = 0.4;

            if (curr_metric < 0.95 * avg_metric) {
                avg_metric = 0.8 * avg_metric + 0.2 * curr_metric;
            } else {
                if (Raccept >= 0.8) {
                    temp *= 0.7;
                } else if (Raccept > upper) {
                    if (diameter < M)
                        diameter++;
                    else
                        temp *= 0.9;
                } else if (Raccept > lower) {
                    temp *= 0.95;
                } else {
                    // Raccept < 0.3
                    if (diameter > 1)
                        diameter--;
                    else
                        temp *= 0.8;
                }
            }
            // Once cooled below legalise threshold, run legalisation and start requiring
            // legal moves only
            if (temp < legalise_temp && require_legal) {
                if (legalise_relative_constraints(ctx)) {
                    // Only increase temperature if something was moved
                    autoplaced.clear();
                    for (auto cell : sorted(ctx->cells)) {
                        if (cell.second->belStrength < STRENGTH_STRONG)
                            autoplaced.push_back(cell.second);
                    }
                    temp = post_legalise_temp;
                    diameter *= post_legalise_dia_scale;
                    ctx->shuffle(autoplaced);

                    // Legalisation is a big change so force a slack redistribution here
                    if (ctx->slack_redist_iter > 0)
                        assign_budget(ctx, true /* quiet */);
                }
                require_legal = false;
            } else if (ctx->slack_redist_iter > 0 && iter % ctx->slack_redist_iter == 0) {
                assign_budget(ctx, true /* quiet */);
            }

            // Recalculate total metric entirely to avoid rounding errors
            // accumulating over time
            curr_metric = 0;
            curr_tns = 0;
            for (auto &net : ctx->nets) {
                wirelen_t wl = get_net_metric(ctx, net.second.get(), MetricType::COST, curr_tns);
                costs[net.second->udata] = CostChange{wl, -1};
                curr_metric += wl;
            }

            // Let the UI show visualization updates.
            ctx->yield();
        }
        // Final post-pacement validitiy check
        ctx->yield();
        for (auto bel : ctx->getBels()) {
            CellInfo *cell = ctx->getBoundBelCell(bel);
            if (!ctx->isBelLocationValid(bel)) {
                std::string cell_text = "no cell";
                if (cell != nullptr)
                    cell_text = std::string("cell '") + ctx->nameOf(cell) + "'";
                if (ctx->force) {
                    log_warning("post-placement validity check failed for Bel '%s' "
                                "(%s)\n",
                                ctx->getBelName(bel).c_str(ctx), cell_text.c_str());
                } else {
                    log_error("post-placement validity check failed for Bel '%s' "
                              "(%s)\n",
                              ctx->getBelName(bel).c_str(ctx), cell_text.c_str());
                }
            }
        }
        for (auto cell : sorted(ctx->cells))
            if (get_constraints_distance(ctx, cell.second) != 0)
                log_error("constraint satisfaction check failed for cell '%s' at Bel '%s'\n", cell.first.c_str(ctx),
                          ctx->getBelName(cell.second->bel).c_str(ctx));
        timing_analysis(ctx);
        ctx->unlock();
        return true;
    }

  private:
    // Initial random placement
    void place_initial(CellInfo *cell)
    {
        bool all_placed = false;
        int iters = 25;
        while (!all_placed) {
            BelId best_bel = BelId();
            uint64_t best_score = std::numeric_limits<uint64_t>::max(),
                     best_ripup_score = std::numeric_limits<uint64_t>::max();
            CellInfo *ripup_target = nullptr;
            BelId ripup_bel = BelId();
            if (cell->bel != BelId()) {
                ctx->unbindBel(cell->bel);
            }
            IdString targetType = cell->type;
            for (auto bel : ctx->getBels()) {
                if (ctx->getBelType(bel) == targetType && ctx->isValidBelForCell(cell, bel)) {
                    if (ctx->checkBelAvail(bel)) {
                        uint64_t score = ctx->rng64();
                        if (score <= best_score) {
                            best_score = score;
                            best_bel = bel;
                        }
                    } else {
                        uint64_t score = ctx->rng64();
                        CellInfo *bound_cell = ctx->getBoundBelCell(bel);
                        if (score <= best_ripup_score && bound_cell->belStrength < STRENGTH_STRONG) {
                            best_ripup_score = score;
                            ripup_target = bound_cell;
                            ripup_bel = bel;
                        }
                    }
                }
            }
            if (best_bel == BelId()) {
                if (iters == 0 || ripup_bel == BelId())
                    log_error("failed to place cell '%s' of type '%s'\n", cell->name.c_str(ctx), cell->type.c_str(ctx));
                --iters;
                ctx->unbindBel(ripup_target->bel);
                best_bel = ripup_bel;
            } else {
                all_placed = true;
            }
            ctx->bindBel(best_bel, cell, STRENGTH_WEAK);

            // Back annotate location
            cell->attrs[ctx->id("BEL")] = ctx->getBelName(cell->bel).str(ctx);
            cell = ripup_target;
        }
    }

    // Attempt a SA position swap, return true on success or false on failure
    bool try_swap_position(CellInfo *cell, BelId newBel)
    {
        static std::vector<NetInfo *> updates;
        updates.clear();
        BelId oldBel = cell->bel;
        CellInfo *other_cell = ctx->getBoundBelCell(newBel);
        if (other_cell != nullptr && other_cell->belStrength > STRENGTH_WEAK) {
            return false;
        }
        int old_dist = get_constraints_distance(ctx, cell);
        int new_dist;
        if (other_cell != nullptr)
            old_dist += get_constraints_distance(ctx, other_cell);
        wirelen_t new_metric = 0, delta;
        ctx->unbindBel(oldBel);
        if (other_cell != nullptr) {
            ctx->unbindBel(newBel);
        }

        for (const auto &port : cell->ports) {
            if (port.second.net != nullptr) {
                auto &cost = costs[port.second.net->udata];
                if (cost.new_cost == 0)
                    continue;
                cost.new_cost = 0;
                updates.emplace_back(port.second.net);
            }
        }

        if (other_cell != nullptr) {
            for (const auto &port : other_cell->ports)
                if (port.second.net != nullptr) {
                    auto &cost = costs[port.second.net->udata];
                    if (cost.new_cost == 0)
                        continue;
                    cost.new_cost = 0;
                    updates.emplace_back(port.second.net);
                }
        }

        ctx->bindBel(newBel, cell, STRENGTH_WEAK);

        if (other_cell != nullptr) {
            ctx->bindBel(oldBel, other_cell, STRENGTH_WEAK);
        }
        if (!ctx->isBelLocationValid(newBel) || ((other_cell != nullptr && !ctx->isBelLocationValid(oldBel)))) {
            ctx->unbindBel(newBel);
            if (other_cell != nullptr)
                ctx->unbindBel(oldBel);
            goto swap_fail;
        }

        new_metric = curr_metric;

        // Recalculate metrics for all nets touched by the peturbation
        for (const auto &net : updates) {
            auto &c = costs[net->udata];
            new_metric -= c.curr_cost;
            float temp_tns = 0;
            wirelen_t net_new_wl = get_net_metric(ctx, net, MetricType::COST, temp_tns);
            new_metric += net_new_wl;
            c.new_cost = net_new_wl;
        }

        new_dist = get_constraints_distance(ctx, cell);
        if (other_cell != nullptr)
            new_dist += get_constraints_distance(ctx, other_cell);
        delta = new_metric - curr_metric;
        delta += (cfg.constraintWeight / temp) * (new_dist - old_dist);
        n_move++;
        // SA acceptance criterea
        if (delta < 0 || (temp > 1e-6 && (ctx->rng() / float(0x3fffffff)) <= std::exp(-delta / temp))) {
            n_accept++;
        } else {
            if (other_cell != nullptr)
                ctx->unbindBel(oldBel);
            ctx->unbindBel(newBel);
            goto swap_fail;
        }
        curr_metric = new_metric;
        for (const auto &net : updates) {
            auto &c = costs[net->udata];
            c = CostChange{c.new_cost, -1};
        }

        return true;
    swap_fail:
        ctx->bindBel(oldBel, cell, STRENGTH_WEAK);
        if (other_cell != nullptr) {
            ctx->bindBel(newBel, other_cell, STRENGTH_WEAK);
        }
        for (const auto &net : updates)
            costs[net->udata].new_cost = -1;
        return false;
    }

    // Find a random Bel of the correct type for a cell, within the specified
    // diameter
    BelId random_bel_for_cell(CellInfo *cell)
    {
        IdString targetType = cell->type;
        Loc curr_loc = ctx->getBelLocation(cell->bel);
        while (true) {
            int nx = ctx->rng(2 * diameter + 1) + std::max(curr_loc.x - diameter, 0);
            int ny = ctx->rng(2 * diameter + 1) + std::max(curr_loc.y - diameter, 0);
            int beltype_idx, beltype_cnt;
            std::tie(beltype_idx, beltype_cnt) = bel_types.at(targetType);
            if (beltype_cnt < cfg.minBelsForGridPick)
                nx = ny = 0;
            if (nx >= int(fast_bels.at(beltype_idx).size()))
                continue;
            if (ny >= int(fast_bels.at(beltype_idx).at(nx).size()))
                continue;
            const auto &fb = fast_bels.at(beltype_idx).at(nx).at(ny);
            if (fb.size() == 0)
                continue;
            BelId bel = fb.at(ctx->rng(int(fb.size())));
            if (locked_bels.find(bel) != locked_bels.end())
                continue;
            return bel;
        }
    }

    Context *ctx;
    wirelen_t curr_metric = std::numeric_limits<wirelen_t>::max();
    float curr_tns = 0;
    float temp = 1000;
    bool improved = false;
    int n_move, n_accept;
    int diameter = 35, max_x = 1, max_y = 1;
    std::unordered_map<IdString, std::tuple<int, int>> bel_types;
    std::vector<std::vector<std::vector<std::vector<BelId>>>> fast_bels;
    std::unordered_set<BelId> locked_bels;
    bool require_legal = true;
    const float legalise_temp = 1;
    const float post_legalise_temp = 10;
    const float post_legalise_dia_scale = 1.5;
    Placer1Cfg cfg;

    struct CostChange
    {
        wirelen_t curr_cost;
        wirelen_t new_cost;
    };
    std::vector<CostChange> costs;
    std::vector<decltype(NetInfo::udata)> old_udata;
};

Placer1Cfg::Placer1Cfg(Context *ctx) : Settings(ctx)
{
    constraintWeight = get<float>("placer1/constraintWeight", 10);
    minBelsForGridPick = get<int>("placer1/minBelsForGridPick", 64);
}

bool placer1(Context *ctx, Placer1Cfg cfg)
{
    try {
        SAPlacer placer(ctx, cfg);
        placer.place();
        log_info("Checksum: 0x%08x\n", ctx->checksum());
#ifndef NDEBUG
        ctx->lock();
        ctx->check();
        ctx->unlock();
#endif
        return true;
    } catch (log_execution_error_exception) {
#ifndef NDEBUG
        ctx->check();
#endif
        return false;
    }
}

NEXTPNR_NAMESPACE_END

ext: cc

max_stars_repo_name: ajeakins/nextpnr

max_issues_repo_name: ajeakins/nextpnr

max_forks_repo_name: ajeakins/nextpnr


text:
#include <pichi/common/config.hpp>
// Include config.hpp first
#include <boost/asio/io_context.hpp>
#include <pichi/api/balancer.hpp>
#include <pichi/api/ingress_holder.hpp>
#include <pichi/common/asserts.hpp>
#include <pichi/vo/ingress.hpp>
#include <utility>

using namespace std;
namespace asio = boost::asio;
namespace ip = asio::ip;

namespace pichi::api {

static auto createAcceptors(asio::io_context& io, vo::Ingress const& vo)
{
  auto acceptors = vector<ip::tcp::acceptor>{};
  transform(cbegin(vo.bind_), cend(vo.bind_), back_inserter(acceptors), [&io](auto&& endpoint) {
    assertFalse(endpoint.type_ == EndpointType::DOMAIN_NAME);
    return ip::tcp::acceptor{io, {ip::make_address(endpoint.host_), endpoint.port_}};
  });
  return acceptors;
}

static any createData(vo::Ingress const& vo)
{
  switch (vo.type_) {
  case AdapterType::TUNNEL: {
    auto& opt = get<vo::TunnelOption>(*vo.opt_);
    return make_shared<Balancer>(opt.balance_, cbegin(opt.destinations_), cend(opt.destinations_));
  }
  default:
    return {};
  }
}

IngressHolder::IngressHolder(asio::io_context& io, vo::Ingress&& vo)
  : vo_{move(vo)}, acceptors_{createAcceptors(io, vo_)}, data_{createData(vo_)}
{
}

void IngressHolder::reset(asio::io_context& io, vo::Ingress&& vo)
{
  // TODO Exception safety
  auto acceptors = createAcceptors(io, vo);
  data_ = createData(vo);
  swap(acceptors_, acceptors);
  vo_ = move(vo);
}

}  // namespace pichi::api

max_stars_repo_name: imuzi/pichi

max_issues_repo_name: imuzi/pichi

max_forks_repo_name: imuzi/pichi


text:
/*
    Copyright (c) 2013-2014 Contributors as noted in the AUTHORS file

    This file is part of azmq

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include <azmq/socket.hpp>
#include <azmq/util/scope_guard.hpp>

#define BOOST_ENABLE_ASSERT_HANDLER
#include <boost/assert.hpp>
#include <boost/asio/buffer.hpp>

#include <array>
#include <thread>
#include <iostream>
#include <vector>
#include <cstdint>
#include <memory>

#include "../assert.ipp"

std::array<boost::asio::const_buffer, 2> snd_bufs = {{
    boost::asio::buffer("A"),
    boost::asio::buffer("B")
}};

std::string subj(const char* name) {
    return std::string("inproc://") + name;
}

void test_set_get_options() {
    boost::asio::io_service ios;

    azmq::socket s(ios, ZMQ_ROUTER);

    // set/get_option are generic, works for one and all...
    azmq::socket::rcv_hwm in_hwm(42);
    s.set_option(in_hwm);

    azmq::socket::rcv_hwm out_hwm;
    s.get_option(out_hwm);
    BOOST_ASSERT_MSG(in_hwm.value() == out_hwm.value(), "in_hwm != out_hwm");
}

void test_send_receive_sync() {
    boost::asio::io_service ios;

    azmq::socket sb(ios, ZMQ_ROUTER);
    sb.bind(subj(BOOST_CURRENT_FUNCTION));

    azmq::socket sc(ios, ZMQ_DEALER);
    sc.connect(subj(BOOST_CURRENT_FUNCTION));

    sc.send(snd_bufs, ZMQ_SNDMORE);

    azmq::message msg;
    auto size = sb.receive(msg);

    BOOST_ASSERT_MSG(msg.more(), "more");

    size = sb.receive(msg, 0);
    BOOST_ASSERT_MSG(size == boost::asio::buffer_size(snd_bufs[0]), "buffer size");
    BOOST_ASSERT_MSG(msg.more(), "more");

    size = sb.receive(msg, 0);
    BOOST_ASSERT_MSG(size == boost::asio::buffer_size(snd_bufs[1]), "buffer size");
    BOOST_ASSERT_MSG(!msg.more(), "!more");

    sc.send(snd_bufs, ZMQ_SNDMORE);

    std::array<char, 5> ident;
    std::array<char, 2> a;
    std::array<char, 2> b;

    std::array<boost::asio::mutable_buffer, 3> rcv_bufs = {{
        boost::asio::buffer(ident),
        boost::asio::buffer(a),
        boost::asio::buffer(b)
    }};

    size = sb.receive(rcv_bufs, ZMQ_RCVMORE);
    BOOST_ASSERT_MSG(size == 9, "buffer size");
}

void test_send_receive_async(bool is_speculative) {
    boost::asio::io_service ios_b;
    boost::asio::io_service ios_c;

    azmq::socket sb(ios_b, ZMQ_ROUTER);
    sb.set_option(azmq::socket::allow_speculative(is_speculative));
    sb.bind(subj(BOOST_CURRENT_FUNCTION));

    azmq::socket sc(ios_c, ZMQ_DEALER);
    sc.set_option(azmq::socket::allow_speculative(is_speculative));
    sc.connect(subj(BOOST_CURRENT_FUNCTION));

    boost::system::error_code ecc;
    size_t btc = 0;
    sc.async_send(snd_bufs, [&] (boost::system::error_code const& ec, size_t bytes_transferred) {
        SCOPE_EXIT { ios_c.stop(); };
        ecc = ec;
        btc = bytes_transferred;
    }, ZMQ_SNDMORE);

    std::array<char, 5> ident;
    std::array<char, 2> a;
    std::array<char, 2> b;

    std::array<boost::asio::mutable_buffer, 3> rcv_bufs = {{
        boost::asio::buffer(ident),
        boost::asio::buffer(a),
        boost::asio::buffer(b)
    }};

    boost::system::error_code ecb;
    size_t btb = 0;
    sb.async_receive(rcv_bufs, [&](boost::system::error_code const& ec, size_t bytes_transferred) {
        SCOPE_EXIT { ios_b.stop(); };
        ecb = ec;
        btb = bytes_transferred;
    }, ZMQ_RCVMORE);

    ios_c.run();
    ios_b.run();

    BOOST_ASSERT_MSG(!ecc, "!ecc");
    BOOST_ASSERT_MSG(btc == 4, "btc != 4");
    BOOST_ASSERT_MSG(!ecb, "!ecb");
    BOOST_ASSERT_MSG(btb == 9, "btb != 9");
}

void test_send_receive_async_threads(bool optimize_single_threaded) {
    boost::asio::io_service ios_b;
    azmq::socket sb(ios_b, ZMQ_ROUTER, optimize_single_threaded);
    sb.bind(subj(BOOST_CURRENT_FUNCTION));

    boost::asio::io_service ios_c;
    azmq::socket sc(ios_c, ZMQ_DEALER, optimize_single_threaded);
    sc.connect(subj(BOOST_CURRENT_FUNCTION));

    boost::system::error_code ecc;
    size_t btc = 0;
    std::thread tc([&] {
        sc.async_send(snd_bufs, [&] (boost::system::error_code const& ec, size_t bytes_transferred) {
            SCOPE_EXIT { ios_c.stop(); };
            ecc = ec;
            btc = bytes_transferred;
        }, ZMQ_SNDMORE);
        ios_c.run();
    });

    boost::system::error_code ecb;
    size_t btb = 0;
    std::thread tb([&] {
        std::array<char, 5> ident;
        std::array<char, 2> a;
        std::array<char, 2> b;

        std::array<boost::asio::mutable_buffer, 3> rcv_bufs = {{
            boost::asio::buffer(ident),
            boost::asio::buffer(a),
            boost::asio::buffer(b)
        }};

        sb.async_receive(rcv_bufs, [&](boost::system::error_code const& ec, size_t bytes_transferred) {
            SCOPE_EXIT { ios_b.stop(); };
            ecb = ec;
            btb = bytes_transferred;
        }, ZMQ_RCVMORE);
        ios_b.run();
    });

    tc.join();
    tb.join();
    BOOST_ASSERT_MSG(!ecc, "!ecc");
    BOOST_ASSERT_MSG(btc == 4, "btc != 4");
    BOOST_ASSERT_MSG(!ecb, "!ecb");
    BOOST_ASSERT_MSG(btb == 9, "btb != 9");
}

void test_send_receive_message_async() {
    boost::asio::io_service ios_b;
    boost::asio::io_service ios_c;

    azmq::socket sb(ios_b, ZMQ_ROUTER);
    sb.bind(subj(BOOST_CURRENT_FUNCTION));

    azmq::socket sc(ios_c, ZMQ_DEALER);
    sc.connect(subj(BOOST_CURRENT_FUNCTION));

    boost::system::error_code ecc;
    size_t btc = 0;
    sc.async_send(snd_bufs, [&] (boost::system::error_code const& ec, size_t bytes_transferred) {
        SCOPE_EXIT { ios_c.stop(); };
        ecc = ec;
        btc = bytes_transferred;
    }, ZMQ_SNDMORE);

    std::array<char, 5> ident;
    std::array<char, 2> a;
    std::array<char, 2> b;

    boost::system::error_code ecb;
    size_t btb = 0;
    sb.async_receive([&](boost::system::error_code const& ec, azmq::message & msg, size_t bytes_transferred) {
        SCOPE_EXIT { ios_b.stop(); };
        ecb = ec;
        if (ecb)
            return;
        btb += bytes_transferred;
        msg.buffer_copy(boost::asio::buffer(ident));

        if (msg.more()) {
            btb += sb.receive(msg, ZMQ_RCVMORE, ecb);
            if (ecb)
                return;
            msg.buffer_copy(boost::asio::buffer(a));
        }

        if (msg.more()) {
            btb += sb.receive(msg, 0, ecb);
            if (ecb)
                return;
            msg.buffer_copy(boost::asio::buffer(b));
        }
    });

    ios_c.run();
    ios_b.run();

    BOOST_ASSERT_MSG(!ecc, "!ecc");
    BOOST_ASSERT_MSG(btc == 4, "btc != 4");
    BOOST_ASSERT_MSG(!ecb, "!ecb");
    BOOST_ASSERT_MSG(btb == 9, "btb != 9");
}

void test_send_receive_message_more_async() {
    boost::asio::io_service ios_b;
    boost::asio::io_service ios_c;

    azmq::socket sb(ios_b, ZMQ_ROUTER);
    sb.bind(subj(BOOST_CURRENT_FUNCTION));

    azmq::socket sc(ios_c, ZMQ_DEALER);
    sc.connect(subj(BOOST_CURRENT_FUNCTION));

    boost::system::error_code ecc;
    size_t btc = 0;
    sc.async_send(snd_bufs, [&] (boost::system::error_code const& ec, size_t bytes_transferred) {
        SCOPE_EXIT { ios_c.stop(); };
        ecc = ec;
        btc = bytes_transferred;
    }, ZMQ_SNDMORE);

    std::array<char, 5> ident;
    std::array<char, 2> a;
    std::array<char, 2> b;

    std::array<boost::asio::mutable_buffer, 2> rcv_bufs = {{
        boost::asio::buffer(a),
        boost::asio::buffer(b)
    }};

    boost::system::error_code ecb;
    size_t btb = 0;
    sb.async_receive([&](boost::system::error_code const& ec, azmq::message & msg, size_t bytes_transferred) {
        SCOPE_EXIT { ios_b.stop(); };
        ecb = ec;
        if (ecb)
            return;
        btb += bytes_transferred;
        msg.buffer_copy(boost::asio::buffer(ident));

        if (!msg.more())
            return;

        azmq::message_vector v;
        btb += sb.receive_more(v, 0, ecb);
        if (ecb)
            return;
        auto it = std::begin(v);
        for (auto&& buf : rcv_bufs)
            (*it++).buffer_copy(buf);
    });

    ios_c.run();
    ios_b.run();

    BOOST_ASSERT_MSG(!ecc, "!ecc");
    BOOST_ASSERT_MSG(btc == 4, "btc != 4");
    BOOST_ASSERT_MSG(!ecb, "!ecb");
    BOOST_ASSERT_MSG(btb == 9, "btb != 9");
}

struct monitor_handler {
    using ptr = std::shared_ptr<monitor_handler>;

#if defined BOOST_MSVC
#pragma pack(push, 1)
    struct event_t
    {
        uint16_t e;
        uint32_t i;
    };
#pragma pack(pop)
#else
    struct event_t
    {
        uint16_t e;
        uint32_t i;
    } __attribute__((packed));
#endif

    azmq::socket socket_;
    std::string role_;
    event_t event_;
    std::vector<event_t> events_;

    monitor_handler(boost::asio::io_service & ios, azmq::socket& s, std::string role)
        : socket_(s.monitor(ios, ZMQ_EVENT_ALL))
        , role_(std::move(role))
    { }

    void start()
    {
        socket_.async_receive(boost::asio::buffer(&event_, sizeof(event_t)),
            [this](boost::system::error_code const& ec, size_t) {
                if (ec)
                    return;
                azmq::message msg;
                socket_.receive(msg, ZMQ_RCVMORE);
                events_.push_back(event_);
                start();
            });
    }

    void cancel()
    {
        socket_.cancel();
    }
};

void bounce(azmq::socket & server, azmq::socket & client) {
    const char *content = "12345678ABCDEFGH12345678abcdefgh";
    std::array<boost::asio::const_buffer, 2> snd_bufs = {{
        boost::asio::buffer(content, 32),
        boost::asio::buffer(content, 32)
    }};

    std::array<char, 32> buf0;
    std::array<char, 32> buf1;

    std::array<boost::asio::mutable_buffer, 2> rcv_bufs = {{
        boost::asio::buffer(buf0),
        boost::asio::buffer(buf1)
    }};
    client.send(snd_bufs, ZMQ_SNDMORE);
    server.receive(rcv_bufs, ZMQ_RCVMORE);
    server.send(snd_bufs, ZMQ_SNDMORE);
    client.receive(rcv_bufs, ZMQ_RCVMORE);
}

void test_socket_monitor() {
    boost::asio::io_service ios;
    boost::asio::io_service ios_m;

    using socket_ptr = std::unique_ptr<azmq::socket>;
    socket_ptr client(new azmq::socket(ios, ZMQ_DEALER));
    socket_ptr server(new azmq::socket(ios, ZMQ_DEALER));

    monitor_handler client_monitor(ios_m, *client, "client");
    monitor_handler server_monitor(ios_m, *server, "server");

    client_monitor.start();
    server_monitor.start();

    std::thread t([&] {
        ios_m.run();
    });

    server->bind("tcp://127.0.0.1:9998");
    client->connect("tcp://127.0.0.1:9998");

    bounce(*client, *server);

    ios_m.stop();
    t.join();

    BOOST_ASSERT_MSG(client_monitor.events_.size() == 2, "wrong count of client_monitor events");
    BOOST_ASSERT_MSG(server_monitor.events_.size() == 2, "wrong count of server_monitor events");
    BOOST_ASSERT_MSG(client_monitor.events_.at(0).e == ZMQ_EVENT_CONNECT_DELAYED, "wrong client_monitor events[0]");
    BOOST_ASSERT_MSG(client_monitor.events_.at(1).e == ZMQ_EVENT_CONNECTED, "wrong client_monitor events[1]");
    BOOST_ASSERT_MSG(server_monitor.events_.at(0).e == ZMQ_EVENT_LISTENING, "wrong server_monitor events[0]");
    BOOST_ASSERT_MSG(server_monitor.events_.at(1).e == ZMQ_EVENT_ACCEPTED, "wrong server_monitor events[1]");
}

int main(int argc, char **argv) {
    std::cout << "Testing socket operations...";
    std::cout.flush();
    try {
        test_set_get_options();
        test_send_receive_sync();
        test_send_receive_async(true);
        test_send_receive_async(false);
        for (auto i = 0; i < 100; i++)
            test_send_receive_async_threads(true);
        for (auto i = 0; i < 100; i++)
            test_send_receive_async_threads(false);
        test_send_receive_message_async();
        test_send_receive_message_more_async();
        test_socket_monitor();
    } catch (std::exception const& e) {
        std::cout << "Failure\n" << e.what() << std::endl;
        return 1;
    }
    std::cout << "Success" << std::endl;
    return 0;
}

max_stars_repo_name: hintjens/azmq

max_issues_repo_name: hintjens/azmq

max_forks_repo_name: hintjens/azmq


text:
//  (C) Copyright John Maddock 2018.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/math/tools/fraction.hpp>
#include <iostream>
#include <complex>

//[golden_ratio_1
template <class T>
struct golden_ratio_fraction
{
   typedef T result_type;

   result_type operator()()
   {
      return 1;
   }
};
//]

//[cf_tan_fraction
template <class T>
struct tan_fraction
{
private:
   T a, b;
public:
   tan_fraction(T v)
      : a(-v * v), b(-1)
   {}

   typedef std::pair<T, T> result_type;

   std::pair<T, T> operator()()
   {
      b += 2;
      return std::make_pair(a, b);
   }
};
//]
//[cf_tan
template <class T>
T tan(T a)
{
   tan_fraction<T> fract(a);
   return a / continued_fraction_b(fract, std::numeric_limits<T>::epsilon());
}
//]
//[cf_expint_fraction
template <class T>
struct expint_fraction
{
   typedef std::pair<T, T> result_type;
   expint_fraction(unsigned n_, T z_) : b(z_ + T(n_)), i(-1), n(n_) {}
   std::pair<T, T> operator()()
   {
      std::pair<T, T> result = std::make_pair(-static_cast<T>((i + 1) * (n + i)), b);
      b += 2;
      ++i;
      return result;
   }
private:
   T b;
   int i;
   unsigned n;
};
//]
//[cf_expint
template <class T>
inline std::complex<T> expint_as_fraction(unsigned n, std::complex<T> const& z)
{
   boost::uintmax_t max_iter = 1000;
   expint_fraction<std::complex<T> > f(n, z);
   std::complex<T> result = boost::math::tools::continued_fraction_b(
      f,
      std::complex<T>(std::numeric_limits<T>::epsilon()),
      max_iter);
   result = exp(-z) / result;
   return result;
}
//]
//[cf_upper_gamma_fraction
template <class T>
struct upper_incomplete_gamma_fract
{
private:
   typedef typename T::value_type scalar_type;
   T z, a;
   int k;
public:
   typedef std::pair<T, T> result_type;

   upper_incomplete_gamma_fract(T a1, T z1)
      : z(z1 - a1 + scalar_type(1)), a(a1), k(0)
   {
   }

   result_type operator()()
   {
      ++k;
      z += scalar_type(2);
      return result_type(scalar_type(k) * (a - scalar_type(k)), z);
   }
};
//]
//[cf_gamma_Q
template <class T>
inline std::complex<T> gamma_Q_as_fraction(const std::complex<T>& a, const std::complex<T>& z)
{
   upper_incomplete_gamma_fract<std::complex<T> > f(a, z);
   std::complex<T> eps(std::numeric_limits<T>::epsilon());
   return pow(z, a) / (exp(z) *(z - a + T(1) + boost::math::tools::continued_fraction_a(f, eps)));
}
//]

int main()
{
   using namespace boost::math::tools;

   //[cf_gr
   golden_ratio_fraction<double> func;
   double gr = continued_fraction_a(
      func,
      std::numeric_limits<double>::epsilon());
   std::cout << "The golden ratio is: " << gr << std::endl;
   //]

   std::cout << tan(0.5) << std::endl;

   std::complex<double> arg(3, 2);
   std::cout << expint_as_fraction(5, arg) << std::endl;

   std::complex<double> a(3, 3), z(3, 2);
   std::cout << gamma_Q_as_fraction(a, z) << std::endl;

   return 0;
}

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
/*    Lua2Bmp Kernel V3
 *
 *    Copyright 2014 wtof1996
 *    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.
 *
 *     this software is based in part on the work of the Independent JPEG Group.
 *     this software is based in part on the libpng library.
 *     this software is based in part on the Boost library.
 */

#include <cstdlib>

#include <boost/progress.hpp>

#include "draw.hpp"
#include "io.hpp"

auto _VERSION = "V3.01 Alpha I Build 01252120";

int main(int argc, char *argv[])
{
    draw::process_options(argc, argv);

    io::notice("============================================");
    io::notice("Lua2Bmp Kernel");
    io::notice(_VERSION);
    io::notice("Copyright 2014 wtof1996");
    io::notice("Use '-l' or '--license' to show the license");
    io::notice("============================================");

    draw::check_path();

    io::Image img;

    boost::progress_timer t;

    img.readLuaImage();
    img.convert();
    io::output(img);

    io::notice("Elapsed time:", false);
    //When progress_timer destruct it will show the time elapsed.

    return EXIT_SUCCESS;
}


text:
#pragma once

// create NumPy "ndarrays" from C++
// See http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html
// See NumPyDataType.hpp for a way to create the "dtype" lists used below
// If you have a type Foo which matches the array's dtype, you can access elements of the created arrays like this:
//    Foo* record = static_cast<Foo*>(PyArray_GETPTR1((PyArrayObject*)array.ptr(), index));

#include <boost/python/list.hpp>

namespace pccl {
namespace python {

// builds a NumPy array with standard C alignment rules for the fields
// count is the number of elements
// the contents will be uninitialized
boost::python::object makeNumPyArrayEmpty(boost::python::list const& dtype, unsigned count);

// as above but initializes the array to all zeros
boost::python::object makeNumPyArrayZeros(boost::python::list const& dtype, unsigned count);

// as above, but use already-allocated storage for the array (it will not be initialized, and its format must match the given dtype)
boost::python::object makeNumPyArrayWithData(boost::python::list const& dtype, unsigned count, void* data);

// as above, but builds a "packed" array a la GCC's __attribute__((__packed__))
boost::python::object makeNumPyArrayEmptyPacked(boost::python::list const& dtype, unsigned count);
boost::python::object makeNumPyArrayZerosPacked(boost::python::list const& dtype, unsigned count);
boost::python::object makeNumPyArrayWithDataPacked(boost::python::list const& dtype, unsigned count, void* data);

} // namespace python
} // namespace pccl

max_stars_repo_name: jzwinck/pccl

max_issues_repo_name: jzwinck/pccl

max_forks_repo_name: jzwinck/pccl


text:
/*
Copyright 2015 Rogier van Dalen.

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.
*/

/* \file
Provide an example usage of python/iterator.hpp.
The functions defined here are exported to Python, and used by
test-python_range.py.
*/

#include "range/python/iterator.hpp"

#include <list>

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>

#include <boost/optional.hpp>

#include "range/std/container.hpp"
#include "range/std/view_optional.hpp"
#include "range/tuple.hpp"

std::list <double> doubles;

auto get_doubles() RETURNS (range::view (doubles));

void set_first_to_doubles (boost::python::object & object) {
    object [0] = range::view (doubles);
}

range::tuple <int, std::string, float> tuple;

auto get_tuple() RETURNS (range::view (tuple));

boost::optional <bool> optional;

auto get_optional() RETURNS (range::view_optional (optional));

BOOST_PYTHON_MODULE (iterator_example) {
    doubles.push_back (3.5);
    doubles.push_back (7.25);

    tuple = range::make_tuple (6, "hello", 17.5f);

    optional = true;

    range::python::initialise_iterator();
    range::python::register_view <decltype (get_doubles())>();
    range::python::register_view <decltype (get_tuple())>();
    range::python::register_view <decltype (get_optional())>();

    using namespace boost::python;

    def ("getDoubles", &get_doubles);
    def ("setFirstToDoubles", &set_first_to_doubles);
    def ("getTuple", &get_tuple);
    def ("getOptional", &get_optional);
}

max_stars_repo_name: rogiervd/range

max_issues_repo_name: rogiervd/range

max_forks_repo_name: rogiervd/range


text:
#include "CorePch.h"
#include <rtp++/rfc2326/RtspClient.h>
#include <iomanip>
#include <boost/asio/placeholders.hpp>
#include <boost/bind.hpp>
#include <boost/optional.hpp>
#include <cpputil/Conversion.h>
#include <cpputil/StringTokenizer.h>
#include <rtp++/rfc2326/HeaderFields.h>
#include <rtp++/rfc2326/RtspErrorCategory.h>

using namespace std;
using boost::optional;

namespace rtp_plus_plus
{
namespace rfc2326
{

// RTSP session timeout
const static uint32_t DEFAULT_RTSP_SESSION_TIMEOUT_SECONDS = 60;

// minimum length of session identifier
const static uint32_t MIN_SESSION_LENGTH = 8;

RtspClient::RtspClient(boost::asio::io_service& ioService, const std::string& sRtspUri, const std::string& sIp, const uint16_t uiPort)
  :m_ioService(ioService),
  m_bShuttingDown(false),
  m_sIp(sIp),
  m_uiPort(uiPort),
  m_rtspUri(sRtspUri),
  m_uiSessionTimeout(DEFAULT_RTSP_SESSION_TIMEOUT_SECONDS),
  m_uiSN(1)
{
}

void RtspClient::initialiseConnection()
{
  VLOG(2) << "Initialising new connection to server " << m_sIp << ":" << m_uiPort;
  m_pConnection = RtspClientConnection::create(m_ioService, m_sIp, m_uiPort);
  // setup connection callbacks
  m_pConnection->setReadCompletionHandler(boost::bind(&RtspClient::readCompletionHandler, this, boost::asio::placeholders::error, _2, _3));
  m_pConnection->setWriteCompletionHandler(boost::bind(&RtspClient::writeCompletionHandler, this, boost::asio::placeholders::error, _2, _3, _4));
  m_pConnection->setCloseHandler(boost::bind(&RtspClient::closeCompletionHandler, this, _1));
  m_pConnection->setConnectErrorHandler(boost::bind(&RtspClient::connectErrorHandler, this, boost::asio::placeholders::error, _2));
}

void RtspClient::connectErrorHandler(const boost::system::error_code& error, RtspClientConnectionPtr pConnection )
{
  // this handler could be triggered eg if no connection could be created
  notifyCallerOfError(error);
}

void RtspClient::shutdown()
{
  m_bShuttingDown = true;
  if (m_pConnection)
  {
    // close any outstanding reads
    VLOG(5) << "Shutting down RTSP client. Closing connection";
    m_pConnection->close();
    m_pConnection.reset();
  }
}

boost::system::error_code RtspClient::options(const std::vector<std::string>& vSupported)
{
  if (!m_optionsHandler)
  {
    LOG(WARNING) << "No options handler has been configured";
    return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category());
  }

  // check for outstanding requests: we only handle one at a time
  if (!m_qOutstandingRequests.empty())
  {
    return boost::system::error_code(boost::system::errc::resource_unavailable_try_again, boost::system::get_generic_category());
  }

#if 0
  std::string sOptionsRequest="OPTIONS <<RtspUri>> RTSP/1.0\r\n"\
      "CSeq: <<CSeq>>\r\n"\
      "User-Agent: <<UserAgent>>\r\n\r\n";

  boost::algorithm::replace_first(sOptionsRequest, "<<RtspUri>>", m_rtspUri.fullUri());
  boost::algorithm::replace_first(sOptionsRequest, "<<CSeq>>", ::toString(m_uiSN));
  boost::algorithm::replace_first(sOptionsRequest, "<<UserAgent>>", getClientInfo());
  return sendRequest(OPTIONS, sOptionsRequest);
#else
  std::ostringstream ostr;

  ostr << "OPTIONS " << m_rtspUri.fullUri() << " RTSP/1.0\r\n";
  ostr << "CSeq: " << m_uiSN << "\r\n";
  ostr << "User-Agent: " << getClientInfo() << "\r\n";

  if (!vSupported.empty())
  {
    ostr << "Supported: " << ::toString(vSupported, ',') << "\r\n";
  }

  ostr << "\r\n";
  return sendRequest(OPTIONS, ostr.str());
#endif
}

boost::system::error_code RtspClient::sendRequest(RtspMethod eMethod, const std::string& sRtspRequest)
{
  m_mRequestMap[m_uiSN] = std::make_pair(eMethod, sRtspRequest);
  m_qOutstandingRequests.push_back(eMethod);

  if (!m_pConnection || m_pConnection->eof())
  {
    initialiseConnection();
  }

  m_pConnection->write(m_uiSN, sRtspRequest);
  ++m_uiSN;
  return boost::system::error_code();
}

boost::system::error_code RtspClient::describe(const std::vector<std::string>& vSupported)
{
  if (!m_describeHandler)
  {
    LOG(WARNING) << "No describe handler has been configured";
    return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category());
  }

  // check for outstanding requests: we only handle one at a time
  if (!m_qOutstandingRequests.empty())
  {
    return boost::system::error_code(boost::system::errc::resource_unavailable_try_again, boost::system::get_generic_category());
  }

#if 0
  std::string sDescribeRequest="DESCRIBE <<RtspUri>> RTSP/1.0\r\n"\
      "CSeq: <<CSeq>>\r\n"\
      "User-Agent: <<UserAgent>>\r\n"\
      "Accept: application/sdp\r\n\r\n";

  boost::algorithm::replace_first(sDescribeRequest, "<<RtspUri>>", m_rtspUri.fullUri());
  boost::algorithm::replace_first(sDescribeRequest, "<<CSeq>>", ::toString(m_uiSN));
  boost::algorithm::replace_first(sDescribeRequest, "<<UserAgent>>", getClientInfo());

  return sendRequest(DESCRIBE, sDescribeRequest);
#else
  std::ostringstream ostr;

  ostr << "DESCRIBE " << m_rtspUri.fullUri() << " RTSP/1.0\r\n";
  ostr << "CSeq: " << m_uiSN << "\r\n";
  ostr << "User-Agent: " << getClientInfo() << "\r\n";
  ostr << "Accept: application/sdp\r\n";

  if (!vSupported.empty())
  {
    ostr << "Supported: " << ::toString(vSupported, ',') << "\r\n";
  }

  ostr << "\r\n";
  return sendRequest(DESCRIBE, ostr.str());
#endif
}

boost::system::error_code RtspClient::setup(const rfc4566::SessionDescription& sessionDescription, const rfc4566::MediaDescription& media, const Transport& transport, const std::vector<std::string>& vSupported)
{
  if (!m_setupHandler)
  {
    LOG(WARNING) << "No SETUP handler has been configured";
    return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category());
  }

  // check for outstanding requests: we only handle one at a time
  if (!m_qOutstandingRequests.empty())
  {
    return boost::system::error_code(boost::system::errc::resource_unavailable_try_again, boost::system::get_generic_category());
  }

  // TrackId
  optional<std::string> trackId = media.getAttributeValue(rfc4566::CONTROL);

  std::string sTrackId = trackId? *trackId : "";
  if (sTrackId.empty())
  {
    // This shouldn't happen?!?
    LOG(WARNING) << "No control for track!";
  }

  // Transport
  // RTP/AVP;unicast;client_port=35220-35221
  std::string sTransport = transport.toString();

#if 0
  std::string sSetupRequest;
  if (m_sSession.empty())
  {
    sSetupRequest="SETUP <<RtspUri>>/<<TrackId>> RTSP/1.0\r\n"\
        "CSeq: <<CSeq>>\r\n"\
        "User-Agent: <<UserAgent>>\r\n"\
        "Transport: <<Transport>>\r\n\r\n";
  }
  else
  {
    sSetupRequest="SETUP <<RtspUri>>/<<TrackId>> RTSP/1.0\r\n"\
        "CSeq: <<CSeq>>\r\n"\
        "Session: <<Session>>\r\n"\
        "User-Agent: <<UserAgent>>\r\n"\
        "Transport: <<Transport>>\r\n\r\n";
    boost::algorithm::replace_first(sSetupRequest, "<<Session>>", m_sSession);
  }

  boost::algorithm::replace_first(sSetupRequest, "<<RtspUri>>", m_rtspUri.fullUri());
  boost::algorithm::replace_first(sSetupRequest, "<<TrackId>>", sTrackId);
  boost::algorithm::replace_first(sSetupRequest, "<<CSeq>>", ::toString(m_uiSN));
  boost::algorithm::replace_first(sSetupRequest, "<<UserAgent>>", getClientInfo());
  boost::algorithm::replace_first(sSetupRequest, "<<Transport>>", sTransport);

  return sendRequest(SETUP, sSetupRequest);
#else
  std::ostringstream ostr;

  ostr << "SETUP " << m_rtspUri.fullUri() << "/" << sTrackId << " RTSP/1.0\r\n";
  ostr << "CSeq: " << m_uiSN << "\r\n";
  if (!m_sSession.empty())
    ostr << "Session: " << m_sSession << "\r\n";

  ostr << "User-Agent: " << getClientInfo() << "\r\n";
  ostr << "Transport: " << sTransport << "\r\n";

  if (!vSupported.empty())
  {
    ostr << "Supported: " << ::toString(vSupported, ',') << "\r\n";
  }

  ostr << "\r\n";
  return sendRequest(SETUP, ostr.str());
#endif
}

boost::system::error_code RtspClient::play(double dStart, double dEnd, const std::vector<std::string>& vSupported)
{
  if (!m_playHandler)
  {
    LOG(WARNING) << "No PLAY handler has been configured";
    return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category());
  }

  // check for outstanding requests: we only handle one at a time
  if (!m_qOutstandingRequests.empty())
  {
    return boost::system::error_code(boost::system::errc::resource_unavailable_try_again, boost::system::get_generic_category());
  }

  std::stringstream start;
  start << std::setprecision(3) << dStart;

  std::string sStop = "";
  if (dEnd != -1.0)
  {
    std::stringstream stop;
    stop << std::setprecision(3) << dEnd;
    sStop = stop.str();
  }

#if 0
  std::string sPlayRequest = "PLAY <<RtspUri>> RTSP/1.0\r\n"\
      "CSeq: <<CSeq>>\r\n"\
      "User-Agent: <<UserAgent>>\r\n"\
      "Session: <<Session>>\r\n"\
      "Range: npt=<<StartDouble>>-<<StopDouble>>\r\n\r\n";

  boost::algorithm::replace_first(sPlayRequest, "<<RtspUri>>", m_rtspUri.fullUri());
  boost::algorithm::replace_first(sPlayRequest, "<<CSeq>>", ::toString(m_uiSN));
  boost::algorithm::replace_first(sPlayRequest, "<<UserAgent>>", getClientInfo());
  boost::algorithm::replace_first(sPlayRequest, "<<Session>>", m_sSession);
  boost::algorithm::replace_first(sPlayRequest, "<<StartDouble>>", start.str());
  boost::algorithm::replace_first(sPlayRequest, "<<StopDouble>>", sStop);

  return sendRequest(PLAY, sPlayRequest);
#else
  std::ostringstream ostr;

  ostr << "PLAY " << m_rtspUri.fullUri() << " RTSP/1.0\r\n";
  ostr << "CSeq: " << m_uiSN << "\r\n";
  ostr << "Session: " << m_sSession << "\r\n";
  ostr << "User-Agent: " << getClientInfo() << "\r\n";
  ostr << "Range: npt=" << start.str() << "-" << sStop << "\r\n";
  if (!vSupported.empty())
  {
    ostr << "Supported: " << ::toString(vSupported, ',') << "\r\n";
  }

  ostr << "\r\n";
  return sendRequest(PLAY, ostr.str());
#endif

}

boost::system::error_code RtspClient::teardown(const std::vector<std::string>& vSupported)
{
  if (!m_teardownHandler)
  {
    LOG(WARNING) << "No TEARDOWN handler has been configured";
    return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category());
  }

  // check for outstanding requests: we only handle one at a time
  if (!m_qOutstandingRequests.empty())
  {
    return boost::system::error_code(boost::system::errc::resource_unavailable_try_again, boost::system::get_generic_category());
  }

#if 0
  std::string sTeardownRequest = "TEARDOWN <<RtspUri>> RTSP/1.0\r\n"\
      "CSeq: <<CSeq>>\r\n"\
      "User-Agent: <<UserAgent>>\r\n"\
      "Session: <<Session>>\r\n\r\n";

  boost::algorithm::replace_first(sTeardownRequest, "<<RtspUri>>", m_rtspUri.fullUri());
  boost::algorithm::replace_first(sTeardownRequest, "<<CSeq>>", ::toString(m_uiSN));
  boost::algorithm::replace_first(sTeardownRequest, "<<UserAgent>>", getClientInfo());
  boost::algorithm::replace_first(sTeardownRequest, "<<Session>>", m_sSession);

  return sendRequest(TEARDOWN, sTeardownRequest);
#else
  std::ostringstream ostr;

  ostr << "TEARDOWN " << m_rtspUri.fullUri() << " RTSP/1.0\r\n";
  ostr << "CSeq: " << m_uiSN << "\r\n";
  ostr << "Session: " << m_sSession << "\r\n";
  ostr << "User-Agent: " << getClientInfo() << "\r\n";
  if (!vSupported.empty())
  {
    ostr << "Supported: " << ::toString(vSupported, ',') << "\r\n";
  }

  ostr << "\r\n";
  return sendRequest(TEARDOWN, ostr.str());
#endif
}

void RtspClient::closeCompletionHandler( RtspClientConnectionPtr pConnection )
{
  VLOG(5) << "Close completion handler called - resetting connection";
  m_pConnection.reset();
}

void RtspClient::readCompletionHandler( const boost::system::error_code& error, const std::string& sRtspMessage, RtspClientConnectionPtr pConnection )
{
  if (!error)
  {
    // check if this is RTSP or RTP
    if (sRtspMessage[0] == 0x24)
    {
      VLOG(2) << "Read RTP packet (" << sRtspMessage.length() << ")";
      // TODO:
    }
    else
    {
      VLOG(2) << "Read RTSP message (" << sRtspMessage.length() << "):\r\n" << sRtspMessage;
      boost::optional<RtspMessage> pRtspMessage = RtspMessage::parse(sRtspMessage);
      if (!pRtspMessage)
      {
        // failed to parse message
        LOG(WARNING) << "Failed to parse incoming RTSP message (" << sRtspMessage.length() << "):\r\n" << sRtspMessage;
        notifyCallerOfError(boost::system::error_code(boost::system::errc::protocol_error, boost::system::get_generic_category()));
        return;
      }
      else
      {
        std::vector<std::string> vSupported;
        boost::optional<std::string> supported = pRtspMessage->getHeaderField(SUPPORTED);
        if (supported)
        {
          vSupported = StringTokenizer::tokenize(*supported, ",", true, true);
        }

        if (pRtspMessage->isRequest())
        {
          // request from server
          handleRequest(*pRtspMessage, pConnection, vSupported);
        }
        else
        {
          // response from server
          handleResponse(*pRtspMessage, pConnection, vSupported);
        }
      }
    }
  }
  else
  {
    if (m_bShuttingDown)
    {
      if (( error != boost::asio::error::operation_aborted ) &&
          ( error != boost::asio::error::connection_aborted ))
        VLOG(5) << "Error in read: " << error.message();
    }
    else
    {
      notifyCallerOfError(error);
    }

    // TODO: double check if we should close the connection here.
  }
}

void RtspClient::writeCompletionHandler( const boost::system::error_code& error, uint32_t uiMessageId, const std::string& sRtspMessage, RtspClientConnectionPtr pConnection )
{
  if (!error)
  {
    VLOG(2) << "[C->S] Wrote RTSP message (" << sRtspMessage.length() << "):\r\n" << sRtspMessage;
  }
  else
  {
    // TODO: once the connection has failed all bets are off: should we trigger the handler for all outstanding requests
    LOG(WARNING) << "Error in write: " << error.message();
    notifyCallerOfError(error);
  }
}

void RtspClient::notifyCallerOfError(const boost::system::error_code& error)
{
  // get first outstanding request in request queue
  if (!m_qOutstandingRequests.empty())
  {
    RtspMethod eMethod = m_qOutstandingRequests.front();
    m_qOutstandingRequests.pop_front();

    switch (eMethod)
    {
      case OPTIONS:
      {
        m_optionsHandler(error, std::vector<std::string>(), std::vector<std::string>());
        break;
      }
      case DESCRIBE:
      {
        m_describeHandler(error, MessageBody(), std::vector<std::string>());
        break;
      }
      case SETUP:
      {
        Transport transportDummy;
        m_setupHandler(error, "", transportDummy, std::vector<std::string>());
        break;
      }
      case PLAY:
      {
        m_playHandler(error, std::vector<std::string>());
        break;
      }
      case PAUSE:
      {
        m_pauseHandler(error, std::vector<std::string>());
        break;
      }
      case TEARDOWN:
      {
        m_teardownHandler(error, std::vector<std::string>());
        break;
      }
      case GET_PARAMETER:
      {
        m_getParameterHandler(error, std::vector<std::string>());
        break;
      }
      case SET_PARAMETER:
      {
        m_setParameterHandler(error, std::vector<std::string>());
        break;
      }
      default:
      {
        // TODO:
        assert(false);
        break;
      }
    }
  }
  else
  {
    // could have been an error in an incoming request or could be on application exit
    if (error != boost::asio::error::eof &&
        error != boost::asio::error::operation_aborted &&
        error != boost::asio::error::connection_aborted)
      LOG(WARNING) << "Error: " << error.message();
    // TODO: do we need to ignore bad file descriptor
  }
}

void RtspClient::handleRequest(const RtspMessage& rtspRequest, RtspClientConnectionPtr pConnection, const std::vector<std::string>& vSupported)
{
  assert(rtspRequest.isRequest());
  switch (rtspRequest.getMethod())
  {
    // TODO:
    //    case OPTIONS:
    //    {
    //      options(rtspRequest, pConnection);
    //      break;
    //    }
    //    case DESCRIBE:
    //    {
    //      describe(rtspRequest, pConnection);
    //      break;
    //    }
    //    case SETUP:
    //    {
    //      setup(rtspRequest, pConnection);
    //      break;
    //    }
    //    case PLAY:
    //    {
    //      play(rtspRequest, pConnection);
    //      break;
    //    }
    //    case PAUSE:
    //    {
    //      pause(rtspRequest, pConnection);
    //      break;
    //    }
    //    case TEARDOWN:
    //    {
    //      teardown(rtspRequest, pConnection);
    //      break;
    //    }
    //    case GET_PARAMETER:
    //    {
    //      getParameter(rtspRequest, pConnection);
    //      break;
    //    }
    //    case SET_PARAMETER:
    //    {
    //      setParameter(rtspRequest, pConnection);
    //      break;
    //    }
    default:
    {
      // TODO: BAD_REQUEST?!?
      // pConnection->write(0, createErrorResponse(BAD_REQUEST, rtspRequest.getCSeq()));
      break;
    }
  }
}

void RtspClient::handleResponse(const RtspMessage& rtspResponse, RtspClientConnectionPtr pConnection, const std::vector<std::string>& vSupported)
{
  bool bDummy;
  uint32_t uiSN = convert<uint32_t>(rtspResponse.getCSeq(), bDummy);
  assert(bDummy);
  auto it = m_mRequestMap.find(uiSN);
  if (it != m_mRequestMap.end())
  {
    RtspErrorCategory cat;
    boost::system::error_code ec(responseCodeToErrorCode(rtspResponse.getResponseCode()), cat);

    // get Supported header info
    vector<string> vSupported;
    optional<string> supported = rtspResponse.getHeaderField(SUPPORTED);
    if (supported)
    {
      vSupported = StringTokenizer::tokenize(*supported, ",", true, true);
    }

    // pop outstanding request
    assert(!m_qOutstandingRequests.empty());
    m_qOutstandingRequests.pop_front();
    // locate request and request handler
    switch (it->second.first)
    {
      case OPTIONS:
      {
        vector<string> vOptions;
        if (!ec)
        {
          optional<string> options = rtspResponse.getHeaderField(PUBLIC);
          if (options)
          {
            vOptions = StringTokenizer::tokenize(*options, ",", true, true);
          }
        }
        m_optionsHandler(ec, vOptions, vSupported);
        break;
      }
      case DESCRIBE:
      {
        m_describeHandler(ec, rtspResponse.getMessageBody(), vSupported);
        break;
      }
      case SETUP:
      {
        if (!ec)
        {
          // get session header
          optional<string> session = rtspResponse.getHeaderField(SESSION);
          optional<string> transportHeader = rtspResponse.getHeaderField(TRANSPORT);

          if (session)
          {
            const std::string sTimeout(";timeout=");
            size_t posTimeout = session->find(sTimeout);
            if (posTimeout != std::string::npos)
            {
              m_sSession = session->substr(0, posTimeout);
              assert(m_sSession.size() >= MIN_SESSION_LENGTH);

              bool bSuccess;
              m_uiSessionTimeout = convert<uint32_t>(session->substr(posTimeout + sTimeout.length()), bSuccess);
              if (!bSuccess)
              {
                LOG(WARNING) << "Failed to parse RTSP Session header: " << *session;
              }
              else
              {
                VLOG(2) << "RTSP session timeout " << m_uiSessionTimeout << "s";
              }
            }
            else
            {
              m_sSession = *session;
            }
          }
          else
          {
            LOG(WARNING) << "Setup contains no Session header";
            m_sSession = "";
          }
          if (m_sSession.empty())
          {
            LOG(WARNING) << "Setup success but empty Session!";
            m_setupHandler(ec, "", Transport(), vSupported);
          }

          if (!transportHeader)
          {
            LOG(WARNING) << "Setup success but empty Transport!";
            m_setupHandler(ec, "", Transport(), vSupported);
          }
          else
          {
            VLOG(5) << "Setup with transport: " << *transportHeader;
          }
          // get transport header
          Transport transport(*transportHeader);
          m_setupHandler(ec, m_sSession, transport, vSupported);
        }
        else
        {
          m_setupHandler(ec, "", Transport(), vSupported);
        }
        break;
      }
      case PLAY:
      {
        m_playHandler(ec, vSupported);
        break;
      }
      case TEARDOWN:
      {
        m_sSession = "";
        m_teardownHandler(ec, vSupported);
        break;
      }
      default:
      {
        LOG(WARNING) << "Unhandled method: " << methodToString(it->second.first);
      }
    }
  }
  else
  {
    LOG(WARNING) << "Unable to find original request!";
  }
}

} // rfc2326
} // rtp_plus_plus