text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_LIMITS_HPP
#define BOOST_UNITS_LIMITS_HPP

///
/// \file
/// \brief specialize std::numeric_limits for units.
///

#include <limits>

#include <boost/config.hpp>
#include <boost/units/units_fwd.hpp>

namespace std {

template<class Unit, class T>
class numeric_limits< ::boost::units::quantity<Unit, T> >
{
    public:
        typedef ::boost::units::quantity<Unit, T> quantity_type;
        static const bool is_specialized = std::numeric_limits<T>::is_specialized;
        static quantity_type (min)() { return(quantity_type::from_value((std::numeric_limits<T>::min)())); }
        static quantity_type (max)() { return(quantity_type::from_value((std::numeric_limits<T>::max)())); }
#ifndef BOOST_NO_CXX11_NUMERIC_LIMITS
        static quantity_type (lowest)() { return(quantity_type::from_value((std::numeric_limits<T>::lowest)())); }
#endif
        static const int digits = std::numeric_limits<T>::digits;
        static const int digits10 = std::numeric_limits<T>::digits10;
#ifndef BOOST_NO_CXX11_NUMERIC_LIMITS
        static const int max_digits10 = std::numeric_limits<T>::max_digits10;
#endif
        static const bool is_signed = std::numeric_limits<T>::is_signed;
        static const bool is_integer = std::numeric_limits<T>::is_integer;
        static const bool is_exact = std::numeric_limits<T>::is_exact;
        static const int radix = std::numeric_limits<T>::radix;
        static quantity_type epsilon()  { return(quantity_type::from_value(std::numeric_limits<T>::epsilon())); }
        static quantity_type round_error()  { return(quantity_type::from_value(std::numeric_limits<T>::round_error())); }
        static const int min_exponent = std::numeric_limits<T>::min_exponent;
        static const int min_exponent10 = std::numeric_limits<T>::min_exponent10;
        static const int max_exponent = std::numeric_limits<T>::max_exponent;
        static const int max_exponent10 = std::numeric_limits<T>::max_exponent10;
        static const bool has_infinity = std::numeric_limits<T>::has_infinity;
        static const bool has_quiet_NaN = std::numeric_limits<T>::has_quiet_NaN;
        static const bool has_signaling_NaN = std::numeric_limits<T>::has_signaling_NaN;
        static const bool has_denorm_loss = std::numeric_limits<T>::has_denorm_loss;
        static quantity_type infinity()  { return(quantity_type::from_value(std::numeric_limits<T>::infinity())); }
        static quantity_type quiet_NaN()  { return(quantity_type::from_value(std::numeric_limits<T>::quiet_NaN())); }
        static quantity_type signaling_NaN()  { return(quantity_type::from_value(std::numeric_limits<T>::signaling_NaN())); }
        static quantity_type denorm_min()  { return(quantity_type::from_value(std::numeric_limits<T>::denorm_min())); }
        static const bool is_iec559 = std::numeric_limits<T>::is_iec559;
        static const bool is_bounded = std::numeric_limits<T>::is_bounded;
        static const bool is_modulo = std::numeric_limits<T>::is_modulo;
        static const bool traps = std::numeric_limits<T>::traps;
        static const bool tinyness_before = std::numeric_limits<T>::tinyness_before;
#if defined(_STLP_STATIC_CONST_INIT_BUG)
        static const int has_denorm = std::numeric_limits<T>::has_denorm;
        static const int round_style = std::numeric_limits<T>::round_style;
#else
        static const float_denorm_style has_denorm = std::numeric_limits<T>::has_denorm;
        static const float_round_style round_style = std::numeric_limits<T>::round_style;
#endif
};

}

#endif // BOOST_UNITS_LIMITS_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#include "bindings-math.h"

#include "../luaapi/context.h"
#include "../luaapi/types.h"
#include "../luaapi/macros.h"

#include "CVec.h"
#include "util/angle.h"
#include "util/math_func.h"
#include "CodeAttributes.h"

#include <cmath>
#include <cstdio>
#include <string>
#include <iostream>

using std::cerr;
using std::endl;
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
using boost::lexical_cast;

namespace LuaBindings
{

INLINE lua_Number luaL_checknumber(lua_State *L, int narg)
{
	lua_Number d = lua_tonumber(L, narg);
	//if(d == 0 && !lua_isnumber(L, narg))
	//	; // TODO: tag_error(L, narg, LUA_TNUMBER);
	return d;
}

/*! sqrt(n)

	Returns the squareroot of n.
*/
int l_sqrt(lua_State* L)
{
	lua_pushnumber(L, sqrt(luaL_checknumber(L, 1)));
	return 1;
}

/*! abs(n)

	Returns the absolute value of n.
*/
int l_abs(lua_State* L)
{
	lua_pushnumber(L, fabs(luaL_checknumber(L, 1)));
	return 1;
}

/*! floor(n)

	Returns the number n rounded down towards infinity.
*/
int l_floor(lua_State* L)
{
	lua_pushnumber(L, floor(luaL_checknumber(L, 1)));
	return 1;
}

int l_round(lua_State* L)
{
	int d = lua_tointeger(L, 2);
	char buffer[256];
	sprintf(buffer, "%.*f", d, lua_tonumber(L, 1));
	lua_pushstring(L, buffer);
	return 1;
}

/*! randomint(l, u)

	Returns a random integer in the interval [l, u].
*/
int l_randomint(lua_State* L)
{
	int l = lua_tointeger(L, 1);
	int u = lua_tointeger(L, 2);

	//lua_pushnumber(L, l + (unsigned int)(rndgen()) % (u - l + 1));
	lua_pushinteger(L, l + rndInt(u - l + 1));

	return 1;
}

/*! randomfloat(l, u)

	Returns a random floating point number in the interval [l, u].
*/
int l_randomfloat(lua_State* L)
{
	lua_Number l = luaL_checknumber(L, 1);
	lua_Number u = luaL_checknumber(L, 2);

	lua_pushnumber(L, l + rnd() * (u - l));

	return 1;
}

/*! to_time_string(v)

	Converts a frame count //v// to a string showing hours, minutes and seconds as HH:MM:SS.
*/
int l_toTimeString(lua_State* L)
{
	lua_Integer v = lua_tointeger(L, 1);

	lua_Integer sec = v / 100;

	char c[8];
	c[0] = ((sec / 36000) % 10) + '0';
	c[1] = ((sec / 3600) % 10) + '0';
	c[2] = ':';
	c[3] = ((sec / 600) % 6) + '0';
	c[4] = ((sec / 60) % 10) + '0';
	c[5] = ':';
	c[6] = ((sec / 10) % 6) + '0';
	c[7] = (sec % 10) + '0';
	lua_pushlstring(L, c, 8);

	return 1;
}

/*! vector_diff(x1, y1, x2, y2)

	Returns a tuple equal to (x2 - x1, y2 - y1)
*/
int l_vector_diff(lua_State* L)
{
	lua_pushnumber(L, lua_tonumber(L, 3) - lua_tonumber(L, 1));
	lua_pushnumber(L, lua_tonumber(L, 4) - lua_tonumber(L, 2));

	return 2;
}

/*! vector_distance(x1, y1, x2, y2)

	Returns the distance from (x1, y1) to (x2, y2)
*/
int l_vector_distance(lua_State* L)
{
	lua_Number vx = lua_tonumber(L, 3) - lua_tonumber(L, 1);
	lua_Number vy = lua_tonumber(L, 4) - lua_tonumber(L, 2);
	vx *= vx;
	vy *= vy;
	lua_pushnumber(L, sqrt(vx + vy));

	return 1;
}

/*! vector_direction(x1, y1, x2, y2)

	Returns the angle between (x1, y1) and (x2, y2)
	in degrees.
*/
int l_vector_direction(lua_State* L)
{
	lua_Number vx = lua_tonumber(L, 3) - lua_tonumber(L, 1);
	lua_Number vy = lua_tonumber(L, 4) - lua_tonumber(L, 2);

	lua_pushnumber(L, rad2deg((float)atan2(vx, -vy)) );

	return 1;
}

/*! vector_add(x1, y1, x2, y2)

	Returns a tuple equal to (x1 + x2, y1 + y2)
*/
int l_vector_add(lua_State* L)
{
	lua_pushnumber(L, lua_tonumber(L, 1) + lua_tonumber(L, 3));
	lua_pushnumber(L, lua_tonumber(L, 2) + lua_tonumber(L, 4));

	return 2;
}

/*! angle_diff(a, b)

	Returns the relative angle in (-180, 180) between
	angle //a// and //b// such that (a + angle_diff(a, b)) = b (mod 360)
*/
int l_angle_diff(lua_State* L)
{
	AngleDiff diff(AngleDiff(lua_tonumber(L, 1)).relative(AngleDiff(lua_tonumber(L, 2))));

	lua_pushnumber(L, diff.toDeg());

	return 1;
}

/*! angle_clamp(angle)

	Returns //angle// normalized to [0, 360).
*/
int l_angle_clamp(lua_State* L)
{
	//lua_Number ang = lua_tonumber(L, 1);
	Angle ang((double)lua_tonumber(L, 1));

	ang.clamp();

	lua_pushnumber(L, ang.toDeg());

	return 1;
}

/*! angle_vector(angle[, length = 1])

	Returns a tuple representing the angle
	with length //length//.
*/
int l_angle_vector(lua_State* L)
{
	Angle ang((double)lua_tonumber(L, 1));
	lua_Number len = 1.0;

	if(lua_gettop(L) >= 2)
		len = lua_tonumber(L, 2);

	Vec vec(ang, len);
	lua_pushnumber(L, vec.x);
	lua_pushnumber(L, vec.y);

	return 2;
}

void initMath(LuaContext& context)
{
	context.functions()
		("sqrt", l_sqrt)
		("abs", l_abs)
		("floor", l_floor)

		("round", l_round)

		("randomint", l_randomint)
		("randomfloat", l_randomfloat)

		("to_time_string", l_toTimeString)

		("vector_diff", l_vector_diff)
		("vector_distance", l_vector_distance)
		("vector_direction", l_vector_direction)
		("vector_add", l_vector_add)

		("angle_clamp", l_angle_clamp)
		("angle_diff", l_angle_diff)
		("angle_vector", l_angle_vector)
	;
}

}

ext: cpp

max_stars_repo_name: JiPRA/openlierox

max_issues_repo_name: JiPRA/openlierox

max_forks_repo_name: JiPRA/openlierox


text:
#ifndef CUKE_STEPMANAGER_HPP_
#define CUKE_STEPMANAGER_HPP_

#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;

#include "../Table.hpp"
#include "../utils/Regex.hpp"

namespace cucumber {
namespace internal {

typedef unsigned int step_id_type;

class StepInfo;

class SingleStepMatch {
public:
    typedef RegexMatch::submatches_type submatches_type;

    operator const void *() const;

    boost::shared_ptr<const StepInfo> stepInfo;
    submatches_type submatches;
};

class MatchResult {
public:
    typedef std::vector<SingleStepMatch> match_results_type;

    const match_results_type& getResultSet();
    void addMatch(SingleStepMatch match);

    operator void *();
    operator bool() const;

private:
    match_results_type resultSet;
};

class InvokeArgs {
    typedef std::vector<std::string> args_type;
public:
    typedef args_type::size_type size_type;

    InvokeArgs() { }

    void addArg(const std::string arg);
    Table & getVariableTableArg();

    template<class T> T getInvokeArg(size_type i) const;
    const Table & getTableArg() const;
private:
    Table tableArg;
    args_type args;
};

enum InvokeResultType {
    SUCCESS,
    FAILURE,
    PENDING
};

class InvokeResult {
private:
    InvokeResultType type;
    std::string description;

    InvokeResult(const InvokeResultType type, const char *description);
public:
    InvokeResult();
    InvokeResult(const InvokeResult &ir);
    InvokeResult& operator= (const InvokeResult& rhs);

    static InvokeResult success();
    static InvokeResult failure(const char *description);
    static InvokeResult failure(const std::string &description);
    static InvokeResult pending(const char *description);

    bool isSuccess() const;
    bool isPending() const;
    InvokeResultType getType() const;
    const std::string &getDescription() const;
};

class StepInfo : public boost::enable_shared_from_this<StepInfo> {
public:
    StepInfo(const std::string &stepMatcher, const std::string source);
    SingleStepMatch matches(const std::string &stepDescription) const;
    virtual InvokeResult invokeStep(const InvokeArgs * pArgs) const = 0;

    step_id_type id;
    Regex regex;
    const std::string source;
private:
    StepInfo& operator=(const StepInfo& other);

};

class BasicStep {
public:
    InvokeResult invoke(const InvokeArgs *pArgs);

protected:
    typedef const Table table_type;
    typedef const Table::hashes_type table_hashes_type;

    virtual const InvokeResult invokeStepBody() = 0;
    virtual void body() = 0;

    void pending(const char *description);
    void pending();

    template<class T> const T getInvokeArg();
    const InvokeArgs *getArgs();
private:
    // FIXME: awful hack because of Boost::Test
    InvokeResult currentResult;

    const InvokeArgs *pArgs;
    InvokeArgs::size_type currentArgIndex;
};

template<class T>
class StepInvoker : public StepInfo {
public:
    StepInvoker(const std::string &stepMatcher, const std::string source);

    InvokeResult invokeStep(const InvokeArgs *args) const;
};

class StepManager {
protected:
    typedef std::map<step_id_type, boost::shared_ptr<const StepInfo> > steps_type;

public:
    virtual ~StepManager();

    void addStep(const boost::shared_ptr<StepInfo>& stepInfo);
    MatchResult stepMatches(const std::string &stepDescription) const;
    const boost::shared_ptr<const StepInfo>& getStep(step_id_type id);
protected:
    steps_type& steps() const;
};

static inline std::string toSourceString(const char *filePath, const int line) {
    using namespace std;
    stringstream s;
    string file(filePath);
    string::size_type pos = file.find_last_of("/\\");
    if (pos == string::npos) {
        s << file;
    } else {
       s << file.substr(++pos);
    }
    s << ":" << line;
    return s.str();
}

template<class T>
static int registerStep(const std::string &stepMatcher, const char *file, const int line) {
   StepManager s;
   boost::shared_ptr<StepInfo> stepInfo(boost::make_shared< StepInvoker<T> >(stepMatcher, toSourceString(file, line)));
   s.addStep(stepInfo);
   return stepInfo->id;
}

template<typename T>
T fromString(const std::string& s) {
    std::istringstream stream(s);
    T t;
    stream >> t;
    if (stream.fail()) {
        throw std::invalid_argument("Cannot convert parameter");
    }
    return t;
}

template<>
inline std::string fromString(const std::string& s) {
    return s;
}

template<typename T>
std::string toString(T arg) {
    std::stringstream s;
    s << arg;
    return s.str();
}

template<typename T>
T InvokeArgs::getInvokeArg(size_type i) const {
    if (i >= args.size()) {
        throw std::invalid_argument("Parameter not found");
    }
    return fromString<T>(args.at(i));
}

template<typename T>
const T BasicStep::getInvokeArg() {
    return pArgs->getInvokeArg<T>(currentArgIndex++);
}

template<class T>
StepInvoker<T>::StepInvoker(const std::string &stepMatcher, const std::string source) :
    StepInfo(stepMatcher, source) {
}

template<class T>
InvokeResult StepInvoker<T>::invokeStep(const InvokeArgs *pArgs) const {
    T t;
    return t.invoke(pArgs);
}

}
}

#endif /* CUKE_STEPMANAGER_HPP_ */

ext: hpp

max_stars_repo_name: OAkyildiz/oscc-joystick-commander


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

#include <boost/filesystem.hpp>
#include <chrono>
#include <portaudio.h>
#include <sndfile.h>
#include <stdexcept>
#include <vector>

#include "./recognizer.h"

namespace picovoice_driver
{
std::string getEpochStamp()
{
  using namespace std::chrono;
  unsigned long ms_since_epoch = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
  unsigned long seconds_since_epoch = ms_since_epoch / 1e3;
  unsigned long ms_decimals_since_epoch = ms_since_epoch - seconds_since_epoch * 1e3;
  return std::to_string(seconds_since_epoch) + "." + std::to_string(ms_decimals_since_epoch);
}

void writeWav(const std::vector<int16_t>& buffer, size_t buffer_size, size_t sample_rate, const std::string& directory)
{
  boost::filesystem::create_directories(directory);
  std::string filename = directory + "/recording-" + getEpochStamp() + ".wav";

  SF_INFO sfinfo;
  sfinfo.channels = 1;
  sfinfo.samplerate = sample_rate;
  sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
  SNDFILE* outfile = sf_open(filename.c_str(), SFM_WRITE, &sfinfo);
  if (outfile != nullptr)
  {
    sf_write_short(outfile, buffer.data(), buffer_size);
    sf_write_sync(outfile);
    sf_close(outfile);
  }
}

void Recognizer::recognizeThread()
{
  preempt_requested_.store(false);
  is_recognizing_.store(true);

  PaError err = Pa_Initialize();
  if (err != paNoError)
  {
    is_recognizing_.store(false);
    throw std::runtime_error("Failed to initialize PortAudio");
  }

  PaStreamParameters input_parameters;
  input_parameters.device = Pa_GetDefaultInputDevice();
  if (input_parameters.device == paNoDevice)
  {
    Pa_Terminate();
    is_recognizing_.store(false);
    throw std::runtime_error("Could not get default input device");
  }
  input_parameters.channelCount = 1;
  input_parameters.sampleFormat = paInt16;
  input_parameters.suggestedLatency = Pa_GetDeviceInfo(input_parameters.device)->defaultLowInputLatency;
  input_parameters.hostApiSpecificStreamInfo = NULL;

  RecordSettings record_settings;
  try
  {
    record_settings = getRecordSettings();
  }
  catch (const std::exception& e)
  {
    Pa_Terminate();
    is_recognizing_.store(false);
    throw std::runtime_error("getRecordSettings failed: " + std::string(e.what()));
  }

  try
  {
    recognizeInit();
  }
  catch (const std::exception& e)
  {
    Pa_Terminate();
    is_recognizing_.store(false);
    throw std::runtime_error("recognizeInit failed: " + std::string(e.what()));
  }

  PaStream* stream;
  err = Pa_OpenStream(&stream, &input_parameters, NULL, record_settings.sample_rate_, paFramesPerBufferUnspecified,
                      paClipOff, NULL, NULL);
  if (err != paNoError)
  {
    Pa_Terminate();
    is_recognizing_.store(false);
    throw std::runtime_error("Could not open stream");
  }

  err = Pa_StartStream(stream);
  if (err != paNoError)
  {
    Pa_Terminate();
    is_recognizing_.store(false);
    throw std::runtime_error("Could not start stream");
  }

  bool is_finalized = false;
  size_t sample_index = 0;
  size_t total_samples = record_timeout_ * record_settings.sample_rate_;
  std::vector<int16_t> recorded_samples(total_samples * sizeof(int16_t));
  while (sample_index < total_samples && !is_finalized && !preempt_requested_.load())
  {
    err = Pa_ReadStream(stream, &recorded_samples.data()[sample_index], record_settings.frame_length_);
    if (err)
    {
      Pa_Terminate();
      is_recognizing_.store(false);
      throw std::runtime_error("Could not read stream");
    }

    try
    {
      is_finalized = recognizeProcess(&recorded_samples[sample_index]);
    }
    catch (const std::exception& e)
    {
      Pa_Terminate();
      is_recognizing_.store(false);
      throw std::runtime_error("recognizeProcess failed: " + std::string(e.what()));
    }
    sample_index += record_settings.frame_length_;
  }

  Pa_Terminate();

  if (!record_directory_.empty())
  {
    writeWav(recorded_samples, sample_index, record_settings.sample_rate_, record_directory_);
  }

  is_recognizing_.store(false);
}

void Recognizer::recognizeThreadCatchException()
{
  try
  {
    recognizeThread();
  }
  catch (const std::exception& e)
  {
    recognize_thread_exception_string_ = std::string(e.what());
  }
}

void Recognizer::initialize(const std::string& record_directory, double record_timeout)
{
  record_directory_ = record_directory;
  record_timeout_ = record_timeout;
  initialized_ = true;
}

void Recognizer::recognize()
{
  if (!initialized_)
  {
    throw std::runtime_error("Recognizer not initialized");
  }

  if (recognize_thread_ != nullptr)
  {
    throw std::runtime_error("Already recognizing");
  }
  recognize_thread_exception_string_.clear();
  is_recognizing_.store(true);
  recognize_thread_.reset(new std::thread(&Recognizer::recognizeThreadCatchException, this));
}

void Recognizer::preempt()
{
  if (!initialized_)
  {
    throw std::runtime_error("Recognizer not initialized");
  }
  preempt_requested_.store(true);
}

bool Recognizer::isPreempting()
{
  if (!initialized_)
  {
    throw std::runtime_error("Recognizer not initialized");
  }
  return preempt_requested_.load();
}

bool Recognizer::isRecognizing()
{
  if (!initialized_)
  {
    throw std::runtime_error("Recognizer not initialized");
  }
  bool is_recognizing = is_recognizing_.load();
  if (!is_recognizing)
  {
    recognize_thread_->join();
    recognize_thread_.reset();
    if (!recognize_thread_exception_string_.empty())
    {
      throw std::runtime_error("Recognize thread exception: " + recognize_thread_exception_string_);
    }
  }
  return is_recognizing;
}
}  // namespace picovoice_driver


text:
//
//  frame-buffer.h
//  ndnrtc
//
//  Copyright 2013 Regents of the University of California
//  For licensing details see the LICENSE file.
//
//  Author:  Peter Gusev
//

#ifndef __ndnrtc__frame_buffer__
#define __ndnrtc__frame_buffer__

#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
#include <ndn-cpp/name.hpp>

#include "name-components.hpp"

#include "slot-buffer.hpp"
#include "ndnrtc-object.hpp"

namespace ndn {
    class Interest;
    class Data;
    class Name;
}

namespace ndnrtc
{
    namespace statistics {
        class StatisticsStorage;
    }

    struct _CommonHeader;
    class WireSegment;

    class SlotSegment {
    public:

        SlotSegment(const boost::shared_ptr<const ndn::Interest>&);

        const NamespaceInfo& getInfo() const;
        void setData(const boost::shared_ptr<WireSegment>& data);
        const boost::shared_ptr<WireSegment>& getData() const { return data_; }

        bool isFetched() const { return data_.get(); }
        bool isPending() const { return !data_.get(); }
        bool isRightmostRequested() const { return !interestInfo_.hasSeqNo_; }
        bool isOriginal() const;

        int64_t getRequestTimeUsec() const { return requestTimeUsec_; }

        int64_t getArrivalTimeUsec() const { return arrivalTimeUsec_; }

        void incrementRequestNum() { requestNo_++; }
        size_t getRequestNum() const { return requestNo_; }

        /**
         * Returns round-trip time delay in microseconds if data has arrived.
         * Otherwise, returns -1.
         */
        int64_t getRoundTripDelayUsec() const
        {
            if (arrivalTimeUsec_ <= 0) return -1;
            return (arrivalTimeUsec_-requestTimeUsec_);
        }

        /**
         * Returns interest used to fetch this segment
         */
        boost::shared_ptr<const ndn::Interest> getInterest() const { return interest_; }

        /**
         * Takes into account if the segment is original or not.
         * If the segment is original, this returns getRoundTripDelayUsec() minus
         * generation delay received in metadata for the segment.
         */
        int64_t getDrdUsec() const;
        int64_t getDgen() const;

    private:
        boost::shared_ptr<const ndn::Interest> interest_;
        NamespaceInfo interestInfo_;
        boost::shared_ptr<WireSegment> data_;
        int64_t requestTimeUsec_, arrivalTimeUsec_;
        size_t requestNo_;
        bool isVerified_;
    };

    //******************************************************************************
    class VideoFrameSlot;
    class AudioBundleSlot;
    class Buffer;
    class Manifest;
    class SampleValidator;
    class ManifestValidator;

    class BufferSlot
    {
    public:
        enum State {
            Free = 1<<0,  // slot is free for being used
            New = 1<<1,   // slot is being used for assembling, but has
                            // not recevied any data segments yet
            Assembling = 1<<2,    // slot is being used for assembling and
                                    // already has some data segments arrived
            Ready = 1<<3, // slot assembled all the data and is ready for
                            // decoding a frame
            Locked = 1<<4 // slot is locked for playout
        }; // enum State

        enum Verification {
            Unknown = 1<<0,
            Failed = 1<<1,
            Verified = 1<<2
        };

        typedef enum _Consistency {
            Inconsistent = 0,        // slot has no meta info yet
            SegmentMeta = 1<<1,         // slot has meta extracted from
                                        // segment header
            HeaderMeta = 1<<2,    // slot has meta data from the
                                  // header, provided by producer
            Consistent = SegmentMeta|HeaderMeta // all meta data is ready
        } Consistency;

        BufferSlot();
        ~BufferSlot(){}

        /**
         * Adds issued Interests to this slot.
         * @param interests Vector of Interests' shared pointers
         * @note Interst names should relate to the same sample, and have segment
         * numbers (no rightmost Interests allowed). Otherwise, this throws an
         * exception (basic guarantee - one need to clear slot in order to re-use it
         * again).
         * @see clear()
         */
        void
        segmentsRequested(const std::vector<boost::shared_ptr<const ndn::Interest>>& interests);

        /**
         * Clears all internal structures of this slot and returns to Free state
         * as if slot has just been created. No memory deallocation/reallocation is
         * performed, thus operation is not expensive.
         */
        void
        clear();

        /**
         * Adds received segment to this slot.
         * @param segment Received segment
         * @note Added segment's name should correspond to one of the Interests,
         * previously added using segmentsRequested method. Otherwise, this throws.
         * Provides strong guarantee.
         * @return Slot segment that contains received segment and previously
         * expressed Interest; it can be used for retrieving segment-level metadata
         * like Data Retrieval Delays, etc.
         */
        const boost::shared_ptr<SlotSegment>
        segmentReceived(const boost::shared_ptr<WireSegment>& segment);

        /**
         * Returns an array of names of missing segments
         */
        std::vector<ndn::Name> getMissingSegments() const;

        /**
         * Returns an array of pending Interests for this slot
         */
        std::vector<boost::shared_ptr<const ndn::Interest>> getPendingInterests() const;

        /**
         * Returns boolean value on whether slot is verified
         */
        Verification getVerificationStatus() const { return verified_; }

        State getState() const { return state_; }

        double getAssembledLevel() const { return asmLevel_; }

        const ndn::Name& getPrefix() const { return name_; }
        const NamespaceInfo& getNameInfo() const { return nameInfo_; }
        int getConsistencyState() const { return consistency_; }
        unsigned int getRtxNum() const { return nRtx_; }
        int getRtxNum(const ndn::Name& segmentName);
        bool hasOriginalSegments() const { return hasOriginalSegments_; }
        size_t getFetchedNum() const { return fetched_.size(); }
        void toggleLock();

        int64_t getAssemblingTime() const
        { return ( state_ >= Ready ? assembledTimeUsec_-firstSegmentTimeUsec_ : 0); }
        int64_t getShortestDrd() const
        { return (state_ >= Assembling ? firstSegmentTimeUsec_-requestTimeUsec_ : 0); }
        int64_t getLongestDrd() const
        { return (state_ >= Ready ? assembledTimeUsec_ - requestTimeUsec_ : 0); }

        /**
         * Returns common packet header if it's available (HeaderMeta consistency),
         * otherwise throws an error.
         * @return CommonHeader structure
         * @see CommonSamplePacket
         */
        const _CommonHeader getHeader() const;

        std::string
        dump(bool showLastSegment = false) const;

    private:
        friend VideoFrameSlot;
        friend AudioBundleSlot;
        friend SampleValidator;
        friend ManifestValidator;
        friend Buffer;

        ndn::Name name_;
        NamespaceInfo nameInfo_;
        std::map<ndn::Name, boost::shared_ptr<SlotSegment>> requested_, fetched_;
        boost::shared_ptr<SlotSegment> lastFetched_;
        unsigned int consistency_, nRtx_, assembledSize_;
        unsigned int nDataSegments_, nParitySegments_;
        bool hasOriginalSegments_;
        State state_;
        int64_t requestTimeUsec_, firstSegmentTimeUsec_, assembledTimeUsec_;
        double assembled_, asmLevel_;
        mutable boost::shared_ptr<Manifest> manifest_;
        mutable Verification verified_;

        virtual void updateConsistencyState(const boost::shared_ptr<SlotSegment>& segment);
        void updateAssembledLevel();
    };

    //******************************************************************************
    template<typename T>
    class VideoFramePacketT;
    struct Immutable;
    typedef VideoFramePacketT<Immutable> ImmutableFrameAlias;
    struct _VideoFrameSegmentHeader;

    class VideoFrameSlot {
    public:
        VideoFrameSlot(const size_t storageSize = 16000);

        /**
         * Tries to read VideoFramePacket from supplied BufferSlot.
         * Also tries to recover frame using available FEC data, if possible.
         * In this case, recovered flag is set to true;
         * @param slot Buffer slot that contains segments of video frame packet
         * @return shared_ptr of ImmutableVideoFramePacket or nullptr if
         * recovery attempt failed
         */
        boost::shared_ptr<ImmutableFrameAlias>
        readPacket(const BufferSlot& slot, bool& recovered);

        _VideoFrameSegmentHeader
        readSegmentHeader(const BufferSlot& slot);

    private:
        boost::shared_ptr<std::vector<uint8_t>> storage_;
        std::vector<uint8_t> fecList_;
    };

    //******************************************************************************
    template<typename T>
    class AudioBundlePacketT;
    typedef AudioBundlePacketT<Immutable> ImmutableAudioBundleAlias;

    class AudioBundleSlot {
    public:
        AudioBundleSlot(const size_t storageSize = 2000);

        /**
         * Tries to read AudioBundlePacket from supplied BufferSlot.
         * @param slot Buffer slot that contains segment(s) of audio bundle
         * @return shared_ptr of ImmutableAudioBundle packet or nullptr if
         * failed to read data.
         */
        boost::shared_ptr<ImmutableAudioBundleAlias>
        readBundle(const BufferSlot& slot);

    private:
        boost::shared_ptr<std::vector<uint8_t>> storage_;
    };

    //******************************************************************************
    class SlotPool {
    public:
        SlotPool(const size_t& capacity = 300);

        boost::shared_ptr<BufferSlot> pop();
        bool push(const boost::shared_ptr<BufferSlot>& slot);

        size_t capacity() const { return capacity_; }
        size_t size() const { return pool_.size(); }

    private:
        SlotPool(const SlotPool&) = delete;

        size_t capacity_;
        std::vector<boost::shared_ptr<BufferSlot>> pool_;
    };

    //******************************************************************************
    class IBufferObserver;
    class PlaybackQueue;

    typedef struct _BufferReceipt {
        boost::shared_ptr<const BufferSlot> slot_;
        boost::shared_ptr<const SlotSegment> segment_;
        BufferSlot::State oldState_;
    } BufferReceipt;

    class IBuffer {
    public:
        virtual void reset() = 0;
        virtual bool requested(const std::vector<boost::shared_ptr<const ndn::Interest>>&) = 0;
        virtual BufferReceipt received(const boost::shared_ptr<WireSegment>&) = 0;
        virtual bool isRequested(const boost::shared_ptr<WireSegment>&) const = 0;
        virtual unsigned int getSlotsNum(const ndn::Name&, int) const = 0;
        virtual std::string shortdump() const = 0;
        virtual void attach(IBufferObserver* observer) = 0;
        virtual void detach(IBufferObserver* observer) = 0;
    };

    class Buffer : public NdnRtcComponent, public IBuffer {
    public:
        Buffer(boost::shared_ptr<statistics::StatisticsStorage> storage,
               boost::shared_ptr<SlotPool> pool =
                boost::shared_ptr<SlotPool>(new SlotPool()));

        void reset();

        bool requested(const std::vector<boost::shared_ptr<const ndn::Interest>>&);
        BufferReceipt received(const boost::shared_ptr<WireSegment>& segment);
        bool isRequested(const boost::shared_ptr<WireSegment>& segment) const;
        unsigned int getSlotsNum(const ndn::Name& prefix, int stateMask) const;

        void attach(IBufferObserver* observer);
        void detach(IBufferObserver* observer);
        boost::shared_ptr<SlotPool> getPool() const { return pool_; }

        std::string
        dump() const;

    private:
        friend PlaybackQueue;

        mutable boost::recursive_mutex mutex_;
        boost::shared_ptr<SlotPool> pool_;
        std::map<ndn::Name, boost::shared_ptr<BufferSlot>> activeSlots_, reservedSlots_;
        std::vector<IBufferObserver*> observers_;
        boost::shared_ptr<statistics::StatisticsStorage> sstorage_;

        std::string
        shortdump() const;

        void
        dumpSlotDictionary(std::stringstream&,
            const std::map<ndn::Name, boost::shared_ptr<BufferSlot>> &) const;

        void invalidate(const ndn::Name& slotPrefix);
        void invalidatePrevious(const ndn::Name& slotPrefix);

        void reserveSlot(const boost::shared_ptr<const BufferSlot>& slot);
        void releaseSlot(const boost::shared_ptr<const BufferSlot>& slot);
    };

    class IBufferObserver {
    public:
        virtual void onNewRequest(const boost::shared_ptr<BufferSlot>&) = 0;
        virtual void onNewData(const BufferReceipt& receipt) = 0;
        virtual void onReset() = 0;
    };

    //******************************************************************************
    typedef boost::function<void(const boost::shared_ptr<const BufferSlot>& slot, double playTimeMs)> ExtractSlot;
    class IPlaybackQueueObserver;

    class IPlaybackQueue {
    public:
        virtual void pop(ExtractSlot) = 0;
        virtual int64_t size() const = 0;
        virtual int64_t pendingSize() const = 0;
        virtual double sampleRate() const = 0;
        virtual double samplePeriod() const = 0;
        virtual void attach(IPlaybackQueueObserver*) = 0;
        virtual void detach(IPlaybackQueueObserver*) = 0;
    };

    /**
     * Class PaybackQueue implements functionality for ordering assembled frames
     * in playback order and provides interface for extracting media samples
     * for playback
     */
    class PlaybackQueue : public NdnRtcComponent,
                          public IPlaybackQueue,
                          public IBufferObserver
    {
    public:
        PlaybackQueue(const ndn::Name& streamPrefix,
            const boost::shared_ptr<Buffer>& buffer);
        ~PlaybackQueue();

        void
        pop(ExtractSlot extract);

        /**
         * This returns size in milliseconds of actual playable content
         * @return Duration in milliseconds of playable content
         */
        int64_t size() const;

        /**
         * This returns size in milliseconds of (estimated) pending content -
         * the content that has not arrived from network yet.
         */
        int64_t pendingSize() const;

        void attach(IPlaybackQueueObserver* observer);
        void detach(IPlaybackQueueObserver* observer);

        double sampleRate() const { return packetRate_; }
        double samplePeriod() const { return (packetRate_ ? 1000./packetRate_ : 0); }

        std::string dump();

    private:
        class Sample {
        public:
            Sample(const boost::shared_ptr<const BufferSlot>& slot):slot_(slot){}

            boost::shared_ptr<const BufferSlot> slot() const { return slot_; }
            int64_t timestamp() const;
            bool operator<(const Sample& sample) const
            { return this->timestamp() < sample.timestamp(); }

        private:
            boost::shared_ptr<const BufferSlot> slot_;
        };

        mutable boost::recursive_mutex mutex_;
        ndn::Name streamPrefix_;
        boost::shared_ptr<Buffer> buffer_;
        double packetRate_;
        std::set<Sample> queue_;
        std::vector<IPlaybackQueueObserver*> observers_;
        boost::shared_ptr<statistics::StatisticsStorage> sstorage_;

        virtual void onNewRequest(const boost::shared_ptr<BufferSlot>&);
        virtual void onNewData(const BufferReceipt& receipt);
        virtual void onReset();
    };

    class IPlaybackQueueObserver
    {
    public:
        virtual void onNewSampleReady() = 0;
    };
}

#endif /* defined(__ndnrtc__frame_buffer__) */


text:
#ifndef CALIBRATION_HPP_13e0c05f_3feb_4044_8590_91faa2cfc1b0
#define CALIBRATION_HPP_13e0c05f_3feb_4044_8590_91faa2cfc1b0

#include <iostream>
#include <fstream>
#include <limits>
#ifdef FILESYSTEM_EXPERIMENTAL
#include <experimental/filesystem>
namespace filesystem = std::experimental::filesystem;
#elif defined(STD_FILESYSTEM)
#include <filesystem>
namespace filesystem = std::filesystem;
#else
#include <boost/filesystem>
#endif

#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>

#include <yaml-cpp/yaml.h>

#include "util.h"
#include "ImageMeta.h"

inline bool is_opencv_yaml(filesystem::path metafile)
//-------------------------------------------------------
{
   std::string ext = metafile.extension();
   std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
   if (ext.substr(0, 5) == ".yaml")
   {
      std::ifstream ifs(metafile.string());
      std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
      return !(content.substr(0, 6) != "%YAML:");
   }
   return false;
}

class Calibration
//===============
{
public:
   Calibration() : fx(std::numeric_limits<double>::quiet_NaN()), fy(std::numeric_limits<double>::quiet_NaN()),
                   cx(std::numeric_limits<double>::quiet_NaN()), cy(std::numeric_limits<double>::quiet_NaN()) {};
   Calibration(double fx, double fy, double ox, double oy, int w, int h) : fx(fx), fy(fy), cx(ox), cy(oy), image_width(w), image_height(h) {}

   Calibration(const Calibration& other) = default;
   Calibration& operator=(const Calibration &other) = default;

   bool open(std::string file, std::stringstream* errs = nullptr)
   //------------------------------------------------------------
   {
      filesystem::path calibration_file = filesystem::absolute(file);
      if (filesystem::exists(calibration_file))
      {
         std::string ext = calibration_file.extension();
         std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
         if ( (is_opencv_yaml(calibration_file)) || (ext.substr(0, 4) == ".xml") )
         {
            cv::Mat intrinsics; //  distortion, intrinsics_inverse;
//            int image_width, image_height;
//            double rms_error =0, total_error =0;
            cv::FileStorage fs(calibration_file.string(), cv::FileStorage::READ);
            cv::FileNode fn = fs["CalibrationValues"];
            fn["intrinsics"] >> intrinsics;
            fx = intrinsics.at<double>(0, 0);
            fy = intrinsics.at<double>(1, 1);
            cx = intrinsics.at<double>(2, 0);
            cy = intrinsics.at<double>(2, 1);
//            fn["distortion"] >> distortion;
            image_width = (int) fn["width"];
            image_height = (int) fn["height"];
//            rms_error = (double) fn["rms_error"];
//            total_error = (double) fn["total_error"];
            if ( (image_width <= 0) || (image_height <= 0) )
               image_size(calibration_file);
            return  ( (fx > 0) && (fy > 0) && (cx >= 0) && (cy >= 0) );
         }
         else
         {
            if (ext.substr(0, 5) == ".yaml")
            {
               try
               {
                  YAML::Node root = YAML::LoadFile(calibration_file.c_str());
                  fx = (root["fx"]) ? root["fx"].as<double>() : std::numeric_limits<float>::quiet_NaN();
                  fy = (root["fy"]) ? root["fy"].as<double>() : std::numeric_limits<float>::quiet_NaN();
                  YAML::Node n = root["cx"];
                  if (! n)
                     n = root["ox"];
                  if (n) cx = n.as<double>();
                  n = root["cy"];
                  if (! n)
                     n = root["oy"];
                  if (n) cy = n.as<double>();
                  n = root["width"];
                  if (! n)
                     n = root["imagewidth"];
                  if (n) image_width = n.as<int>();
                  n = root["height"];
                  if (! n)
                     n = root["imageheight"];
                  if (n) image_height = n.as<int>();
               }
               catch (std::exception& e)
               {
                  if (errs != nullptr)
                     *errs << "Error reading calibration file " << filesystem::absolute(calibration_file).string();
                  return false;
               }
               if ( (image_width <= 0) || (image_height <= 0) )
                  image_size(calibration_file);
               return  ( (fx > 0) && (fy > 0) && (cx >= 0) && (cy >= 0) );
            }
         }

         // comma delimited
         std::ifstream ifs(calibration_file.string());
         std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
         content.erase(std::remove(content.begin(), content.end(), ' '), content.end());
         content.erase(std::remove(content.begin(), content.end(), '\t'), content.end());
         content.erase(std::remove(content.begin(), content.end(), '\n'), content.end());
         return set(content);

         return false;
      }
      else
         return false;
   }

   bool save(std::string file, bool is_overwrite = true, std::stringstream* errs = nullptr)
   //------------------------------------------------------------
   {
      filesystem::path calibration_file = filesystem::absolute(file);
      if ( (filesystem::exists(calibration_file)) && (! is_overwrite) )
      {
         if (errs)
            *errs << calibration_file.string() << " exists";
         return false;
      }

      std::string ext = calibration_file.extension();
      std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);

      if (ext.substr(0, 4) == ".xml")
      {
         cv::FileStorage fs(calibration_file.c_str(), cv::FileStorage::WRITE);
         fs << "CalibrationValues" << "{";
         fs << "intrinsics" << asMat3x3f() << "distortion" << 0 << "width" << image_width << "height"
            << image_height << "rms_error" << 0 << "total_error" << 0 << "}";
         return true;
      }
      else
      {
         YAML::Emitter out;
         out.SetIndent(3);
         out << YAML::BeginMap;
         out << YAML::Key << "fx" << YAML::Value << fx;
         out << YAML::Key << "fy" << YAML::Value << fy;
         out << YAML::Key << "cx" << YAML::Value << cx;
         out << YAML::Key << "cy" << YAML::Value << cy;
         if ( (image_width > 0) && (image_height > 0) )
         {
            out << YAML::Key << "imagewidth" << YAML::Value << image_width;
            out << YAML::Key << "imageheight" << YAML::Value << image_height;
         }
         out << YAML::EndMap;
         std::ofstream of(calibration_file.c_str());
         of << out.c_str();
         return of.good();
      }
   }

   bool set(std::string delimited, std::stringstream* errs = nullptr)
   //--------------------------------------------------------------
   {
      std::vector<std::string> tokens;
      size_t n = split(delimited, tokens, ",");
      if (n >= 4)
      {
         try
         {
            fx = std::stod(trim(tokens[0]));
            fy = std::stod(trim(tokens[1]));
            cx = std::stod(trim(tokens[2]));
            cy = std::stod(trim(tokens[3]));
            image_width = image_height = -1;
            if (n > 4)
               image_width = std::stoi(tokens[4]);
            if (n > 5)
               image_height = std::stoi(tokens[5]);

         }
         catch (std::exception &e)
         {
            if (errs != nullptr)
               *errs << "Invalid (non numeric) values in comma delimited calibration values " << " (" << tokens[0] << ","
                     << tokens[1] << "," << tokens[2] << "," << tokens[3] << ")";
            return false;
         }
         return true;
      }
      return false;
   }

   cv::Matx33f asMatx3x3f() { return cv::Matx33f(fx, 0, cx, 0, fy, cy, 0, 0, 1); }

   cv::Matx33f asMatx3x3d() { return cv::Matx33d(fx, 0, cx, 0, fy, cy, 0, 0, 1); }

   cv::Mat asMat3x3d()
   {
      cv::Mat K = cv::Mat::eye(3, 3, CV_64FC1);
      K.at<double>(0, 0) = fx;
      K.at<double>(1, 1) = fy;
      K.at<double>(0, 2) = cx;
      K.at<double>(1, 2) = cy;
      return K;
   }

   cv::Mat asMat3x3f()
   {
      cv::Mat K = cv::Mat::eye(3, 3, CV_32FC1);
      K.at<float>(0, 0) = static_cast<float>(fx);
      K.at<float>(1, 1) = static_cast<float>(fy);
      K.at<float>(0, 2) = static_cast<float>(cx);
      K.at<float>(1, 2) = static_cast<float>(cy);
      return K;
   }

private:
   double fx, fy, cx, cy;
   int image_width =-1, image_height =-1;

   void image_size(filesystem::path& calibration_path)
   //------------------------------------------------
   {
      filesystem::path base = calibration_path.parent_path() / calibration_path.stem();
      filesystem::path imgfile(base.string() + ".png");
      cv::Mat img;
      if (filesystem::exists(imgfile))
         img = cv::imread(imgfile.c_str());
      if (img.empty())
      {
         imgfile = filesystem::path(base.string() + ".jpg");
         if (filesystem::exists(imgfile))
            img = cv::imread(imgfile.c_str());
      }
      if (img.empty())
      {
         imgfile = filesystem::path(base.string() + ".jpeg");
         if (filesystem::exists(imgfile))
            img = cv::imread(imgfile.c_str());
      }
      if (! img.empty())
      {
         image_width = img.cols;
         image_height = img.rows;
      }
   }
};
#endif //TRAINER_CALIBRATION_HPP

ext: hh

max_stars_repo_name: donaldmunro/PlanarTrainer

max_issues_repo_name: donaldmunro/PlanarTrainer

max_forks_repo_name: donaldmunro/PlanarTrainer


text:
#pragma once

#include <array>
#include <vector>

#include "octotiger/cuda_util/cuda_global_def.hpp"
#include "octotiger/hydro_defs.hpp"
#include "octotiger/unitiger/hydro.hpp"
#include "octotiger/unitiger/safe_real.hpp"

#include <buffer_manager.hpp>
#ifdef OCTOTIGER_HAVE_CUDA
#include <cuda_buffer_util.hpp>
#include <cuda_runtime.h>
#include <stream_manager.hpp>
#include "octotiger/cuda_util/cuda_helper.hpp"
#endif

#include <boost/container/vector.hpp>    // to get non-specialized vector<bool>

timestep_t flux_kernel_interface(const hydro::recon_type<NDIM>& Q, hydro::flux_type& F,
    hydro::x_type& X, safe_real omega, const size_t nf_);

// Vc kernels
#if defined(__x86_64__) && defined(OCTOTIGER_HAVE_VC)
timestep_t flux_cpu_kernel(const hydro::recon_type<NDIM>& Q, hydro::flux_type& F, hydro::x_type& X,
    safe_real omega, const size_t nf_);
timestep_t flux_unified_cpu_kernel(const hydro::recon_type<NDIM>& Q, hydro::flux_type& F,
    hydro::x_type& X, safe_real omega, const size_t nf_);
#endif

#ifdef OCTOTIGER_HAVE_CUDA
timestep_t launch_flux_cuda(
    stream_interface<hpx::cuda::experimental::cuda_executor, pool_strategy>& executor,
    double* device_q,
    std::vector<double, recycler::recycle_allocator_cuda_host<double>>& combined_f,
    std::vector<double, recycler::recycle_allocator_cuda_host<double>> &combined_x, double* device_x,
    safe_real omega, const size_t nf_, double dx, size_t device_id);
void launch_flux_cuda_kernel_post(stream_interface<hpx::cuda::experimental::cuda_executor, pool_strategy>& executor,
    dim3 const grid_spec, dim3 const threads_per_block, void *args[]);
#endif

// helpers for using vectortype specialization functions
template <typename double_t, typename cond_t>
CUDA_GLOBAL_METHOD inline void select_wrapper(
    double_t& target, const cond_t cond, const double_t& tmp1, const double_t& tmp2) {
    target = cond ? tmp1 : tmp2;
}
template <typename T>
CUDA_GLOBAL_METHOD inline T max_wrapper(const T& tmp1, const T& tmp2) {
    return max(tmp1, tmp2);
}
template <typename T>
CUDA_GLOBAL_METHOD inline T min_wrapper(const T& tmp1, const T& tmp2) {
    return min(tmp1, tmp2);
}
template <typename T>
CUDA_GLOBAL_METHOD inline T sqrt_wrapper(const T& tmp1) {
    return std::sqrt(tmp1);
}
template <typename T>
CUDA_GLOBAL_METHOD inline T pow_wrapper(const T& tmp1, const double& tmp2) {
    return std::pow(tmp1, tmp2);
}
template <typename T>
CUDA_GLOBAL_METHOD inline T asinh_wrapper(const T& tmp1) {
    return std::asinh(tmp1);
}
template <typename T>
CUDA_GLOBAL_METHOD inline bool skippable(const T& tmp1) {
    return !tmp1;
}
template <typename T>
CUDA_GLOBAL_METHOD inline T load_value(const double* data, const size_t index) {
    return data[index];
}
template <typename T>
CUDA_GLOBAL_METHOD inline void store_value(
    double* data, const size_t index, const T& value) {
    data[index] = value;
}
template <typename T, typename container_t>
CUDA_GLOBAL_METHOD inline T load_value(const container_t &data, const size_t index) {
    return data[index];
}
template <typename T, typename container_t>
CUDA_GLOBAL_METHOD inline void store_value(
    container_t &data, const size_t index, const T& value) {
    data[index] = value;
}

boost::container::vector<bool> create_masks();

#pragma GCC push_options
#pragma GCC optimize("unroll-loops")

template <typename double_t>
CUDA_GLOBAL_METHOD inline double_t inner_flux_loop(const double omega, const size_t nf_,
    const double A_, const double B_, const double_t* __restrict__ UR,
    const double_t* __restrict__ UL, double_t* __restrict__ this_flux,
    const double_t* __restrict__ x, const double_t* __restrict__ vg, double_t& ap, double_t& am,
    const size_t dim, const size_t d, const double dx, const double fgamma,
    const double de_switch_1) {
    double_t amr, apr, aml, apl;
    double_t this_ap, this_am;    // tmps
    double_t p, v, v0, c;

    auto rho = UR[rho_i];
    auto rhoinv = (1.) / rho;
    double_t pdeg = static_cast<double_t>(0.0), edeg = static_cast<double_t>(0.0),
     dpdeg_drho = static_cast<double_t>(0.0);

    // all workitems choose the same path
    if (A_ != 0.0) {
        const auto Binv = 1.0 / B_;
        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);
        const auto x_sqr = x * x;
        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);
        const auto x_pow_5 = x_sqr * x_sqr * x;
        const double_t hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);

        const double_t edeg_tmp1 = rho * hdeg - pdeg;
        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;
        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asinh_wrapper(x));
        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;
        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);
        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);

        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;
    }
    double_t ek = 0.0;
    for (int dim = 0; dim < NDIM; dim++) {
        ek += UR[sx_i + dim] * UR[sx_i + dim] * rhoinv * 0.5;
    }
    const auto ein1_tmp2 = UR[egas_i] - ek - edeg;
    const auto ein1_mask = (ein1_tmp2 < (de_switch_1 * UR[egas_i]));
    double_t ein;
    if (!skippable(ein1_mask)) {
        const auto ein1_tmp1 = pow_wrapper(UR[tau_i], fgamma);
        select_wrapper(ein, ein1_mask, ein1_tmp1, ein1_tmp2);
    } else {
        ein = ein1_tmp2;
    }
    double_t dp_drho = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;
    double_t dp_deps = (fgamma - 1.0) * rho;
    v0 = UR[sx_i + dim] * rhoinv;
    p = (fgamma - 1.0) * ein + pdeg;
    c = sqrt_wrapper(p * rhoinv * rhoinv * dp_deps + dp_drho);
    v = v0 - vg[dim];
    amr = v - c;
    apr = v + c;

    rho = UL[rho_i];
    rhoinv = (1.) / rho;
    pdeg = static_cast<double_t>(0.0);
    edeg = static_cast<double_t>(0.0);
    dpdeg_drho = static_cast<double_t>(0.0);

    // all workitems choose the same path
    if (A_ != 0.0) {
        const auto Binv = 1.0 / B_;
        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);
        const auto x_sqr = x * x;
        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);
        const auto x_pow_5 = x_sqr * x_sqr * x;
        const double_t hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);
        const double_t edeg_tmp1 = rho * hdeg - pdeg;
        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;
        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asinh_wrapper(x));
        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;
        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);
        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);
        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;
    }
    ek = 0.0;
    for (int dim = 0; dim < NDIM; dim++) {
        ek += UL[sx_i + dim] * UL[sx_i + dim] * rhoinv * 0.5;
    }
    const auto ein2_tmp2 = UL[egas_i] - ek - edeg;
    const auto ein2_mask = (ein2_tmp2 < (de_switch_1 * UL[egas_i]));
    if (!skippable(ein2_mask)) {
        const auto ein2_tmp1 = pow_wrapper(UL[tau_i], fgamma);
        select_wrapper(ein, ein2_mask, ein2_tmp1, ein2_tmp2);
    } else {
        ein = ein2_tmp2;
    }
    const auto dp_drho2 = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;
    const auto dp_deps2 = (fgamma - 1.0) * rho;
    const auto v02 = UL[sx_i + dim] * rhoinv;
    const auto p2 = (fgamma - 1.0) * ein + pdeg;
    const auto c2 = sqrt_wrapper(p2 * rhoinv * rhoinv * dp_deps2 + dp_drho2);
    const auto v2 = v02 - vg[dim];
    aml = v2 - c2;
    apl = v2 + c2;

    this_ap = max_wrapper(max_wrapper(apr, apl), double_t(0.0));
    this_am = min_wrapper(min_wrapper(amr, aml), double_t(0.0));
    const auto amp_mask = (this_ap - this_am == 0.0);
    for (int f = 0; f < nf_; f++) {
        double_t fr = v * UR[f];
        double_t fl = v2 * UL[f];

        if (f == sx_i + dim) {
            fr += p;
            fl += p2;
        } else if (f == egas_i) {
            fr += v0 * p;
            fl += v02 * p2;
        }
        if (dim == 0) {
            // levi_civita 1 2 0
            if (f == lx_i + 1) {
                fr += x[2] * p;
                fl += x[2] * p2;
            } else if (f == lx_i + 2) {
                // levi_civita 2 1 0
                fr -= x[1] * p;
                fl -= x[1] * p2;
            }
        } else if (dim == 1) {
            // levi_civita 0 2 1
            if (f == lx_i + 0) {
                fr -= x[2] * p;
                fl -= x[2] * p2;
                // 2 0 1
            } else if (f == lx_i + 2) {
                fr += x[0] * p;
                fl += x[0] * p2;
            }
        } else if (dim == 2) {
            if (f == lx_i) {
                // levi_civita 0 1 2
                fr += x[1] * p;
                fl += x[1] * p2;
                // 1 0 2
            } else if (f == lx_i + 1) {
                fr -= x[0] * p;
                fl -= x[0] * p2;
            }
        }

        if (!skippable(amp_mask)) {
            const double_t flux_tmp1 =
                (this_ap * fl - this_am * fr + this_ap * this_am * (UR[f] - UL[f])) /
                (this_ap - this_am);
            const double_t flux_tmp2 = (fl + fr) / 2.0;
            select_wrapper(this_flux[f], amp_mask, flux_tmp2, flux_tmp1);
        } else {
            this_flux[f] = (this_ap * fl - this_am * fr + this_ap * this_am * (UR[f] - UL[f])) /
                (this_ap - this_am);
        }
    }

    am = min_wrapper(am, this_am);
    ap = max_wrapper(ap, this_ap);
    return max_wrapper(ap, double_t(-am));
}

/*template <typename double_t>
CUDA_GLOBAL_METHOD inline double_t inner_flux_loop2(const double omega, const size_t nf_,
    const double A_, const double B_, const double* __restrict__ U,
    double_t* __restrict__ this_flux, const double_t* __restrict__ x,
    const double_t* __restrict__ vg, double_t& ap, double_t& am, const size_t dim, const size_t d,
    const double dx, const double fgamma, const double de_switch_1, const size_t index,
    const size_t flipped_index, const size_t face_offset) {
    double_t amr, apr, aml, apl;
    double_t this_ap, this_am;    // tmps

    auto rho = load_value<double_t>(U, rho_i * face_offset + index);
    auto rhoinv = (1.) / rho;
    double_t hdeg = static_cast<double_t>(0.0), pdeg = static_cast<double_t>(0.0),
             edeg = static_cast<double_t>(0.0), dpdeg_drho = static_cast<double_t>(0.0);

    // all workitems choose the same path
    if (A_ != 0.0) {
        const auto Binv = 1.0 / B_;
        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);
        const auto x_sqr = x * x;
        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);
        const auto x_pow_5 = x_sqr * x_sqr * x;
        hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);

        const double_t edeg_tmp1 = rho * hdeg - pdeg;
        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;
        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asin_wrapper(x));
        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;
        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);
        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);

        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;
    }
    double_t ek = 0.0;
    double_t ein;
    for (int dim = 0; dim < NDIM; dim++) {
        ek += load_value<double_t>(U, (sx_i + dim) * face_offset + index) *
            load_value<double_t>(U, (sx_i + dim) * face_offset + index) * rhoinv * 0.5;
    }
    const auto ein1_tmp2 = load_value<double_t>(U, egas_i * face_offset + index) - ek - edeg;
    const auto ein1_mask =
        (ein1_tmp2 < (de_switch_1 * load_value<double_t>(U, egas_i * face_offset + index)));
    if (!skippable(ein1_mask)) {
        const auto ein1_tmp1 =
            pow_wrapper(load_value<double_t>(U, tau_i * face_offset + index), fgamma);
        select_wrapper(ein, ein1_mask, ein1_tmp1, ein1_tmp2);
    } else {
        ein = ein1_tmp2;
    }
    const auto dp_drho = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;
    const auto dp_deps = (fgamma - 1.0) * rho;
    const auto v0 = load_value<double_t>(U, (sx_i + dim) * face_offset + index) * rhoinv;
    const auto p = (fgamma - 1.0) * ein + pdeg;
    const auto c = sqrt_wrapper(p * rhoinv * rhoinv * dp_deps + dp_drho);
    const auto v = v0 - vg[dim];
    amr = v - c;
    apr = v + c;

    rho = load_value<double_t>(U, rho_i * face_offset + flipped_index);
    rhoinv = (1.) / rho;
    hdeg = static_cast<double_t>(0.0);
    pdeg = static_cast<double_t>(0.0);
    edeg = static_cast<double_t>(0.0);
    dpdeg_drho = static_cast<double_t>(0.0);

    // all workitems choose the same path
    if (A_ != 0.0) {
        const auto Binv = 1.0 / B_;
        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);
        const auto x_sqr = x * x;
        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);
        const auto x_pow_5 = x_sqr * x_sqr * x;
        hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);
        const double_t edeg_tmp1 = rho * hdeg - pdeg;
        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;
        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asin_wrapper(x));
        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;
        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);
        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);
        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;
    }
    ek = 0.0;
    for (int dim = 0; dim < NDIM; dim++) {
        ek += load_value<double_t>(U, (sx_i + dim) * face_offset + flipped_index) *
            load_value<double_t>(U, (sx_i + dim) * face_offset + flipped_index) * rhoinv * 0.5;
    }
    const auto ein2_tmp2 =
        load_value<double_t>(U, egas_i * face_offset + flipped_index) - ek - edeg;
    const auto ein2_mask =
        (ein2_tmp2 < (de_switch_1 * load_value<double_t>(U, egas_i * face_offset + flipped_index)));
    if (!skippable(ein2_mask)) {
        const auto ein2_tmp1 =
            pow_wrapper(load_value<double_t>(U, tau_i * face_offset + flipped_index), fgamma);
        select_wrapper(ein, ein2_mask, ein2_tmp1, ein2_tmp2);
    } else {
        ein = ein2_tmp2;
    }
    const auto dp_drho2 = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;
    const auto dp_deps2 = (fgamma - 1.0) * rho;
    const auto v02 = load_value<double_t>(U, (sx_i + dim) * face_offset + flipped_index) * rhoinv;
    const auto p2 = (fgamma - 1.0) * ein + pdeg;
    const auto c2 = sqrt_wrapper(p2 * rhoinv * rhoinv * dp_deps2 + dp_drho2);
    const auto v2 = v02 - vg[dim];
    aml = v2 - c2;
    apl = v2 + c2;

    this_ap = max_wrapper(max_wrapper(apr, apl), double_t(0.0));
    this_am = min_wrapper(min_wrapper(amr, aml), double_t(0.0));
    const auto amp_mask = (this_ap - this_am == 0.0);
    for (int f = 0; f < nf_; f++) {
        double_t fr = v * load_value<double_t>(U, f * face_offset + index);
        double_t fl = v2 * load_value<double_t>(U, f * face_offset + flipped_index);

        if (f == sx_i + dim) {
            fr += p;
            fl += p2;
        } else if (f == egas_i) {
            fr += v0 * p;
            fl += v02 * p2;
        }
        if (dim == 0) {
            // levi_civita 1 2 0
            if (f == lx_i + 1) {
                fr += x[2] * p;
                fl += x[2] * p2;
            } else if (f == lx_i + 2) {
                // levi_civita 2 1 0
                fr -= x[1] * p;
                fl -= x[1] * p2;
            }
        } else if (dim == 1) {
            // levi_civita 0 2 1
            if (f == lx_i + 0) {
                fr -= x[2] * p;
                fl -= x[2] * p2;
                // 2 0 1
            } else if (f == lx_i + 2) {
                fr += x[0] * p;
                fl += x[0] * p2;
            }
        } else if (dim == 2) {
            if (f == lx_i) {
                // levi_civita 0 1 2
                fr += x[1] * p;
                fl += x[1] * p2;
                // 1 0 2
            } else if (f == lx_i + 1) {
                fr -= x[0] * p;
                fl -= x[0] * p2;
            }
        }

        if (!skippable(amp_mask)) {
            const double_t flux_tmp1 =
                (this_ap * fl - this_am * fr +
                    this_ap * this_am *
                        (load_value<double_t>(U, f * face_offset + index) -
                            load_value<double_t>(U, f * face_offset + flipped_index))) /
                (this_ap - this_am);
            const double_t flux_tmp2 = (fl + fr) / 2.0;
            select_wrapper(this_flux[f], amp_mask, flux_tmp2, flux_tmp1);
        } else {
            this_flux[f] = (this_ap * fl - this_am * fr +
                               this_ap * this_am *
                                   (load_value<double_t>(U, f * face_offset + index) -
                                       load_value<double_t>(U, f * face_offset + flipped_index))) /
                (this_ap - this_am);
        }
    }

    am = min_wrapper(am, this_am);
    ap = max_wrapper(ap, this_ap);
    return max_wrapper(ap, double_t(-am));
}*/

template <typename Alloc>
void convert_q_structure(const hydro::recon_type<NDIM>& Q, std::vector<double, Alloc>& combined_q) {
    auto it = combined_q.begin();
    auto nf_ = physics<NDIM>::nf_;
    for (auto field = 0; field < nf_; field++) {
        for (auto d = 0; d < 27; d++) {
            auto start_offset = 2 * 14 * 14 + 2 * 14 + 2;
            for (auto ix = 2; ix < 2 + INX + 2; ix++) {
                for (auto iy = 2; iy < 2 + INX + 2; iy++) {
                    it = std::copy(Q[field][d].begin() + start_offset,
                        Q[field][d].begin() + start_offset + 10, it);
                    start_offset += 14;
                }
                start_offset += (2 + 2) * 14;
            }
        }
    }
}

template <typename Alloc>
void compare_q_structure(const hydro::recon_type<NDIM>& Q, std::vector<double, Alloc>& combined_q) {
    auto it = combined_q.begin();
    auto nf_ = physics<NDIM>::nf_;
    for (auto field = 0; field < nf_; field++) {
        bool correct = true;
        for (auto d = 0; d < 27; d++) {
            auto start_offset = 2 * 14 * 14 + 2 * 14;
            for (auto ix = 2; ix < 2 + INX + 2; ix++) {
                for (auto iy = 2; iy < 2 + INX + 2; iy++) {
                    for (auto line_element = 0; line_element < 10; line_element++) {
                        if (std::abs(Q[field][d][start_offset + line_element + 2] -
                                *(it + line_element)) > 1e-7) {
                            std::cout << "Orig: " << Q[field][d][start_offset + line_element + 2]
                                      << " vs: " << *(it + line_element) << std::endl;
                            std::cout << "Found error at field " << field << " with d " << d
                                      << " and grid element " << ix << "/" << iy << "/"
                                      << line_element + 2 << std::endl;
                            for (auto line_element = 0; line_element < 10; line_element++) {
                                std::cout << Q[field][d][start_offset + line_element + 2] << " ";
                            }
                            std::cout << std::endl;
                            for (auto line_element = 0; line_element < 10; line_element++) {
                                std::cout << *(it + line_element) << " ";
                            }
                            std::cout << std::endl;
                            correct = false;
                        }
                    }
                    start_offset += 14;
                    it += 10;
                }
                start_offset += (2 + 2) * 14;
            }
        }
        if (!correct) {
            std::cout << " field " << field << " is incorrect!" << std::endl;
            std::cin.get();
        }
    }
}

#pragma GCC pop_options


text:
// Copyright 2020 Olga Molchun olgamolchun5@gmail.com

#include <ftp_analyzer.hpp>
// STL headers
#include <iostream>
// boost headers
#include <boost/program_options.hpp>

int main(int argc, char* argv[]) {
    boost::program_options::options_description desc("Allowed optoins");
    desc.add_options()
        ("help", "print help message and exit")
        ("path_to_ftp", boost::program_options::value<std::string>(),
         "path to FTP directory which will be analyzed");

    boost::program_options::variables_map vm;
    boost::program_options::store(
        boost::program_options::parse_command_line(argc, argv, desc), vm);
    boost::program_options::notify(vm);
    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }
    if (!vm.count("path_to_ftp")) {
        std::cout << desc << std::endl;
        return 1;
    }
    try {
        FtpAnalyzer analyzer(vm["path_to_ftp"].as<std::string>());
        auto stats = analyzer.analyze(std::cout);

        for (const auto &record : stats) {
            std::cout << "broker: " << record.first
                      << " account: " << record.second.account
                      << " files: " << record.second.total
                      << " lastdate: " << record.second.lastDate
                      << std::endl;
        }
    } catch (const  boost::filesystem::filesystem_error& err) {
        std::cerr << "filesystem error: " << err.what() << std::endl;
        return 2;
    }
    return 0;
}


text:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <boost/filesystem.hpp>
#include "derivatives.h"
#include "labelconnect.hpp"
#include "region.h"
#include "link.h"
#include "utils.hpp"
#include <iostream>
#include <iomanip>
#include "strands.h"
#include <cmath>
#include "version.h"
#include <exception>
#include <time.h>

#include <chrono>

string NowToString()
{
	chrono::system_clock::time_point p = chrono::system_clock::now();
	time_t t = chrono::system_clock::to_time_t(p);
//	char str[26];
//	ctime_s(str, sizeof str, &t);
	return ctime(&t);
}

using namespace cv;
using namespace std;
using namespace boost;
namespace fs = boost::filesystem;
using namespace stegers;
using namespace timer;

void strands::run(){

	assert(labelConnect::test());
	assert(region::test());

	auto polarity = strands::line_polarity::light;
	float sigma = 1.5;
	float low_thr = 1.0;
	float high_thr = 6.0;

	std::string version_string(VERSION);
	version_string = NowToString() + "build " + version_string + "\nimage file: " + m_input_file.stem().string();
	auto filename = m_input_file.stem();
	filename = "histogram_output_" + filename.string() + ".csv";
	filename = m_output_dir / filename;

	Mat image = imread(m_input_file.string(), cv::IMREAD_GRAYSCALE);

	Mat display;
	string screen("display");
	if (show() || graphics()) {
		std::vector<Mat> triple{ image, image, image };
		merge(triple, display);
	}
	// Show our image inside a window.
	if (show())
		namedWindow(screen.c_str(), cv::WINDOW_GUI_EXPANDED);

	std::map<int32_t, int32_t> lm;

	try {

		// Convert to flat vector of doubles
		// @todo have cv::Mat api
		cv::Mat dst;
		image.convertTo(dst, CV_64F);
		std::vector<double> dimg(size_t(image.rows * image.cols));
		assert(dst.isContinuous());
		std::memcpy(dimg.data(), dst.ptr(0), image.total() * sizeof(double));
		convol conv(image.cols, image.rows);
		conv.debug(debug());

		std::vector<std::vector<float>> out;
		conv.get_all_derivatives(dimg, sigma, out);
		std::vector<int32_t> ismax;
		std::vector<std::vector<double>> line_out;
		class link lnk(image.cols, image.rows, 1.5, strands::line_polarity::light);
		lnk.debug(debug());
		lnk.compute_line_points(out, ismax, line_out, low_thr, high_thr);
		const cv::Mat& esp = lnk.eSpace();
		lnk.compute_contours(ismax, line_out[0], line_out[5], line_out[6], line_out[1], line_out[2], line_out[3], line_out[5]);

		float length_total = 0;
		for (auto cc = 0; cc < lnk.results().size(); cc++) {
			const contour& ct = lnk.results()[cc];
			auto length = ct.compute_length();
			int ilength = (int)length;
			auto miter = lm.find(ilength);
			if (miter == lm.end())
				lm[ilength] = 0;
			auto current = lm[ilength];
			lm[ilength] = current + 1;
			length_total += length;
		}

		float avg_node_count = lnk.results().empty() ? 0 : length_total / float(lnk.results().size());
		std::string output = "AvgLength: " + std::to_string(avg_node_count);
		std::string output2 = "Count: " + std::to_string(lnk.results().size());

		if (debug()) {
			std::cout << output << std::endl;
			std::cout << output2 << std::endl;
		}

		string total_string = version_string + "\n" + output + "\n" + output2 + "\n";
		if (lnk.is_crowded())
			total_string = total_string + "is Crowded \n";

		save_csv(lm, filename.string(), total_string);

		if (show() || graphics()) {
			int factor = 8;
			for (auto cc = 0; cc < lnk.results().size(); cc++) {
				const contour& ct = lnk.results()[cc];
				std::vector<Point> pts;
				std::vector<float>::const_iterator rowItr = ct.row.begin();
				std::vector<float>::const_iterator colItr = ct.col.begin();
				for (auto pp = 0; pp < ct.row.size(); pp++, rowItr++, colItr++) {
					pts.emplace_back(static_cast<int>(*colItr * factor), static_cast<int>(*rowItr * factor));
				}
				polylines(display, pts, false, Scalar(0, 0, 255), 2, LINE_AA, int(std::log2(factor)));
			}

			if (lnk.is_crowded())
				putText(display, "Is Crowded ", Point(1000, 900), FONT_HERSHEY_SIMPLEX, 3.0, Scalar(0, 255, 0), 2);

			std::string output = " Average Length " + std::to_string(avg_node_count);
			putText(display, output.c_str(), Point(1000, 1000), FONT_HERSHEY_SIMPLEX, 3.0, Scalar(0, 255, 0), 2);
			std::string output2 = " Count " + std::to_string(lnk.results().size());
			putText(display, output2.c_str(), Point(1000, 1200), FONT_HERSHEY_SIMPLEX, 3.0, Scalar(0, 255, 0), 2);

			int start = 100;
			auto it = lm.begin();
			while (it != lm.end()) {
				std::string hout = "histogram [" + std::to_string(it->first) + "] = " + std::to_string(it->second);
				putText(display, hout.c_str(), Point(500, start), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(255, 0, 0), 2);
				start += 30;
				it++;
			}

			if (show()) {
				imshow(screen.c_str(), display);
				// Wait for any keystroke in the window
				waitKey(0);
			}

			if (graphics()) {
				auto filename = m_input_file.filename();
				filename = "output_" + filename.string();
				filename = m_output_dir / filename;
				cv::imwrite(filename.string(), display);
			}

		}

	}

	catch (std::exception& e) {
		version_string = version_string + " error " + e.what();
		lm.clear();
		save_csv(lm, filename.string(), version_string);
	}

}


text:
/**
 * Copyright (c) 2009 Carnegie Mellon University.
 *     All rights reserved.
 *
 *  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.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */

#include <boost/unordered_map.hpp>
#include <boost/preprocessor.hpp>
#include "gl_emx_graphtypes.hpp"
#include "update_function_generator.hpp"
//#include "update_function_array.hpp"
/*********************************************************************
 * The __matlab_config.hpp defines an array __UPDATE_FUNCTIONS__
 * which lists all the matlab update functions available.
 * However, I need to generate my own graphlab update functions
 * which call the matlab update functions. So, for each matlab update
 * function, I generate a graphlab update function with the same name but
 * prefixed with __gl__
 *********************************************************************/

// Some useful macros to extract elements from the __UPDATE_FUNCTIONS__ array
#define GET_UPDATE_FUNCTION_N(N) BOOST_PP_ARRAY_ELEM(N, __UPDATE_FUNCTIONS__)
#define GET_NUM_UPDATE_FUNCTIONS BOOST_PP_ARRAY_SIZE(__UPDATE_FUNCTIONS__)
#define GET_UPDATE_FUNCTION_NAME_N(N) BOOST_PP_STRINGIZE(GET_UPDATE_FUNCTION_N(N))
// To get the GraphLab versions of the update functions
#define GET_GL_UPDATE_FUNCTION_N(N) BOOST_PP_CAT( __gl__ , BOOST_PP_ARRAY_ELEM(N, __UPDATE_FUNCTIONS__))
#define GET_GL_UPDATE_FUNCTION_NAME_N(N) BOOST_PP_STRINGIZE(GET_GL_UPDATE_FUNCTION_N(N))

#define GEN_UPDATE_FUNCTION(Z,N,_) void GET_GL_UPDATE_FUNCTION_N(N)     \
                                  (gl_types::iscope& scope,               \
                                   gl_types::icallback& scheduler) {  \
  exec_update_function< GET_UPDATE_FUNCTION_N(N) >(scope,scheduler); \
}

BOOST_PP_REPEAT(GET_NUM_UPDATE_FUNCTIONS, GEN_UPDATE_FUNCTION, _)

/*********************************************************************
 * Registers all the graphlab update functions created in a map
 * so I get a string->update_function mapping.
 *********************************************************************/
#define INSERT_ELEM_INTO_MAP(Z,N, _) \
  update_function_map[GET_GL_UPDATE_FUNCTION_NAME_N(N)] = GET_GL_UPDATE_FUNCTION_N(N); \
  std::cout << "Registering update function: " << GET_GL_UPDATE_FUNCTION_NAME_N(N) << std::endl;
update_function_map_type update_function_map;

void register_all_matlab_update_functions() {
  BOOST_PP_REPEAT(GET_NUM_UPDATE_FUNCTIONS, INSERT_ELEM_INTO_MAP, _)
}

max_stars_repo_name: iivek/graphlab-cmu-mirror

max_issues_repo_name: iivek/graphlab-cmu-mirror

max_forks_repo_name: iivek/graphlab-cmu-mirror


text:
// Test for boost/core/bit.hpp (bit_ceil)
//
// Copyright 2020 Peter Dimov
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt

#include <boost/core/bit.hpp>
#include <boost/core/lightweight_test.hpp>
#include <boost/cstdint.hpp>
#include <cstring>

int main()
{
    boost::uint64_t v = static_cast<boost::uint64_t>( 0x0102030405060708ull );

    if( boost::core::endian::native == boost::core::endian::little )
    {
        unsigned char w[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
        BOOST_TEST( std::memcmp( &v, w, 8 ) == 0 );
    }
    else if( boost::core::endian::native == boost::core::endian::big )
    {
        unsigned char w[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
        BOOST_TEST( std::memcmp( &v, w, 8 ) == 0 );
    }
    else
    {
        unsigned char w1[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
        BOOST_TEST( std::memcmp( &v, w1, 8 ) != 0 );

        unsigned char w2[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
        BOOST_TEST( std::memcmp( &v, w2, 8 ) != 0 );
    }

    return boost::report_errors();
}

max_stars_repo_name: anarthal/boost-unix-mirror

max_issues_repo_name: anarthal/boost-unix-mirror


text:
/*
	This file is part of solidity.

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

	solidity is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <libyul/optimiser/ControlFlowSimplifier.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/TypeInfo.h>
#include <libyul/AsmData.h>
#include <libyul/Utilities.h>
#include <libyul/Dialect.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Visitor.h>

#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/algorithm/cxx11/any_of.hpp>

using namespace std;
using namespace solidity;
using namespace solidity::util;
using namespace solidity::yul;

using OptionalStatements = std::optional<vector<Statement>>;

namespace
{

ExpressionStatement makeDiscardCall(
	langutil::SourceLocation const& _location,
	BuiltinFunction const& _discardFunction,
	Expression&& _expression
)
{
	return {_location, FunctionCall{
		_location,
		Identifier{_location, _discardFunction.name},
		{std::move(_expression)}
	}};
}

void removeEmptyDefaultFromSwitch(Switch& _switchStmt)
{
	boost::remove_erase_if(
		_switchStmt.cases,
		[](Case const& _case) { return !_case.value && _case.body.statements.empty(); }
	);
}

void removeEmptyCasesFromSwitch(Switch& _switchStmt)
{
	bool hasDefault = boost::algorithm::any_of(
		_switchStmt.cases,
		[](Case const& _case) { return !_case.value; }
	);

	if (hasDefault)
		return;

	boost::remove_erase_if(
		_switchStmt.cases,
		[](Case const& _case) { return _case.body.statements.empty(); }
	);
}

}

void ControlFlowSimplifier::run(OptimiserStepContext& _context, Block& _ast)
{
	TypeInfo typeInfo(_context.dialect, _ast);
	ControlFlowSimplifier{_context.dialect, typeInfo}(_ast);
}

void ControlFlowSimplifier::operator()(Block& _block)
{
	simplify(_block.statements);
}

void ControlFlowSimplifier::operator()(FunctionDefinition& _funDef)
{
	ASTModifier::operator()(_funDef);
	if (!_funDef.body.statements.empty() && holds_alternative<Leave>(_funDef.body.statements.back()))
		_funDef.body.statements.pop_back();
}

void ControlFlowSimplifier::visit(Statement& _st)
{
	if (holds_alternative<ForLoop>(_st))
	{
		ForLoop& forLoop = std::get<ForLoop>(_st);
		yulAssert(forLoop.pre.statements.empty(), "");

		size_t outerBreak = m_numBreakStatements;
		size_t outerContinue = m_numContinueStatements;
		m_numBreakStatements = 0;
		m_numContinueStatements = 0;

		ASTModifier::visit(_st);

		if (!forLoop.body.statements.empty())
		{
			bool isTerminating = false;
			TerminationFinder::ControlFlow controlFlow = TerminationFinder{m_dialect}.controlFlowKind(forLoop.body.statements.back());
			if (controlFlow == TerminationFinder::ControlFlow::Break)
			{
				isTerminating = true;
				--m_numBreakStatements;
			}
			else if (
				controlFlow == TerminationFinder::ControlFlow::Terminate ||
				controlFlow == TerminationFinder::ControlFlow::Leave
			)
				isTerminating = true;

			if (isTerminating && m_numContinueStatements == 0 && m_numBreakStatements == 0)
			{
				If replacement{forLoop.location, std::move(forLoop.condition), std::move(forLoop.body)};
				if (controlFlow == TerminationFinder::ControlFlow::Break)
					replacement.body.statements.resize(replacement.body.statements.size() - 1);
				_st = std::move(replacement);
			}
		}

		m_numBreakStatements = outerBreak;
		m_numContinueStatements = outerContinue;
	}
	else
		ASTModifier::visit(_st);
}

void ControlFlowSimplifier::simplify(std::vector<yul::Statement>& _statements)
{
	GenericVisitor visitor{
		VisitorFallback<OptionalStatements>{},
		[&](If& _ifStmt) -> OptionalStatements {
			if (_ifStmt.body.statements.empty() && m_dialect.discardFunction(m_dialect.boolType))
			{
				OptionalStatements s = vector<Statement>{};
				s->emplace_back(makeDiscardCall(
					_ifStmt.location,
					*m_dialect.discardFunction(m_dialect.boolType),
					std::move(*_ifStmt.condition)
				));
				return s;
			}
			return {};
		},
		[&](Switch& _switchStmt) -> OptionalStatements {
			removeEmptyDefaultFromSwitch(_switchStmt);
			removeEmptyCasesFromSwitch(_switchStmt);

			if (_switchStmt.cases.empty())
				return reduceNoCaseSwitch(_switchStmt);
			else if (_switchStmt.cases.size() == 1)
				return reduceSingleCaseSwitch(_switchStmt);

			return {};
		}
	};
	iterateReplacing(
		_statements,
		[&](Statement& _stmt) -> OptionalStatements
		{
			OptionalStatements result = std::visit(visitor, _stmt);
			if (result)
				simplify(*result);
			else
				visit(_stmt);
			return result;
		}
	);
}

OptionalStatements ControlFlowSimplifier::reduceNoCaseSwitch(Switch& _switchStmt) const
{
	yulAssert(_switchStmt.cases.empty(), "Expected no case!");
	BuiltinFunction const* discardFunction =
		m_dialect.discardFunction(m_typeInfo.typeOf(*_switchStmt.expression));
	if (!discardFunction)
		return {};

	auto loc = locationOf(*_switchStmt.expression);

	return make_vector<Statement>(makeDiscardCall(
		loc,
		*discardFunction,
		std::move(*_switchStmt.expression)
	));
}

OptionalStatements ControlFlowSimplifier::reduceSingleCaseSwitch(Switch& _switchStmt) const
{
	yulAssert(_switchStmt.cases.size() == 1, "Expected only one case!");

	auto& switchCase = _switchStmt.cases.front();
	auto loc = locationOf(*_switchStmt.expression);
	YulString type = m_typeInfo.typeOf(*_switchStmt.expression);
	if (switchCase.value)
	{
		if (!m_dialect.equalityFunction(type))
			return {};
		return make_vector<Statement>(If{
			std::move(_switchStmt.location),
			make_unique<Expression>(FunctionCall{
				loc,
				Identifier{loc, m_dialect.equalityFunction(type)->name},
				{std::move(*switchCase.value), std::move(*_switchStmt.expression)}
			}),
			std::move(switchCase.body)
		});
	}
	else
	{
		if (!m_dialect.discardFunction(type))
			return {};

		return make_vector<Statement>(
			makeDiscardCall(
				loc,
				*m_dialect.discardFunction(type),
				std::move(*_switchStmt.expression)
			),
			std::move(switchCase.body)
		);
	}
}

max_stars_repo_name: MrChico/solidity

max_issues_repo_name: MrChico/solidity

max_forks_repo_name: MrChico/solidity


text: #include <boost/parameter/keyword.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef SERIALIZATION_TEST_TYPES_H_
#define SERIALIZATION_TEST_TYPES_H_

#include <boost/fusion/include/define_struct.hpp>
#include <string>
#include <vector>
#include <optional.hpp>

namespace SerializationTestTypes {

using version_t = std::integral_constant<uint16_t, 0xf001>;

enum class msg_type_t : uint16_t { A, B, C };

struct collection_t {
    std::vector<std::string> value;
};

using opt_fields = detail::optional_field_set<uint16_t>;
using opt_int32_field = detail::optional_field<int32_t, 0>;
using opt_msg_type_t = detail::optional_field<msg_type_t, 1>;
using opt_string_t = detail::optional_field<std::string, 2>;
} /* SerializationTestTypes */

BOOST_FUSION_DEFINE_STRUCT(
    (SerializationTestTypes), header_t,
    (SerializationTestTypes::version_t,
     version)(uint32_t, seq_num)(SerializationTestTypes::msg_type_t, msg_type))

BOOST_FUSION_ADAPT_STRUCT(SerializationTestTypes::collection_t,
                          (std::vector<std::string>, value))

BOOST_FUSION_DEFINE_STRUCT((SerializationTestTypes), some_message_t,
                           (std::string,
                            id)(SerializationTestTypes::collection_t,
                                properties))
BOOST_FUSION_DEFINE_STRUCT(
    (SerializationTestTypes), msg_with_opt_fields_t,
    (SerializationTestTypes::collection_t, properties)
    (SerializationTestTypes::opt_fields, opt_mask)
    (SerializationTestTypes::opt_int32_field, number)
    (SerializationTestTypes::opt_string_t, description))

#endif /* ifndef SERIALIZATION_TEST_TYPES_H_ */

max_stars_repo_name: semirpuskarevic/serialization

max_issues_repo_name: semirpuskarevic/serialization

max_forks_repo_name: semirpuskarevic/serialization


text:
#include "utility/reporter/mpi.h"

#include <deal.II/base/conditional_ostream.h>
#include <gtest/gtest.h>

#include "utility/reporter/colors.h"
#include "test_helpers/gmock_wrapper.h"

namespace  {

using namespace bart;

class UtilityReporterMpiTest : public ::testing::Test {
 protected:
  std::ostringstream string_stream;
  std::unique_ptr<utility::reporter::Mpi> test_reporter_;
  void SetUp() override;
};

void UtilityReporterMpiTest::SetUp() {
  auto pout_ptr = std::make_unique<dealii::ConditionalOStream>(string_stream, true);
  test_reporter_ = std::make_unique<utility::reporter::Mpi>(std::move(pout_ptr));
}

/* Verifies that the reporter sends the string to the ostream */
TEST_F(UtilityReporterMpiTest, StringReport) {
  std::string to_report = "report me";
  test_reporter_->Report(to_report);
  EXPECT_EQ(string_stream.str(), to_report);
}

TEST_F(UtilityReporterMpiTest, InstreamOperator) {
  std::string to_report = "report me";
  *test_reporter_ << to_report;
  EXPECT_EQ(string_stream.str(), to_report);
}

TEST_F(UtilityReporterMpiTest, ColoredStringReport) {
  using Color = utility::reporter::Color;
  std::unordered_map<Color, std::string> color_string{
      {Color::Reset, "\033[0m"},
      {Color::Red,   "\033[31m"},
      {Color::Green, "\033[32m"},
      {Color::Blue,  "\033[34m"},
  };

  for (auto color_pair : color_string) {
    string_stream.str("");
    std::string to_report = "report me";
    std::string colored_report = color_pair.second + to_report + color_string.at(Color::Reset);
    test_reporter_->Report(to_report, color_pair.first);
    EXPECT_EQ(string_stream.str(), colored_report);
  }

}

TEST_F(UtilityReporterMpiTest, InstreamOperatorColor) {
  using Color = utility::reporter::Color;
  std::unordered_map<Color, std::string> color_string{
      {Color::Reset, "\033[0m"},
      {Color::Red,   "\033[31m"},
      {Color::Green, "\033[32m"},
      {Color::Blue,  "\033[34m"},
  };

  for (auto color_pair : color_string) {
    string_stream.str("");
    std::string to_report = "report me";
    std::string colored_report = color_pair.second + to_report + color_string.at(Color::Reset);
    *test_reporter_ << color_pair.second << to_report << Color::Reset;
    EXPECT_EQ(string_stream.str(), colored_report);
  }

}

} // namespace

ext: cc

max_stars_repo_name: narang-amit/BART

max_issues_repo_name: narang-amit/BART

max_forks_repo_name: narang-amit/BART


text:
/*

Copyright (c) 2011, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#include "boost_python.hpp"
#include <libtorrent/error_code.hpp>
#include <libtorrent/bdecode.hpp>
#include <libtorrent/upnp.hpp>
#include <libtorrent/socks5_stream.hpp>

namespace boost
{
	// this fixe mysterious link error on msvc
	template <>
	inline boost::system::error_category const volatile*
	get_pointer(class boost::system::error_category const volatile* p)
	{
		return p;
	}
}

#include <boost/asio/error.hpp>
#if TORRENT_USE_SSL
#include <boost/asio/ssl/error.hpp>
#include <libtorrent/aux_/ssl.hpp>
#endif
#if TORRENT_USE_I2P
#include <libtorrent/i2p_stream.hpp>
#endif

using namespace boost::python;
using namespace lt;
using boost::system::error_category;

namespace {

	struct ec_pickle_suite : boost::python::pickle_suite
	{
		static boost::python::tuple
		getinitargs(error_code const&)
		{
			return boost::python::tuple();
		}

		static boost::python::tuple
		getstate(error_code const& ec)
		{
			return boost::python::make_tuple(ec.value(), ec.category().name());
		}

		static void
		setstate(error_code& ec, boost::python::tuple state)
		{
			using namespace boost::python;
			if (len(state) != 2)
			{
				PyErr_SetObject(PyExc_ValueError,
					("expected 2-item tuple in call to __setstate__; got %s"
					% state).ptr());
				throw_error_already_set();
			}

			int const value = extract<int>(state[0]);
			std::string const category = extract<std::string>(state[1]);
			if (category == "system")
				ec.assign(value, lt::system_category());
			else if (category == "generic")
				ec.assign(value, lt::generic_category());
			else if (category == "libtorrent")
				ec.assign(value, lt::libtorrent_category());
			else if (category == "http error")
				ec.assign(value, lt::http_category());
			else if (category == "UPnP error")
				ec.assign(value, lt::upnp_category());
			else if (category == "bdecode error")
				ec.assign(value, lt::bdecode_category());
			else if (category == "asio.netdb")
				ec.assign(value, boost::asio::error::get_netdb_category());
			else if (category == "asio.addinfo")
				ec.assign(value, boost::asio::error::get_addrinfo_category());
			else if (category == "asio.misc")
				ec.assign(value, boost::asio::error::get_misc_category());
#if TORRENT_USE_SSL
			else if (category == "asio.ssl")
				ec.assign(value, boost::asio::error::get_ssl_category());
#endif
			else
			{
				PyErr_SetObject(PyExc_ValueError,
					("unexpected error_category passed to __setstate__; got '%s'"
					% object(category)).ptr());
				throw_error_already_set();
			}
		}
	};
}

struct category_holder
{
	category_holder(boost::system::error_category const& cat) : m_cat(&cat) {}
	char const* name() const { return m_cat->name(); }
	std::string message(int const v) const { return m_cat->message(v); }

	friend bool operator==(category_holder const lhs, category_holder const rhs)
	{ return *lhs.m_cat == *rhs.m_cat; }

	friend bool operator!=(category_holder const lhs, category_holder const rhs)
	{ return *lhs.m_cat != *rhs.m_cat; }

	friend bool operator<(category_holder const lhs, category_holder const rhs)
	{ return *lhs.m_cat < *rhs.m_cat; }

	boost::system::error_category const& ref() const { return *m_cat; }
	operator boost::system::error_category const&() const { return *m_cat; }
private:
	boost::system::error_category const* m_cat;
};

void error_code_assign(boost::system::error_code& me, int const v, category_holder const cat)
{
	me.assign(v, cat.ref());
}

category_holder error_code_category(boost::system::error_code const& me)
{
	return category_holder(me.category());
}

#define WRAP_CAT(name) \
	category_holder wrap_ ##name## _category() { return category_holder(name## _category()); }

WRAP_CAT(libtorrent)
WRAP_CAT(upnp)
WRAP_CAT(http)
WRAP_CAT(socks)
WRAP_CAT(bdecode)
#if TORRENT_USE_I2P
WRAP_CAT(i2p)
#endif
WRAP_CAT(generic)
WRAP_CAT(system)

#undef WRAP_CAT

#if TORRENT_ABI_VERSION == 1

#define WRAP_DEPR_CAT(name) \
	category_holder wrap_ ##name## _category_deprecated() { \
        python_deprecated(#name " is deprecated"); \
		return category_holder(name## _category()); \
	}

WRAP_DEPR_CAT(libtorrent)
WRAP_DEPR_CAT(upnp)
WRAP_DEPR_CAT(http)
WRAP_DEPR_CAT(socks)
WRAP_DEPR_CAT(bdecode)
#if TORRENT_USE_I2P
WRAP_DEPR_CAT(i2p)
#endif
WRAP_DEPR_CAT(generic)
WRAP_DEPR_CAT(system)

#undef WRAP_DEPR_CAT
#endif

void bind_error_code()
{
    class_<category_holder>("error_category", no_init)
        .def("name", &category_holder::name)
        .def("message", &category_holder::message)
        .def(self == self)
        .def(self < self)
        .def(self != self)
        ;

    class_<error_code>("error_code")
        .def(init<>())
        .def(init<int, category_holder>())
        .def("message", static_cast<std::string (error_code::*)() const>(&error_code::message))
        .def("value", &error_code::value)
        .def("clear", &error_code::clear)
        .def("category", &error_code_category)
        .def("assign", &error_code_assign)
        .def_pickle(ec_pickle_suite())
        ;

    def("libtorrent_category", &wrap_libtorrent_category);
    def("upnp_category", &wrap_upnp_category);
    def("http_category", &wrap_http_category);
    def("socks_category", &wrap_socks_category);
    def("bdecode_category", &wrap_bdecode_category);
#if TORRENT_USE_I2P
    def("i2p_category", &wrap_i2p_category);
#endif

#if TORRENT_ABI_VERSION == 1
    def("get_libtorrent_category", &wrap_libtorrent_category_deprecated);
    def("get_upnp_category", &wrap_upnp_category_deprecated);
    def("get_http_category", &wrap_http_category_deprecated);
    def("get_socks_category", &wrap_socks_category_deprecated);
    def("get_bdecode_category", &wrap_bdecode_category_deprecated);
#if TORRENT_USE_I2P
    def("get_i2p_category", &wrap_i2p_category_deprecated);
#endif
#endif // TORRENT_ABI_VERSION

    def("generic_category", &wrap_generic_category);

    def("system_category", &wrap_system_category);
}

max_stars_repo_name: aldenml/libtorrent

max_issues_repo_name: aldenml/libtorrent

max_forks_repo_name: aldenml/libtorrent


text:
#include <boost/asio.hpp>
#include <iostream>

using namespace boost;

int main()
{
	// Step1. Assume that the client application has already
	// obtained the IP-address and the protocol port number.
	std::string raw_ip_address = "127.0.0.1";
	unsigned short port_num = 3333;

	// Used to store information about error that happens
	// while parsing the raw IP-address.
	boost::system::error_code ec;

	// Step2. Using IP protocol version independent address
	// representation.
	asio::ip::address ip_address =
		asio::ip::address::from_string(raw_ip_address, ec);

	if (ec.value() != 0) {
		// Provided IP address is invalid. Breaking execution.
		std::cout
			<< "Failed to parse the IP address. Error code = "
			<< ec.value() << ". Message: " << ec.message();
		return ec.value();
	}

	// Step 3.
	asio::ip::tcp::endpoint ep(ip_address, port_num);

	// Step 4. The endpoint is ready and can be used to specify a
	// particular server in the network the client wants to
	// communicate with.

	return 0;
}

max_stars_repo_name: sinomiko/project

max_issues_repo_name: sinomiko/project

max_forks_repo_name: sinomiko/project


text:
#include <frovedis.hpp>
#include <frovedis/matrix/sliced_vector.hpp>
#include <frovedis/matrix/sliced_matrix.hpp>
#include <frovedis/matrix/blas_wrapper.hpp>

#define BOOST_TEST_MODULE FrovedisTest
#include <boost/test/unit_test.hpp>

using namespace frovedis;
using namespace std;

BOOST_AUTO_TEST_CASE( frovedis_test )
{
    int argc = 1;
    char** argv = NULL;
    use_frovedis use(argc, argv);

    colmajor_matrix_local<float> cm (
             make_rowmajor_matrix_local_load<float>("./sample_6x6"));

    // creating slice matrix from colmajor matrix (error, invalid range)
    bool error_in_slice_matrix_creation = false;
    sliced_colmajor_matrix_local<float> sm;
    try {
      sm = make_sliced_colmajor_matrix_local<float>(cm,1,1,6,6);
    }
    catch (std::exception& e) {
      error_in_slice_matrix_creation = true;
    }

    // creating slice matrix from colmajor matrix (OK)
    sm = make_sliced_colmajor_matrix_local<float>(cm,1,1,4,4);

    // creating slice vectors from slice matrix
    bool error_in_row_vector_creation = false;
    sliced_colmajor_vector_local<float> sv;
    try {
      sv = make_row_vector(sm,4); // error, invalid row-id
    }
    catch (std::exception& e) {
      error_in_row_vector_creation = true;
    }

    // confirming if above expected exceptions occur
    BOOST_CHECK (error_in_slice_matrix_creation);
    BOOST_CHECK (error_in_row_vector_creation);
}

max_stars_repo_name: XpressAI/frovedis

max_issues_repo_name: XpressAI/frovedis

max_forks_repo_name: XpressAI/frovedis


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_GET_SYSTEM_HPP
#define BOOST_UNITS_GET_SYSTEM_HPP

/// \file
/// \brief Get the system of a unit, absolute unit or quantity.

#include <boost/units/units_fwd.hpp>

namespace boost {

namespace units {

template<class T>
struct get_system {};

/// Get the system of a unit.
template<class Dim,class System>
struct get_system< unit<Dim,System> >
{
    typedef System type;
};

/// Get the system of an absolute unit.
template<class Unit>
struct get_system< absolute<Unit> >
{
    typedef typename get_system<Unit>::type type;
};

/// Get the system of a quantity.
template<class Unit,class Y>
struct get_system< quantity<Unit,Y> >
{
    typedef typename get_system<Unit>::type     type;
};

} // namespace units

} // namespace boost

#endif // BOOST_UNITS_GET_SYSTEM_HPP