text:
#include "random_tree.h"

#include <boost/algorithm/string/join.hpp>
#include <boost/format.hpp>

namespace curfil {

namespace detail {
bool isScoreBetter(const ScoreType bestScore, const ScoreType score, const int featureNr) {
    double diff = fabs(score - bestScore);

#ifndef NDEBUG
    if (diff > 0 && diff < 1e-8) {
        CURFIL_WARNING(boost::format("close scores: %.15f (feat %d)") % bestScore % featureNr
                << boost::format(" vs %.15f, diff: %.15f") % score % diff);
    }
#endif

    if (diff < 1e-13) {
        // hack to make CPU and GPU results comparable
        return false;
    }

    return (score > bestScore);
}

cuv::ndarray<double, cuv::host_memory_space> normalizeHistogram(
        const cuv::ndarray<WeightType, cuv::host_memory_space>& histogram,
        const cuv::ndarray<WeightType, cuv::host_memory_space>& priorDistribution,
        const double histogramBias) {

    const int numLabels = histogram.size();

    cuv::ndarray<double, cuv::host_memory_space> normalizedHistogram(numLabels);

    std::vector<double> labelWeights(numLabels);
    {
        double sum = 0;
        for (int i = 0; i < numLabels; i++) {
            sum += priorDistribution[i];
        }
        for (int i = 0; i < numLabels; i++) {
            labelWeights[i] = priorDistribution[i] / sum;
        }
    }

    double sum = 0;
    for (int i = 0; i < numLabels; i++) {
        assert(sum < std::numeric_limits<WeightType>::max() - histogram[i]);
        sum += histogram[i];
    }

    for (int i = 0; i < numLabels; i++) {
        normalizedHistogram[i] = histogram[i] - histogramBias * sum;
        if (normalizedHistogram[i] < 0.0) {
            normalizedHistogram[i] = 0.0;
        }
    }

    sum = 0;
    for (int i = 0; i < numLabels; i++) {
        assert(sum < std::numeric_limits<WeightType>::max() - histogram[i]);
        sum += normalizedHistogram[i];
    }

    if (sum > 0) {
        for (int i = 0; i < numLabels; i++) {
          //  normalizedHistogram[i] = normalizedHistogram[i] / sum * labelWeights[i];
            normalizedHistogram[i] = normalizedHistogram[i] / sum ;
        }
    }

    return normalizedHistogram;
}
}

int Sampler::getNext() {
    int value = distribution(rng);
    assert(value >= lower);
    assert(value <= upper);
    return value;
}

AccelerationMode TrainingConfiguration::parseAccelerationModeString(const std::string& modeString) {
    if (modeString == "cpu") {
        return AccelerationMode::CPU_ONLY;
    } else if (modeString == "gpu") {
        return AccelerationMode::GPU_ONLY;
    } else if (modeString == "compare") {
        return AccelerationMode::GPU_AND_CPU_COMPARE;
    } else {
        throw std::runtime_error(std::string("illegal acceleration mode: ") + modeString);
    }
}

std::string TrainingConfiguration::getAccelerationModeString() const {
    switch (accelerationMode) {
        case GPU_ONLY:
            return "gpu";
        case CPU_ONLY:
            return "cpu";
        case GPU_AND_CPU_COMPARE:
            return "compare";
        default:
            throw std::runtime_error(boost::str(boost::format("unknown acceleration mode: %d") % accelerationMode));
    }
}

TrainingConfiguration::TrainingConfiguration(const TrainingConfiguration& other) {
    *this = other;
}

TrainingConfiguration& TrainingConfiguration::operator=(const TrainingConfiguration& other) {
    randomSeed = other.randomSeed;
    samplesPerImage = other.samplesPerImage;
    featureCount = other.featureCount;
    minSampleCount = other.minSampleCount;
    maxDepth = other.maxDepth;
    boxRadius = other.boxRadius;
    regionSize = other.regionSize;
    thresholds = other.thresholds;
    numThreads = other.numThreads;
    maxImages = other.maxImages;
    imageCacheSize = other.imageCacheSize;
    maxSamplesPerBatch = other.maxSamplesPerBatch;
    accelerationMode = other.accelerationMode;
    useCIELab = other.useCIELab;
    useDepthFilling = other.useDepthFilling;
    deviceIds = other.deviceIds;
    subsamplingType = other.subsamplingType;
    ignoredColors = other.ignoredColors;
    useDepthImages = other.useDepthImages;
    horizontalFlipping = other.horizontalFlipping;
    assert(*this == other);
    return *this;
}

bool TrainingConfiguration::equals(const TrainingConfiguration& other,
        bool strict) const {

    if (strict && randomSeed != other.randomSeed)
        return false;
    if (strict && deviceIds != other.deviceIds)
        return false;
    if (strict && imageCacheSize != other.imageCacheSize)
        return false;
    if (strict && maxSamplesPerBatch != other.maxSamplesPerBatch)
        return false;

    if (samplesPerImage != other.samplesPerImage)
        return false;
    if (featureCount != other.featureCount)
        return false;
    if (minSampleCount != other.minSampleCount)
        return false;
    if (maxDepth != other.maxDepth)
        return false;
    if (boxRadius != other.boxRadius)
        return false;
    if (regionSize != other.regionSize)
        return false;
    if (thresholds != other.thresholds)
        return false;
    if (numThreads != other.numThreads)
        return false;
    if (maxImages != other.maxImages)
        return false;
    if (accelerationMode != other.accelerationMode)
        return false;
    if (subsamplingType != other.subsamplingType)
        return false;
    if (ignoredColors != other.ignoredColors)
        return false;
    if (useCIELab != other.useCIELab)
        return false;
    if (useDepthFilling != other.useDepthFilling)
        return false;
    if (useDepthImages != other.useDepthImages)
    	return false;
    if (horizontalFlipping != other.horizontalFlipping)
    	return false;

    return true;
}

}

template<class T>
static std::string joinToString(const std::vector<T>& input, const std::string separator = ", ",
        const std::string prefix = "[", const std::string postfix = "]") {
    std::vector<std::string> strings;
    for (const auto& v : input) {
        strings.push_back(boost::lexical_cast<std::string>(v));
    }
    return prefix + boost::algorithm::join(strings, separator) + postfix;
}

std::ostream& operator<<(std::ostream& os, const curfil::TrainingConfiguration& configuration) {
    os << "randomSeed: " << configuration.getRandomSeed() << std::endl;
    os << "samplesPerImage: " << configuration.getSamplesPerImage() << std::endl;
    os << "featureCount: " << configuration.getFeatureCount() << std::endl;
    os << "minSampleCount: " << configuration.getMinSampleCount() << std::endl;
    os << "maxDepth: " << configuration.getMaxDepth() << std::endl;
    os << "boxRadius: " << configuration.getBoxRadius() << std::endl;
    os << "regionSize: " << configuration.getRegionSize() << std::endl;
    os << "thresholds: " << configuration.getThresholds() << std::endl;
    os << "maxImages: " << configuration.getMaxImages() << std::endl;
    os << "imageCacheSize: " << configuration.getImageCacheSize() << std::endl;
    os << "accelerationMode: " << configuration.getAccelerationModeString() << std::endl;
    os << "maxSamplesPerBatch: " << configuration.getMaxSamplesPerBatch() << std::endl;
    os << "subsamplingType: " << configuration.getSubsamplingType() << std::endl;
    os << "useCIELab: " << configuration.isUseCIELab() << std::endl;
    os << "useDepthFilling: " << configuration.isUseDepthFilling() << std::endl;
    os << "deviceIds: " << joinToString(configuration.getDeviceIds()) << std::endl;
    os << "ignoredColors: " << joinToString(configuration.getIgnoredColors()) << std::endl;
    os << "useDepthImages: " << configuration.isUseDepthImages() << std::endl;
    os << "horizontalFlipping: " << configuration.doHorizontalFlipping() << std::endl;
    return os;
}

max_stars_repo_name: ferasha/curfil

max_issues_repo_name: ferasha/curfil

max_forks_repo_name: ferasha/curfil


text:
#include "string_utils.hpp"

#include <string>
#include <vector>

#include <boost/array.hpp>
#include <boost/lexical_cast.hpp>

namespace string_utils {

const std::string ellipsis = "...";

const std::string unicode_minus = "−";
const std::string unicode_en_dash = "–";
const std::string unicode_em_dash = "—";
const std::string unicode_figure_dash = "‒";
const std::string unicode_multiplication_sign = "×";
const std::string unicode_bullet = "•";

bool isnewline(const char c) {
	return c == '\r' || c == '\n';
}

// Make sure that we can use Mac, DOS, or Unix style text files on any system
// and they will work, by making sure the definition of whitespace is consistent
bool portable_isspace(const char c) {
	// returns true only on ASCII spaces
	if (static_cast<unsigned char>(c) >= 128)
		return false;
	return isnewline(c) || isspace(c);
}

// Make sure we regard '\r' and '\n' as a space, since Mac, Unix, and DOS
// all consider these differently.
bool notspace(const char c) {
	return !portable_isspace(c);
}

std::string& strip(std::string& str) {
	// If all the string contains is whitespace,
	// then the whitespace may have meaning, so don't strip it
	std::string::iterator it = std::find_if(str.begin(), str.end(), notspace);
	if (it == str.end())
		return str;

	str.erase(str.begin(), it);
	str.erase(std::find_if(str.rbegin(), str.rend(), notspace).base(), str.end());

	return str;
}

std::string& strip_end(std::string& str) {
	str.erase(std::find_if(str.rbegin(), str.rend(), notspace).base(), str.end());

	return str;
}

/**
 * Splits a (comma-)separated string into a vector of pieces.
 * @param[in]  val    A (comma-)separated string.
 * @param[in]  c      The separator character (usually a comma).
 * @param[in]  flags  Flags controlling how the split is done.
 *                    This is a bit field with two settings (both on by default):
 *                    REMOVE_EMPTY causes empty pieces to be skipped/removed.
 *                    STRIP_SPACES causes the leading and trailing spaces of each piece to be ignored/stripped.
 */
std::vector<std::string> split(std::string const& val, const char c, const int flags) {
	std::vector<std::string> res;

	std::string::const_iterator i1 = val.begin();
	std::string::const_iterator i2;
	if (flags & STRIP_SPACES) {
		while (i1 != val.end() && portable_isspace(*i1))
			++i1;
	}
	i2 = i1;

	while (i2 != val.end()) {
		if (*i2 == c) {
			std::string new_val(i1, i2);
			if (flags & STRIP_SPACES)
				strip_end(new_val);
			if (!(flags & REMOVE_EMPTY) || !new_val.empty())
				res.push_back(new_val);
			++i2;
			if (flags & STRIP_SPACES) {
				while (i2 != val.end() && portable_isspace(*i2))
					++i2;
			}

			i1 = i2;
		} else {
			++i2;
		}
	}

	std::string new_val(i1, i2);
	if (flags & STRIP_SPACES)
		strip_end(new_val);
	if (!(flags & REMOVE_EMPTY) || !new_val.empty())
		res.push_back(new_val);

	return res;
}

} // end namespace string_utils

ext: cpp


text:
#include <assert.h>
#include <sstream>

#include <experimental/filesystem>
//#include <boost/filesystem/operations.hpp>

#include <GL/glew.h>

#include "auto_update_window.hpp"
#include "base64.hpp"
#include "compress.hpp"
#include "filesystem.hpp"
#include "json_parser.hpp"
#include "module.hpp"
#include "preferences.hpp"
#include "profile_timer.hpp"
#include "unit_test.hpp"
#include "variant_utils.hpp"

#include "CameraObject.hpp"
#include "Canvas.hpp"
#include "Font.hpp"
#include "Texture.hpp"

#ifdef _MSC_VER
#include <direct.h>
#define chdir _chdir
#define execv _execv
#else
#include <unistd.h>
#endif

extern std::string g_anura_exe_name;
extern std::string g_loading_screen_bg_color;

PREF_STRING(auto_update_dir, "", "Directory in which the auto-updater is");
PREF_STRING(auto_update_exe, "", "Exe of the auto-updater");

PREF_STRING(auto_update_game_name, "Anura", "Title shown on the auto update window");
PREF_STRING(auto_update_title, "Anura auto-update", "Title of the auto-update window");

PREF_STRING(auto_update_install_dir, "", "Directory which to install the game to");

void run_auto_updater()
{
	std::string original_cwd = sys::get_cwd();

	if(!g_auto_update_dir.empty() && !g_auto_update_exe.empty()) {

		int res = chdir(g_auto_update_dir.c_str());
		if(res != 0) {
			LOG_ERROR("Auto-update: Could not chdir " << g_auto_update_dir << ": " << res);
			return;
		}

		std::vector<char*> anura_args;
		anura_args.push_back(const_cast<char*>(g_anura_exe_name.c_str()));
		anura_args.push_back(nullptr);

		LOG_ERROR("Auto-update: switched to " << g_auto_update_dir << " running " << g_auto_update_exe);

#if !defined(WINRT)
		execv(anura_args[0], &anura_args[0]);
#endif
		LOG_ERROR("Failed to execute auto updater. Re-running game...");
#if defined(__linux__)
		LOG_ERROR("Errno: " << errno);
#endif

		res = chdir(original_cwd.c_str());
		if(res != 0) {
			LOG_ERROR("Auto-update: Could not chdir " << original_cwd << ": " << res);
			return;
		}
	}

	auto v = preferences::argv();
	std::vector<char*> anura_args;
	for(const std::string& s : v) {
		anura_args.push_back(const_cast<char*>(s.c_str()));
	}

	anura_args.push_back(nullptr);

#if !defined(WINRT)
	execv(anura_args[0], &anura_args[0]);
#endif
	LOG_ERROR("Failed to restart game\n");
#if defined(__linux__)
	LOG_ERROR("Errno: " << errno);
#endif

	return;
}

namespace
{
	variant get_update_config(const std::string& name)
	{
		static std::map<std::string,variant> attr;
		static bool init = false;
		if(!init) {
			init = true;
			try {
				if(sys::file_exists("./update/update.cfg")) {
					variant cfg = json::parse(sys::read_file("./update/update.cfg"), json::JSON_PARSE_OPTIONS::NO_PREPROCESSOR);

					if(cfg.is_map()) {
						for(auto p : cfg.as_map()) {
							if(p.first.is_string()) {
								attr[p.first.as_string()] = p.second;
							}
						}
					}
				}
			} catch(...) {
			}
		}

		return attr[name];
	}

	KRE::Color get_update_color(const std::string& name, std::string default_val)
	{
		variant v = get_update_config(name);
		if(v.is_null()) {
			return KRE::Color(default_val);
		}

		return KRE::Color(v);
	}

	KRE::TexturePtr render_updater_text(const std::string& str, const KRE::Color& color, int size=-1)
	{
		if(size < 0) {
			size = get_update_config("font_size").as_int(24);
		}

		return KRE::Font::getInstance()->renderText(str, color, size, true, KRE::Font::getDefaultFont());
	}

	class progress_animation
	{
	public:
		static progress_animation& get() {
			static progress_animation instance;
			return instance;
		}

		progress_animation()
		{
			std::string contents = sys::read_file("update/progress.cfg");
			if(contents == "") {
				area_ = rect();
				pad_ = rows_ = cols_ = 0;
				return;
			}

			variant cfg = json::parse(contents, json::JSON_PARSE_OPTIONS::NO_PREPROCESSOR);
			area_ = rect(cfg["x"].as_int(), cfg["y"].as_int(), cfg["w"].as_int(), cfg["h"].as_int());
			tex_ = KRE::Texture::createTexture(cfg["image"].as_string());
			pad_ = cfg["pad"].as_int();
			rows_ = cfg["rows"].as_int();
			cols_ = cfg["cols"].as_int();
		}

		KRE::TexturePtr tex() const { return tex_; }
		rect calculate_rect(int ntime) const {
			if(rows_ * cols_ == 0) {
				return area_;
			}
			ntime = ntime % (rows_*cols_);

			int row = ntime / cols_;
			int col = ntime % cols_;

			rect result(area_.x() + (area_.w() + pad_) * col, area_.y() + (area_.h() + pad_) * row, area_.w(), area_.h());
			return result;
		}

	private:
		KRE::TexturePtr tex_;
		rect area_;
		int pad_, rows_, cols_;
	};
}

auto_update_window::auto_update_window() : window_(), nframes_(0), start_time_(SDL_GetTicks()), percent_(0.0), is_new_install_(false)
{
}

auto_update_window::~auto_update_window()
{
}

void auto_update_window::load_background_texture()
{
	if(module_path_.empty() == false) {
		if(sys::file_exists(module_path_ + "update-bg.jpg")) {
			sys::copy_file(module_path_ + "update-bg.jpg", "./update/update-bg.jpg");
		}
	}

	load_background_texture("./update/update-bg.jpg");
}

void auto_update_window::load_background_texture(const std::string& path)
{

	try {
		assert_recover_scope guard;
		bg_texture_ = KRE::Texture::createTexture(path);
	} catch(...) {
	}
}

void auto_update_window::set_progress(float percent)
{
	percent_ = percent;
}

void auto_update_window::set_message(const std::string& str)
{
	message_ = str;
}

void auto_update_window::set_error_message(const std::string& str)
{
	error_message_ = str;
}

void auto_update_window::process()
{
	++nframes_;
	if(window_ == nullptr && (SDL_GetTicks() - start_time_ > 2000 || is_new_install_)) {
		create_window();
	}
}

void auto_update_window::create_window()
{
	if(window_ != nullptr) {
		return;
	}

	manager_.reset(new SDL::SDL());

	variant_builder hints;
	hints.add("renderer", "opengl");
	hints.add("title", get_update_config("window_title").as_string_default(g_auto_update_title.c_str()));
	hints.add("clear_color", "black");

	KRE::WindowManager wm("SDL");
	window_ = wm.createWindow(get_update_config("window_width").as_int(800), get_update_config("window_height").as_int(600), hints.build());

	window_->setWindowIcon("update/window-icon.png");

	using namespace KRE;

	// Set the default font to use for rendering. This can of course be overridden when rendering the
	// text to a texture.
	Font::setDefaultFont("default");
	std::map<std::string,std::string> font_paths;
	font_paths["default"] = "update/font.otf";
	KRE::Font::setAvailableFonts(font_paths);

	load_background_texture();
}

void auto_update_window::draw() const
{
	if(window_ == nullptr) {
		return;
	}

	auto canvas = KRE::Canvas::getInstance();

	window_->setClearColor(get_update_color("background_color", "black"));
	window_->clear(KRE::ClearFlags::COLOR);

	if(bg_texture_) {
		canvas->blitTexture(bg_texture_, 0, 0, 0);
	}

	const int bar_width = get_update_config("bar_width").as_int(400);

	canvas->drawSolidRect(rect(window_->width()/2 - bar_width/2, get_update_config("bar_ypos").as_int(480), bar_width, get_update_config("bar_height").as_int(10)), get_update_color("bar_empty_color", "white"));
	const rect filled_area(window_->width()/2 - bar_width/2, get_update_config("bar_ypos").as_int(480), int(bar_width*percent_), get_update_config("bar_height").as_int(10));
	canvas->drawSolidRect(filled_area, get_update_color("bar_filled_color", "cyan"));

	KRE::TexturePtr aa_text_surf(render_updater_text(get_update_config("title_text").as_string_default(g_auto_update_game_name.c_str()), get_update_color("title_text_color", "white"), get_update_config("title_font_size").as_int(48)));
	if(aa_text_surf) {
		canvas->blitTexture(aa_text_surf, 0, window_->width()/2 - aa_text_surf->width()/2, get_update_config("title_ypos").as_int(300));
	}

	const int bar_point = filled_area.x2();

	const int percent = static_cast<int>(percent_*100.0);
	std::ostringstream percent_stream;
	percent_stream << percent << "%";

	KRE::TexturePtr percent_surf(render_updater_text(percent_stream.str(), get_update_color("percent_text_color", "white"), get_update_config("percent_font_size").as_int(24)));

	if(percent_surf != nullptr) {
		canvas->blitTexture(percent_surf, 0,
			(window_->width() - percent_surf->width()) / 2, get_update_config("percent_ypos").as_int(440));
	}

	KRE::TexturePtr message_surf(render_updater_text(message_, KRE::Color(get_update_config("message_text_color").as_string_default("white")), 20));
	if(message_surf != nullptr) {
		canvas->blitTexture(message_surf, 0, window_->width()/2 - message_surf->width()/2, get_update_config("message_ypos").as_int(500));
	}

	if(error_message_ != "") {
		KRE::TexturePtr message_surf(render_updater_text(error_message_, get_update_color("error_text_color", "red")));
		if(message_surf != nullptr) {
			canvas->blitTexture(message_surf, 0, window_->width()/2 - message_surf->width()/2, get_update_config("error_ypos").as_int(540));
		}
	}

	progress_animation& anim = progress_animation::get();
	auto anim_tex = anim.tex();
	if(anim_tex != nullptr) {
		rect src = anim.calculate_rect(nframes_);
		rect dest(window_->width()/2 - src.w()/2, window_->height()/2 - src.h(), src.w(), src.h());
		canvas->blitTexture(anim_tex, src, 0, dest);
	}
	window_->swap();
}

bool auto_update_window::proceed_or_retry_dialog(const std::string& msg)
{
	create_window();

	static const KRE::Color normal_button_color(0,140,114,255);
	static const KRE::Color depressed_button_color(168,64,30,255);
	static const KRE::Color text_button_color(158,216,166,255);

	for(;;) {
		auto canvas = KRE::Canvas::getInstance();

		window_->clear(KRE::ClearFlags::COLOR);

		int mx, my;
		SDL_GetMouseState(&mx, &my);

		point mouse_pos(mx, my);

		const rect proceed_button_area(window_->width()/2 - 200, window_->height()/2 + 100, 100, 40);
		const rect retry_button_area(window_->width()/2 + 100, window_->height()/2 + 100, 100, 40);

		const bool mouseover_proceed = pointInRect(mouse_pos, proceed_button_area);
		const bool mouseover_retry = pointInRect(mouse_pos, retry_button_area);

		canvas->drawSolidRect(proceed_button_area, mouseover_proceed ? depressed_button_color : normal_button_color);
		canvas->drawSolidRect(retry_button_area, mouseover_retry ? depressed_button_color : normal_button_color);

		KRE::TexturePtr proceed_text_texture = KRE::Font::getInstance()->renderText("Proceed", KRE::Color(0,0,0,255), 24, true, KRE::Font::getDefaultFont());
		KRE::TexturePtr retry_text_texture = KRE::Font::getInstance()->renderText("Retry", KRE::Color(0,0,0,255), 24, true, KRE::Font::getDefaultFont());
		canvas->blitTexture(proceed_text_texture, 0, (proceed_button_area.x() + proceed_button_area.x2() - proceed_text_texture->width())/2, (proceed_button_area.y() + proceed_button_area.y2() - proceed_text_texture->height())/2);
		canvas->blitTexture(retry_text_texture, 0, (retry_button_area.x() + retry_button_area.x2() - retry_text_texture->width())/2, (retry_button_area.y() + retry_button_area.y2() - retry_text_texture->height())/2);

		KRE::TexturePtr message_texture = KRE::Font::getInstance()->renderText("Failed to update the game. Retry or proceed without updating?", KRE::Color(255,255,255,255), 24, true, KRE::Font::getDefaultFont());
		canvas->blitTexture(message_texture, 0, (window_->width() - message_texture->width())/2, window_->height()/2);

		message_texture = KRE::Font::getInstance()->renderText(msg, KRE::Color(255,0,0,255), 24, true, KRE::Font::getDefaultFont());
		canvas->blitTexture(message_texture, 0, (window_->width() - message_texture->width())/2, window_->height()/2 + 40);

		window_->swap();

		SDL_PumpEvents();
		SDL_Delay(20);

		SDL_Event event;
		while(SDL_PollEvent(&event)) {
			switch(event.type) {
			case SDL_QUIT:
				SDL_Quit();
				exit(0);
				break;
			case SDL_MOUSEBUTTONDOWN:
			case SDL_MOUSEBUTTONUP:
				if(mouseover_proceed) {
					return true;
				} else if(mouseover_retry) {
					return false;
				}

				break;
			}
		}
	}

	return true;
}

namespace {

class module_updater_client : public module::client
{
public:
	explicit module_updater_client(auto_update_window& w) : window_(w)
	{}
private:
	auto_update_window& window_;
	std::map<std::string, std::string> update_chunks_;
	virtual bool isHighPriorityChunk(const variant& chunk_id, variant& chunk) override {
		if(!chunk_id.is_string()) {
			return false;
		}

		fprintf(stderr, "CHUNK: %s -> %s\n",chunk_id.as_string().c_str(), chunk["md5"].as_string().c_str());

		std::string id = chunk_id.as_string();
		if(std::equal(id.begin(), id.begin()+7, "update/") == false) {
			return false;
		}

		update_chunks_[chunk["md5"].as_string()] = id;
		return true;

		static const std::string update_bg("update/update-bg.jpg");
		if(id == update_bg) {
			return true;
		}
		return false;
	}

	virtual void onChunkReceived(variant& chunk) override {
		auto itor = update_chunks_.find(chunk["md5"].as_string());
		if(itor != update_chunks_.end()) {
			try {
				std::string data_str;
				if(chunk["data"].is_string()) {
					data_str = chunk["data"].as_string();
				} else {
					data_str = sys::read_file("update-cache/" + chunk["md5"].as_string());
				}

				std::vector<char> data_buf;
				data_buf.insert(data_buf.begin(), data_str.begin(), data_str.end());

				const int data_size = chunk["size"].as_int();

				std::vector<char> data = zip::decompress_known_size(base64::b64decode(data_buf), data_size);
				std::string contents(data.begin(), data.end());

				fprintf(stderr, "WRITE FILE: %s\n", itor->second.c_str());

				sys::write_file(itor->second, contents);

				if(itor->second == "update/update-bg.jpg") {
					window_.set_module_path("");
					window_.load_background_texture("update/update-bg.jpg");
				}
			} catch(...) {
			}
		}
	}
};

bool do_auto_update(std::deque<std::string> argv, auto_update_window& update_window, std::string& error_msg, int timeout_ms)
{
#ifdef _MSC_VER
	std::string anura_exe = "anura.exe";
#else
	std::string anura_exe = "./anura";
#endif

	std::string subdir;
	std::string real_anura;
	bool update_anura = true;
	bool update_module = true;
	bool force = false;

	if(sys::file_exists("./update/overrides.cfg")) {
		try {
			variant overrides = json::parse(sys::read_file("./update/overrides.cfg"), json::JSON_PARSE_OPTIONS::NO_PREPROCESSOR);
			if(overrides.is_map()) {
				variant one_time_args = overrides["arguments"];
				if(one_time_args.is_list()) {
					for(auto s : one_time_args.as_list_string()) {
						argv.push_front(s);
					}
				}
			}
		} catch(...) {
		}
	}

	while(!argv.empty()) {
		std::string arg = argv.front();
		argv.pop_front();

		std::string arg_name = arg;
		std::string arg_value;
		auto equal_itor = std::find(arg_name.begin(), arg_name.end(), '=');
		if(equal_itor != arg_name.end()) {
			arg_value = std::string(equal_itor+1, arg_name.end());
			arg_name = std::string(arg_name.begin(), equal_itor);
		}

		if(arg_name == "--timeout") {
			timeout_ms = atoi(arg_value.c_str());
		} else if(arg_name == "--args") {
			ASSERT_LOG(arg_value.empty(), "Unrecognized argument: " << arg);
			break;
		} else if(arg_name == "--update_module" || arg_name == "--update-module") {
			if(arg_value == "true" || arg_value == "yes") {
				update_module = true;
			} else if(arg_value == "false" || arg_value == "no") {
				update_module = false;
			} else {
				ASSERT_LOG(false, "Unrecognized argument: " << arg);
			}
		} else if(arg_name == "--update_anura" || arg_name == "--update-anura") {
			if(arg_value == "true" || arg_value == "yes") {
				update_anura = true;
			} else if(arg_value == "false" || arg_value == "no") {
				update_anura = false;
			} else {
				ASSERT_LOG(false, "Unrecognized argument: " << arg);
			}
		} else if(arg_name == "--anura") {
			ASSERT_LOG(arg_value.empty() == false, "--anura requires a value giving the name of the anura module to use");
			real_anura = arg_value;
		} else if(arg_name == "--anura-exe" || arg_name == "--anura_exe") {
			ASSERT_LOG(arg_value.empty() == false, "--anura-exe requires a value giving the name of the anura executable to use");
			anura_exe = arg_value;
		} else if(arg_name == "--subdir") {
			subdir = arg_value;
		} else if(arg_name == "--force") {
			force = true;
		} else {
			ASSERT_LOG(false, "Unrecognized argument: " << arg);
		}
	}

	ASSERT_LOG(real_anura != "", "Must provide a --anura argument with the name of the anura module to use");

	variant_builder update_info;

	if(update_anura || update_module) {
		ffl::IntrusivePtr<module::client> cl, anura_cl;

		bool is_new_install = false;

		bool has_error = false;

#define HANDLE_ERROR(msg) \
		{ \
			LOG_ERROR(msg); \
			std::ostringstream s; \
			s << msg; \
			error_msg = s.str(); \
			bool newer = strstr(error_msg.c_str(), "newer") != nullptr; \
			if(!newer) { has_error = true; } \
			if(!newer && (!cl || !anura_cl)) { \
				if(is_new_install || update_window.proceed_or_retry_dialog(error_msg) == false) { \
					 return false; \
				} \
			} \
		}

		if(update_module) {
			cl.reset(new module_updater_client(update_window));
			cl->set_module_description("game");
			if(g_auto_update_install_dir.empty() == false) {
				cl->set_install_path_override(g_auto_update_install_dir + "/modules/" + module::get_module_name());
			}

			cl->set_show_progress_fn([&update_window](const std::string& msg) {
				update_window.set_message(msg);
				update_window.process();
				update_window.draw();
			});
			const bool res = cl->install_module(module::get_module_name(), force);
			if(!res) {
				cl.reset();
			} else {
				update_info.add("attempt_module", true);
				if(cl->is_new_install()) {
					is_new_install = true;
				}

				update_window.set_module_path(cl->module_path());
			}
		}

		if(update_anura) {
			anura_cl.reset(new module::client);
			anura_cl->set_module_description("engine");
			if(g_auto_update_install_dir.empty() == false) {
				anura_cl->set_install_path_override(g_auto_update_install_dir);
			}

			anura_cl->set_show_progress_fn([&update_window](const std::string& msg) {
				update_window.set_message(msg);
				update_window.process();
				update_window.draw();
			});
			//anura_cl->set_install_image(true);
			const bool res = anura_cl->install_module(real_anura, force);
			if(!res) {
				anura_cl.reset();
			} else {
				update_info.add("attempt_anura", true);
				if(anura_cl->is_new_install()) {
					is_new_install = true;
				}
			}
		}

		if(is_new_install) {
			timeout_ms *= 10;
		}

		int start_time = profile::get_tick_time();
		bool timeout = false;
		LOG_INFO("Requesting update to module from server...");
		int nupdate_cycle = 0;

		if(cl || anura_cl) {
		update_window.set_error_message(error_msg);
		if(is_new_install) {
			update_window.set_is_new_install();
		}

		ffl::IntrusivePtr<module::client> cl_install, anura_cl_install;

		int cl_nbytes_total = 0, anura_cl_nbytes_total = 0, cl_nbytes_transferred = 0, anura_cl_nbytes_transferred = 0;

		while(cl || anura_cl) {
			update_window.process();

			++nupdate_cycle;

			if(cl) {
				cl_nbytes_transferred = cl->nbytes_transferred();
				cl_nbytes_total = cl->nbytes_total();
			}

			if(anura_cl) {
				anura_cl_nbytes_transferred = anura_cl->nbytes_transferred();
				anura_cl_nbytes_total = anura_cl->nbytes_total();
			}

			const int time_taken = profile::get_tick_time() - start_time;
			if(time_taken > timeout_ms) {
				HANDLE_ERROR("Timed out updating module. Canceling. " << time_taken << "ms vs " << timeout_ms << "ms");
				if(is_new_install) {
					return false;
				}
				break;
			}

			char msg[1024];
			if(anura_cl_nbytes_total < 0 || cl_nbytes_total < 0) {
				sprintf(msg, "%s", get_update_config("message_text_contacting").as_string_default("Updating Game. Contacting server...").c_str());
			} else {
				sprintf(msg, "%s%0.2f/%0.2f%s", get_update_config("message_text_prefix").as_string_default("Updating Game. Transferred ").c_str(), float((cl_nbytes_transferred + anura_cl_nbytes_transferred)/(1024.0*1024.0)), float((anura_cl_nbytes_total + cl_nbytes_total)/(1024.0*1024.0)), get_update_config("message_text_postfix").as_string_default("MB").c_str());
			}

			update_window.set_message(msg);

			const float ratio = (anura_cl_nbytes_total < 0 || cl_nbytes_total < 0) ? 0 : static_cast<float>(cl_nbytes_transferred + anura_cl_nbytes_transferred)/static_cast<float>(std::max<int>(1, (anura_cl_nbytes_total + cl_nbytes_total)));
			update_window.set_progress(ratio);
			update_window.draw();

			SDL_Event event;
			while(SDL_PollEvent(&event)) {
				if(event.type == SDL_QUIT) {
					return true;
				}
			}

			const int target_end = profile::get_tick_time() + 50;
			while(static_cast<int>(profile::get_tick_time()) < target_end && (cl || anura_cl)) {
				if(cl && !cl->process()) {
					if(cl->error().empty() == false) {
						HANDLE_ERROR("Error while updating module: " << cl->error().c_str());
						update_info.add("module_error", variant(cl->error()));
					} else {
						cl_install = cl;
					}

					cl.reset();
				}

				if(anura_cl && !anura_cl->process()) {
					if(anura_cl->error().empty() == false) {
						HANDLE_ERROR("Error while updating anura: " << anura_cl->error().c_str());
						update_info.add("anura_error", variant(anura_cl->error()));
					} else {
						update_info.add("complete_anura", true);
						anura_cl_install = anura_cl;
					}

					anura_cl.reset();
				}
			}
		}

		cl = cl_install;
		anura_cl = anura_cl_install;

		if(cl && cl->is_pending_install()) {
			cl->complete_install();
			if(cl->error().empty() == false) {
				HANDLE_ERROR("Error while installing module: " << cl->error().c_str());
				update_info.add("module_error", variant(cl->error()));
			} else {
				update_info.add("complete_module", true);
			}
		}

		if(anura_cl && anura_cl->is_pending_install()) {
			anura_cl->complete_install();
			if(anura_cl->error().empty() == false) {
				HANDLE_ERROR("Error while installing anura: " << anura_cl->error().c_str());
				update_info.add("anura_error", variant(anura_cl->error()));
			} else {
				update_info.add("complete_anura", true);
			}
		}

		if(has_error && (is_new_install || update_window.proceed_or_retry_dialog(error_msg) == false)) {
			return false;
		}

		}
	}

	if(sys::file_exists("./update/overrides.cfg")) {
		try {
			variant overrides = json::parse_from_file("./update/overrides.cfg", json::JSON_PARSE_OPTIONS::NO_PREPROCESSOR);
			if(overrides.is_map()) {
				overrides.remove_attr_mutation(variant("arguments"));
				sys::write_file("./update/overrides.cfg", overrides.write_json());
			}
		} catch(...) {
		}
	}

	//remove the update cache since we downloaded and installed everything.
	sys::rmdir_recursive("update-cache");

#ifdef _MSC_VER
	const std::string cl_quotes = "\"";
#else
	const std::string cl_quotes = "";
#endif

	std::string cwd_arg = cl_quotes + "--auto-update-dir=" + sys::get_cwd() + cl_quotes;
	std::string exe_arg = cl_quotes + "--auto-update-exe=" + (g_auto_update_exe.empty() == false ? g_auto_update_exe : g_anura_exe_name) + cl_quotes;

	const std::string working_dir = g_auto_update_install_dir.empty() == false ? g_auto_update_install_dir : preferences::dlc_path() + "/" + real_anura + subdir;
	LOG_INFO("CHANGE DIRECTORY: " << working_dir);
	const int res = chdir(working_dir.c_str());
	ASSERT_LOG(res == 0, "Could not change directory to game working directory: " << working_dir);

	//write the file in the directory we are executing in to tell anura
	//what the auto-update status is.
	sys::write_file("./auto-update-status.json", update_info.build().write_json(false, variant::JSON_COMPLIANT));

	std::vector<char*> anura_args;
	anura_args.push_back(const_cast<char*>(anura_exe.c_str()));

	for(const std::string& a : argv) {
		anura_args.push_back(const_cast<char*>(a.c_str()));
	}

	anura_args.push_back(const_cast<char*>(cwd_arg.c_str()));
	anura_args.push_back(const_cast<char*>(exe_arg.c_str()));

	std::string command_line;
	for(const char* c : anura_args) {
		command_line += '"' + std::string(c) + "\" ";
	}

	LOG_INFO("EXECUTING: " << command_line);

	anura_args.push_back(nullptr);

#if !defined(WINRT)
	execv(anura_args[0], &anura_args[0]);
#endif

	const bool has_file = sys::file_exists(anura_exe);

#ifndef _MSC_VER
	if(has_file && !sys::is_file_executable(anura_exe)) {
		sys::set_file_executable(anura_exe);

		execv(anura_args[0], &anura_args[0]);

		if(!sys::is_file_executable(anura_exe)) {
			ASSERT_LOG(false, "Could not execute " << anura_exe << " from " << working_dir << " file does not appear to be executable");
		}
	}
#endif

	ASSERT_LOG(has_file, "Could not execute " << anura_exe << " from " << working_dir << ". The file does not exist. Try re-running the update process.");
	ASSERT_LOG(false, "Could not execute " << anura_exe << " from " << working_dir << ". The file exists and appears to be executable.");

	return false;
}
}

COMMAND_LINE_UTILITY(update_launcher)
{
	int timeout_ms = 10000000;

	auto_update_window update_window;
	std::string error_msg;
	std::deque<std::string> argv(args.begin(), args.end());
	try {
		while(!do_auto_update(argv, update_window, error_msg, timeout_ms)) {
			if(timeout_ms < 10000000) {
				timeout_ms = 10000000;
			}
		}
	} catch(std::experimental::filesystem::filesystem_error& e) {
		ASSERT_LOG(false, "File Error: " << e.what());
	}
}

COMMAND_LINE_UTILITY(window_test)
{
	int flags = 0;
	int width = 800, height = 600;

	SDL_Init(SDL_INIT_VIDEO);

	SDL_DisplayMode dm;
	int res = SDL_GetDesktopDisplayMode(0, &dm);
	if(res != 0) {
		fprintf(stderr, "Failed to query desktop display: %s\n", SDL_GetError());
	} else {
		fprintf(stderr, "Desktop display: %dx%d@%dhz format=%d\n", dm.w, dm.h, dm.refresh_rate, (int)dm.format);
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);

	std::deque<std::string> argv(args.begin(), args.end());
	while(argv.empty() == false) {
		std::string a = argv.front();
		argv.pop_front();
		if(a == "--fullscreen-exclusive") {
			flags = flags | SDL_WINDOW_FULLSCREEN;
		} else if(a == "--fullscreen-desktop") {
			flags = flags | SDL_WINDOW_FULLSCREEN_DESKTOP;
		} else if(a == "--opengl") {
			flags = flags | SDL_WINDOW_OPENGL;
		} else if(a == "--borderless") {
			flags = flags | SDL_WINDOW_BORDERLESS;
		} else if(a == "--highdpi") {
			flags = flags | SDL_WINDOW_ALLOW_HIGHDPI;
		} else if(a == "--gl_major") {
			ASSERT_LOG(argv.empty() == false, "No arg specified");
			std::string w = argv.front();
			argv.pop_front();
			SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, atoi(w.c_str()));
		} else if(a == "--gl_minor") {
			ASSERT_LOG(argv.empty() == false, "No arg specified");
			std::string w = argv.front();
			argv.pop_front();
			SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, atoi(w.c_str()));
		} else if(a == "--gl_depth") {
			ASSERT_LOG(argv.empty() == false, "No arg specified");
			std::string w = argv.front();
			argv.pop_front();
			SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, atoi(w.c_str()));
		} else if(a == "--gl_stencil") {
			ASSERT_LOG(argv.empty() == false, "No arg specified");
			std::string w = argv.front();
			argv.pop_front();
			SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, atoi(w.c_str()));
		} else if(a == "--gl_bpp") {
			ASSERT_LOG(argv.empty() == false, "No arg specified");
			std::string w = argv.front();
			argv.pop_front();
			SDL_GL_SetAttribute(SDL_GL_RED_SIZE, atoi(w.c_str()));
			SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, atoi(w.c_str()));
			SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, atoi(w.c_str()));
			SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, atoi(w.c_str()));
		} else if(a == "--gl_multisamplebuffers") {
			ASSERT_LOG(argv.empty() == false, "No arg specified");
			std::string w = argv.front();
			argv.pop_front();
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, atoi(w.c_str()));
		} else if(a == "--width") {
			ASSERT_LOG(argv.empty() == false, "No width specified");
			std::string w = argv.front();
			argv.pop_front();
			width = atoi(w.c_str());
		} else if(a == "--height") {
			ASSERT_LOG(argv.empty() == false, "No height specified");
			std::string w = argv.front();
			argv.pop_front();
			height = atoi(w.c_str());
		} else {
			ASSERT_LOG(false, "Unrecognized arg: " << a);
		}
	}

	SDL_Window* win = SDL_CreateWindow("Anura test window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags);
	if(win == nullptr) {
		fprintf(stderr, "Could not create window: %s\n", SDL_GetError());
		return;
	}

	auto context = SDL_GL_CreateContext(win);
	assert(context != nullptr);

	SDL_GL_SetSwapInterval(0);

	int prev = 0;
	for(int i = 0; i != 100000; ++i) {
		glClearColor(i%2 ? 0.05 : 0.0, 0.0, 0.0, 1.0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
		SDL_GL_SwapWindow(win);
		if(i%100 == 0) {
			int t = SDL_GetTicks();
			fprintf(stderr, "%d -> %fms\n", i, float((t - prev)/100.0f));
			prev = t;
		}
	}

	SDL_Delay(1000);
	SDL_DestroyWindow(win);
	SDL_Quit();
}

max_stars_repo_name: Greentwip/anura

max_issues_repo_name: Greentwip/anura

max_forks_repo_name: Greentwip/anura


text:
// Boost.Geometry

// Copyright (c) 2017, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_SRS_PROJECTIONS_ESRI_PARAMS_HPP
#define BOOST_GEOMETRY_SRS_PROJECTIONS_ESRI_PARAMS_HPP

#include <string>

#include <boost/geometry/srs/spheroid.hpp>

namespace boost { namespace geometry
{

namespace srs
{

struct esri
{
    explicit esri(int c)
        : code(c)
    {}

    int code;
};

template <int Code>
struct static_esri
{
    static const int code = Code;
};

} // namespace srs

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_ESRI_PARAMS_HPP

ext: hpp


text:
#define BOOST_TEST_MODULE TStoredQueryDef
#define BOOST_TEST_DYN_LINK 1
#include <boost/test/unit_test.hpp>

#include "StoredQueryParamDef.h"
#include "WfsException.h"
#include <macgyver/Exception.h>

using namespace boost::unit_test;

test_suite* init_unit_test_suite(int argc, char* argv[])
{
  const char* name = "StoredQueryParamDef tester";
  unit_test_log.set_threshold_level(log_messages);
  framework::master_test_suite().p_name.value = name;
  BOOST_TEST_MESSAGE("");
  BOOST_TEST_MESSAGE(name);
  BOOST_TEST_MESSAGE(std::string(std::strlen(name), '='));
  return NULL;
}

using namespace SmartMet;
using namespace SmartMet::Plugin::WFS;
using SmartMet::Spine::Value;

BOOST_AUTO_TEST_CASE(test_scalar_string_def)
{
  BOOST_TEST_MESSAGE("+ [StoredQueryParamDef] Testing getting scalar string parameter");
  StoredQueryParamDef param_def;
  param_def.parse_def("string");
  BOOST_CHECK(param_def.getValueType() == StoredQueryParamDef::STRING);
  BOOST_CHECK(!param_def.isArray());
  BOOST_CHECK(param_def.getMinSize() == 1);
  BOOST_CHECK(param_def.getMaxSize() == 1);

  Value value;
  std::string s1;
  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("foobar"));
  BOOST_CHECK(value.type() == typeid(std::string));
  BOOST_REQUIRE_NO_THROW(s1 = value.get_string());
  BOOST_CHECK_EQUAL(s1, std::string("foobar"));
}

BOOST_AUTO_TEST_CASE(test_scalar_int_def)
{
  BOOST_TEST_MESSAGE("+ [StoredQueryParamDef] Testing getting scalar int parameter");
  StoredQueryParamDef param_def;
  param_def.parse_def("int");
  BOOST_CHECK(param_def.getValueType() == StoredQueryParamDef::INT);
  BOOST_CHECK(!param_def.isArray());
  BOOST_CHECK(param_def.getMinSize() == 1);
  BOOST_CHECK(param_def.getMaxSize() == 1);

  Value value;
  int64_t i1;
  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("123"));
  BOOST_CHECK(value.type() == typeid(int64_t));
  BOOST_REQUIRE_NO_THROW(i1 = value.get_int());
  BOOST_CHECK_EQUAL(i1, (int64_t)123);

  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("-321"));
  BOOST_CHECK(value.type() == typeid(int64_t));
  BOOST_REQUIRE_NO_THROW(i1 = value.get_int());
  BOOST_CHECK_EQUAL(i1, (int64_t)(-321));

  BOOST_CHECK_THROW(value = param_def.readValue("1.2"), Fmi::Exception);
  BOOST_CHECK_THROW(value = param_def.readValue("foo"), Fmi::Exception);
}

BOOST_AUTO_TEST_CASE(test_scalar_bool_def)
{
  BOOST_TEST_MESSAGE("+ [StoredQueryParamDef] Testing getting scalar boolean parameter");
  StoredQueryParamDef param_def;
  param_def.parse_def("bool");
  BOOST_CHECK(param_def.getValueType() == StoredQueryParamDef::BOOL);
  BOOST_CHECK(!param_def.isArray());
  BOOST_CHECK(param_def.getMinSize() == 1);
  BOOST_CHECK(param_def.getMaxSize() == 1);

  Value value;
  bool b1;
  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("true"));
  BOOST_CHECK(value.type() == typeid(bool));
  BOOST_REQUIRE_NO_THROW(b1 = value.get_bool());
  BOOST_CHECK_EQUAL(b1, true);

  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("false"));
  BOOST_CHECK(value.type() == typeid(bool));
  BOOST_REQUIRE_NO_THROW(b1 = value.get_bool());
  BOOST_CHECK_EQUAL(b1, false);

  BOOST_CHECK_THROW(value = param_def.readValue("1.2"), Fmi::Exception);
  BOOST_CHECK_THROW(value = param_def.readValue("foo"), Fmi::Exception);
}

BOOST_AUTO_TEST_CASE(test_scalar_uint_def)
{
  BOOST_TEST_MESSAGE("+ [StoredQueryParamDef] Testing getting scalar unsigned int parameter");
  StoredQueryParamDef param_def;
  param_def.parse_def("uint");
  BOOST_CHECK(param_def.getValueType() == StoredQueryParamDef::UINT);
  BOOST_CHECK(!param_def.isArray());
  BOOST_CHECK(param_def.getMinSize() == 1);
  BOOST_CHECK(param_def.getMaxSize() == 1);

  Value value;
  uint64_t u1;
  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("123"));
  BOOST_REQUIRE(value.type() == typeid(uint64_t));
  BOOST_REQUIRE_NO_THROW(u1 = value.get_uint());
  BOOST_CHECK_EQUAL(u1, (uint64_t)123);

  // FIXME: Fails to throw due to implementation of boost::lexical_cast<>
  // BOOST_CHECK_THROW(value = param_def.readValue("-321"), Fmi::Exception);
  BOOST_CHECK_THROW(value = param_def.readValue("1.2"), Fmi::Exception);
  BOOST_REQUIRE_THROW(value = param_def.readValue("foo"), Fmi::Exception);
}

BOOST_AUTO_TEST_CASE(test_scalar_double_def)
{
  BOOST_TEST_MESSAGE("+ [StoredQueryParamDef] Testing getting scalar double parameter");
  StoredQueryParamDef param_def;
  param_def.parse_def("double");
  BOOST_CHECK(param_def.getValueType() == StoredQueryParamDef::DOUBLE);
  BOOST_CHECK(!param_def.isArray());
  BOOST_CHECK(param_def.getMinSize() == 1);
  BOOST_CHECK(param_def.getMaxSize() == 1);

  Value value;
  double d1;
  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("123"));
  BOOST_REQUIRE(value.type() == typeid(double));
  BOOST_REQUIRE_NO_THROW(d1 = value.get_double());
  BOOST_CHECK_CLOSE_FRACTION(d1, (double)123, 1e-10);

  BOOST_REQUIRE_NO_THROW(value = param_def.readValue("-1.2"));
  BOOST_REQUIRE(value.type() == typeid(double));
  BOOST_REQUIRE_NO_THROW(d1 = value.get_double());
  BOOST_CHECK_CLOSE_FRACTION(d1, (double)(-1.2), 1e-10);

  BOOST_REQUIRE_THROW(value = param_def.readValue("foo"), Fmi::Exception);
}

BOOST_AUTO_TEST_CASE(test_scalar_time_def)
{
  StoredQueryParamDef param_def;
  BOOST_TEST_MESSAGE(
      "+ [StoredQueryParamDef] Testing getting scalar boost::posix_time::ptime parameter");
  param_def.parse_def("time");
  BOOST_CHECK(param_def.getValueType() == StoredQueryParamDef::TIME);
  BOOST_CHECK(!param_def.isArray());
  BOOST_CHECK(param_def.getMinSize() == 1);
  BOOST_CHECK(param_def.getMaxSize() == 1);
}

max_stars_repo_name: nakkim/smartmet-plugin-wfs

max_issues_repo_name: nakkim/smartmet-plugin-wfs

max_forks_repo_name: nakkim/smartmet-plugin-wfs


text:
// Copyright 2021 LeoDrive.
//
// 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.

// Developed by LeoDrive, 2021

#ifndef IO_CONTEXT__IO_CONTEXT_HPP_
#define IO_CONTEXT__IO_CONTEXT_HPP_

#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>

#include <memory>

namespace autoware
{

namespace drivers
{

class IoContext : private boost::noncopyable
{
public:
  explicit IoContext(size_t threads_count = -1);
  ~IoContext();

  boost::asio::io_service & ios() const;

  bool isServiceStopped();
  uint32_t serviceThreadCount();

  void waitForExit();

  template<class F>
  void post(F f)
  {
    ios().post(f);
  }

private:
  std::shared_ptr<boost::asio::io_service> m_ios;
  std::shared_ptr<boost::asio::io_service::work> m_work;
  std::shared_ptr<boost::thread_group> m_ios_thread_workers;
};

}  // namespace drivers
}  // namespace autoware

#endif  // IO_CONTEXT__IO_CONTEXT_HPP_


text:
// Copyright (c) 2002-2016, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 <dp/Assert.h>
#include <dp/util/PlugIn.h>
#include <dp/util/File.h>
#include <boost/tokenizer.hpp>
#include <algorithm>

#if !defined( NDEBUG )
#include <stdio.h>
#if defined( MSVC )
#include <strsafe.h>
#endif
#endif

#include <cstring>

using std::make_pair;
using std::unique;
using std::vector;
using std::string;

namespace dp
{
  namespace util
  {
    UPITID::UPITID(unsigned short pit, const char verStr[16])
    : data0(pit)
    {
      strncpy(data1, verStr, 15);
      data1[15] = '\0'; // terminate
    }

    UPITID::UPITID(const UPITID& rhs)
    {
      memcpy(this, &rhs, sizeof(UPITID));
    }

    UPIID::UPIID(const char idstr[16], UPITID pitid)
    : data1(pitid)
    {
      strncpy(data0, idstr, 15);
      data0[15] = '\0'; // terminate
    }

    UPIID& UPIID::operator=(const UPIID& rhs)
    {
      if (&rhs != this)
      {
        memcpy(this, &rhs, sizeof(UPIID));
      }
      return *this;
    }

    PlugInServer::PlugInServer()
    :m_filter(LibExtStr)
    {
    }

    PlugInServer::~PlugInServer()
    {
      // release all PlugIns
      m_plugIns.clear();
    }

    void PlugInServer::gatherPlugIns( dp::util::FileFinder const& fileFinder )
    {
      std::vector<std::string> plugInFiles;
      findPlugIns( fileFinder, plugInFiles );

      for ( std::vector<std::string>::const_iterator it = plugInFiles.begin() ; it != plugInFiles.end() ; ++it )
      {
        DynamicLibrarySharedPtr dynamicLibrary = DynamicLibrary::createFromFile(it->c_str());

        if ( dynamicLibrary )
        {
          PFNQUERYPLUGINTERFACEPIIDS pfnQueryPlugInterfacePIIDs = (PFNQUERYPLUGINTERFACEPIIDS)dynamicLibrary->getSymbol("queryPlugInterfacePIIDs");
          if ( pfnQueryPlugInterfacePIIDs )
          {
            std::vector<UPIID> upiids;
            (*pfnQueryPlugInterfacePIIDs)(upiids);

            for ( std::vector<UPIID>::const_iterator upiidit = upiids.begin() ; upiidit != upiids.end() ; ++upiidit )
            {
              m_plugIns[*upiidit].fileName = *it;
            }
          }
        }
      }
    }

    bool PlugInServer::getInterfaceImpl(dp::util::FileFinder const& fileFinder, const UPIID& piid, dp::util::PlugInSharedPtr & plugIn)
    {
      plugIn.reset();
      if ( m_unsupportedUPIIDs.find( piid ) == m_unsupportedUPIIDs.end() )
      {
        PlugInMap::iterator plugInMapIt = m_plugIns.find( piid );
        if ( plugInMapIt == m_plugIns.end() )
        {
          gatherPlugIns( fileFinder );
          plugInMapIt = m_plugIns.find( piid );
        }
        if ( plugInMapIt != m_plugIns.end() )
        {
          if ( !plugInMapIt->second.pfnGetPlugInterface )
          {
            DynamicLibrarySharedPtr dynamicLibrary = DynamicLibrary::createFromFile(plugInMapIt->second.fileName.c_str());
            if ( dynamicLibrary )
            {
              PFNGETPLUGINTERFACE pfnGetPlugInterface = (PFNGETPLUGINTERFACE)dynamicLibrary->getSymbol("getPlugInterface");
              if ( pfnGetPlugInterface )
              {
                plugInMapIt->second.dynamicLibrary = dynamicLibrary;
                plugInMapIt->second.pfnGetPlugInterface = pfnGetPlugInterface;
              }
            }
          }
          if ( plugInMapIt->second.pfnGetPlugInterface )
          {
            // TODO keep reference to DynamicLibrary inside plugin to ensure that the cleanup order is always correct
            DP_VERIFY( (*plugInMapIt->second.pfnGetPlugInterface)( piid, plugIn ) );
          }
          else
          {
            m_unsupportedUPIIDs.insert( piid );
          }
        }
      }
      return( !!plugIn );
    }

    bool PlugInServer::queryInterfaceTypeImpl(const vector<string>& searchPath, const UPITID& pitid, vector<UPIID>& piids)
    {
      piids.clear();

      // TODO actually calling function needs to call gather plugins each time a new search path has been added...
      if ( m_plugIns.empty() )
      {
        gatherPlugIns( dp::util::FileFinder( searchPath ) );
      }

      for ( PlugInMap::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
      {
        if ( it->first.getPlugInterfaceType() == pitid )
        {
          piids.push_back(it->first);
        }
      }
      return( !piids.empty() );
    }

    void PlugInServer::releaseInterfaceImpl(const UPIID& piid)
    {
      PlugInMap::iterator it = m_plugIns.find( piid );
      if ( it != m_plugIns.end() )
      {
        if ( it->second.dynamicLibrary )
        {
          it->second.dynamicLibrary.reset();
          it->second.pfnGetPlugInterface = 0;
        }
      }
    }

    /* set file filter specified by filter */
    void PlugInServer::setFileFilterImpl(const std::string& filter)
    {
      if ( !filter.empty() )
      {
        m_filter = filter;
      }
    }

    bool PlugInServer::findPlugIns(dp::util::FileFinder const& fileFinder, vector<string>& plugIns)
    {
      plugIns.clear();
      dp::util::FileFinder localFF( fileFinder );
      localFF.addSearchPaths( getPlugInSearchPath() );

      boost::tokenizer<boost::char_separator<char>> tokenizer( m_filter, boost::char_separator<char>( ";" ) );
      for ( boost::tokenizer<boost::char_separator<char>>::const_iterator it = tokenizer.begin(); it != tokenizer.end() ; ++it )
      {
        findFiles( it->substr( 1 ), localFF.getSearchPaths(), plugIns );
      }

      return !plugIns.empty();
    }

    bool getInterface(dp::util::FileFinder const& fileFinder, const UPIID& piid, dp::util::PlugInSharedPtr & plugIn)
    {
      // call the singleton's implementation
      return PIS::instance()->getInterfaceImpl(fileFinder, piid, plugIn);
    }

    bool queryInterfaceType(const std::vector<std::string>& searchPath, const UPITID& pitid, std::vector<UPIID>& piids)
    {
      // call the singleton's implementation
      return PIS::instance()->queryInterfaceTypeImpl(searchPath, pitid, piids);
    }

    /* release the interface identified by piid */
    void releaseInterface(const UPIID& piid)
    {
      // call the singleton's implementation
      PIS::instance()->releaseInterfaceImpl(piid);
    }

    /* set file filter specified by filter */
    void setPlugInFileFilter(const std::string& filter)
    {
      // call the singleton's implementation
      PIS::instance()->setFileFilterImpl(filter);
    }

    void addPlugInSearchPath(const std::string& path)
    {
      PIS::instance()->m_searchPath.push_back(path);
      DP_ASSERT(PIS::instance()->m_searchPath.size()>0);
    }

    const std::vector<string>& getPlugInSearchPath()
    {
      DP_ASSERT(PIS::instance()->m_searchPath.size()>0);
      return PIS::instance()->m_searchPath;
    }
  } // namespace util
} // namespace dp

max_stars_repo_name: asuessenbach/pipeline

max_issues_repo_name: asuessenbach/pipeline

max_forks_repo_name: asuessenbach/pipeline


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/assert.hpp>
#include <boost/hana/ext/std/integral_constant.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>

#include <cassert>
#include <iostream>
#include <string>
#include <tuple>
#include <type_traits>

#include <boost/mpl/if.hpp>
#include <boost/mpl/quote.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/equal.hpp>
using namespace boost::hana;

int main() {

{

//! [type]
// We "lift" the `int` type to a value, and the `std::add_pointer` metafunction
// to a regular function. Then, we can call that metafunction with a regular
// function call syntax.
constexpr auto t = type<int>;
constexpr auto add_pointer = metafunction<std::add_pointer>;
static_assert(add_pointer(t) == type<int*>, "");
//! [type]

//! [type_as_nullary_metafunction]
using T = decltype(t)::type;
static_assert(std::is_same<T, int>{}, "");
//! [type_as_nullary_metafunction]

}{

//! [type_sequence]
constexpr auto types = make<Tuple>(type<int>, type<char const>, type<void>);
static_assert(
    transform(types, metafunction<std::add_pointer>) ==
    make<Tuple>(type<int*>, type<char const*>, type<void*>)
, "");
//! [type_sequence]

}{

//! [tuple_t]
constexpr auto types = tuple_t<int, char const, void>;
static_assert(types == make<Tuple>(type<int>, type<char const>, type<void>), "");

static_assert(
    transform(types, metafunction<std::add_pointer>) ==
    tuple_t<int*, char const*, void*>
, "");
//! [tuple_t]

}{

//! [type_three_step_cumbersome]
static_assert(std::is_same<
    decltype(metafunction<std::add_pointer>(type<int>))::type,
    int*
>{}, "");
//! [type_three_step_cumbersome]

//! [type_three_step_alternative]
static_assert(std::is_same<
    std::add_pointer<int>::type,
    int*
>{}, "");
//! [type_three_step_alternative]

}{

//! [apply_to_all]
auto apply_to_all = [](auto sequences, auto f) {
    return transform(sequences, [=](auto sequence) {
        return transform(sequence, f);
    });
};

constexpr auto types = make<Tuple>(
    tuple_t<int, char>,
    tuple_t<void, std::string, double>
);

BOOST_HANA_CONSTANT_CHECK(
    apply_to_all(types, metafunction<std::add_pointer>) ==
    make<Tuple>(
        tuple_t<int*, char*>,
        tuple_t<void*, std::string*, double*>
    )
);
//! [apply_to_all]

}

}

namespace mpl = boost::mpl;
//! [apply_to_all_mpl]
template <typename Sequences, typename F>
struct apply_to_all
    : mpl::transform<
        Sequences,
        mpl::transform<mpl::_1, F>
    >
{ };

using types = mpl::vector<
    mpl::vector<int, char>,
    mpl::vector<void, std::string, double>
>;

static_assert(mpl::equal<
    apply_to_all<types, mpl::quote1<std::add_pointer>>::type,
    mpl::vector<
        mpl::vector<int*, char*>,
        mpl::vector<void*, std::string*, double*>
    >,

    // mpl::equal was seemingly not designed for deep comparisons, so we
    // need this tricky line for it to do what we want.
    mpl::equal<mpl::_1, mpl::_2, mpl::quote2<std::is_same>>
>{}, "");
//! [apply_to_all_mpl]

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
// Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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.

#define JC_TEST_IMPLEMENTATION
#include <jc_test/jc_test.h>

#include <map>

#include <dlib/dstrings.h>
#include <dlib/hash.h>

#include <resource/resource.h>

#include "../gameobject.h"
#include "../gameobject_private.h"
#include "../script.h"

#include "gameobject/test/component/test_gameobject_component_ddf.h"

class ComponentTest : public jc_test_base_class
{
protected:
    virtual void SetUp()
    {
        m_UpdateCount = 0;
        m_UpdateContext.m_DT = 1.0f / 60.0f;

        dmResource::NewFactoryParams params;
        params.m_MaxResources = 16;
        params.m_Flags = RESOURCE_FACTORY_FLAGS_EMPTY;
        m_Factory = dmResource::NewFactory(&params, "build/default/src/gameobject/test/component");
        m_ScriptContext = dmScript::NewContext(0, 0, true);
        dmScript::Initialize(m_ScriptContext);
        m_Register = dmGameObject::NewRegister();
        dmGameObject::Initialize(m_Register, m_ScriptContext);

        m_Contexts.SetCapacity(7,16);
        m_Contexts.Put(dmHashString64("goc"), m_Register);
        m_Contexts.Put(dmHashString64("collectionc"), m_Register);
        m_Contexts.Put(dmHashString64("scriptc"), m_ScriptContext);
        m_Contexts.Put(dmHashString64("luac"), &m_ModuleContext);
        dmResource::RegisterTypes(m_Factory, &m_Contexts);

        dmGameObject::ComponentTypeCreateCtx component_create_ctx = {};
        component_create_ctx.m_Script = m_ScriptContext;
        component_create_ctx.m_Register = m_Register;
        component_create_ctx.m_Factory = m_Factory;
        dmGameObject::CreateRegisteredComponentTypes(&component_create_ctx);
        dmGameObject::SortComponentTypes(m_Register);

        m_Collection = dmGameObject::NewCollection("collection", m_Factory, m_Register, 1024, 0x0);

        // Register dummy physical resource type
        dmResource::Result e;
        e = dmResource::RegisterType(m_Factory, "a", this, 0, ACreate, 0, ADestroy, 0);
        ASSERT_EQ(dmResource::RESULT_OK, e);
        e = dmResource::RegisterType(m_Factory, "b", this, 0, BCreate, 0, BDestroy, 0);
        ASSERT_EQ(dmResource::RESULT_OK, e);
        e = dmResource::RegisterType(m_Factory, "c", this, 0, CCreate, 0, CDestroy, 0);
        ASSERT_EQ(dmResource::RESULT_OK, e);

        dmResource::ResourceType resource_type;
        dmGameObject::Result result;

        // A has component_user_data
        e = dmResource::GetTypeFromExtension(m_Factory, "a", &resource_type);
        ASSERT_EQ(dmResource::RESULT_OK, e);
        dmGameObject::ComponentType a_type;
        a_type.m_Name = "a";
        a_type.m_ResourceType = resource_type;
        a_type.m_Context = this;
        a_type.m_CreateFunction = AComponentCreate;
        a_type.m_InitFunction = AComponentInit;
        a_type.m_AddToUpdateFunction = AComponentAddToUpdate;
        a_type.m_FinalFunction = AComponentFinal;
        a_type.m_DestroyFunction = AComponentDestroy;
        a_type.m_UpdateFunction = AComponentsUpdate;
        a_type.m_InstanceHasUserData = true;
        result = dmGameObject::RegisterComponentType(m_Register, a_type);
        dmGameObject::SetUpdateOrderPrio(m_Register, resource_type, 2);
        ASSERT_EQ(dmGameObject::RESULT_OK, result);

        // B has *not* component_user_data
        e = dmResource::GetTypeFromExtension(m_Factory, "b", &resource_type);
        ASSERT_EQ(dmResource::RESULT_OK, e);
        dmGameObject::ComponentType b_type;
        b_type.m_Name = "b";
        b_type.m_ResourceType = resource_type;
        b_type.m_Context = this;
        b_type.m_CreateFunction = BComponentCreate;
        b_type.m_InitFunction = BComponentInit;
        b_type.m_AddToUpdateFunction = BComponentAddToUpdate;
        b_type.m_FinalFunction = BComponentFinal;
        b_type.m_DestroyFunction = BComponentDestroy;
        b_type.m_UpdateFunction = BComponentsUpdate;
        result = dmGameObject::RegisterComponentType(m_Register, b_type);
        dmGameObject::SetUpdateOrderPrio(m_Register, resource_type, 1);
        ASSERT_EQ(dmGameObject::RESULT_OK, result);

        // C has component_user_data
        e = dmResource::GetTypeFromExtension(m_Factory, "c", &resource_type);
        ASSERT_EQ(dmResource::RESULT_OK, e);
        dmGameObject::ComponentType c_type;
        c_type.m_Name = "c";
        c_type.m_ResourceType = resource_type;
        c_type.m_Context = this;
        c_type.m_CreateFunction = CComponentCreate;
        c_type.m_InitFunction = CComponentInit;
        c_type.m_AddToUpdateFunction = CComponentAddToUpdate;
        c_type.m_FinalFunction = CComponentFinal;
        c_type.m_DestroyFunction = CComponentDestroy;
        c_type.m_UpdateFunction = CComponentsUpdate;
        c_type.m_InstanceHasUserData = true;
        result = dmGameObject::RegisterComponentType(m_Register, c_type);
        dmGameObject::SetUpdateOrderPrio(m_Register, resource_type, 0);
        ASSERT_EQ(dmGameObject::RESULT_OK, result);

        dmGameObject::SortComponentTypes(m_Register);

        m_MaxComponentCreateCountMap[TestGameObjectDDF::AResource::m_DDFHash] = 1000000;
    }

    virtual void TearDown()
    {
        dmGameObject::DeleteCollection(m_Collection);
        dmGameObject::PostUpdate(m_Register);
        dmScript::Finalize(m_ScriptContext);
        dmScript::DeleteContext(m_ScriptContext);
        dmGameObject::DeleteRegister(m_Register);
        dmResource::DeleteFactory(m_Factory);
    }

    static dmResource::FResourceCreate          ACreate;
    static dmResource::FResourceDestroy         ADestroy;
    static dmGameObject::ComponentCreate        AComponentCreate;
    static dmGameObject::ComponentInit          AComponentInit;
    static dmGameObject::ComponentFinal         AComponentFinal;
    static dmGameObject::ComponentDestroy       AComponentDestroy;
    static dmGameObject::ComponentAddToUpdate   AComponentAddToUpdate;
    static dmGameObject::ComponentsUpdate       AComponentsUpdate;

    static dmResource::FResourceCreate          BCreate;
    static dmResource::FResourceDestroy         BDestroy;
    static dmGameObject::ComponentCreate        BComponentCreate;
    static dmGameObject::ComponentInit          BComponentInit;
    static dmGameObject::ComponentFinal         BComponentFinal;
    static dmGameObject::ComponentDestroy       BComponentDestroy;
    static dmGameObject::ComponentAddToUpdate   BComponentAddToUpdate;
    static dmGameObject::ComponentsUpdate       BComponentsUpdate;

    static dmResource::FResourceCreate          CCreate;
    static dmResource::FResourceDestroy         CDestroy;
    static dmGameObject::ComponentCreate        CComponentCreate;
    static dmGameObject::ComponentInit          CComponentInit;
    static dmGameObject::ComponentFinal         CComponentFinal;
    static dmGameObject::ComponentDestroy       CComponentDestroy;
    static dmGameObject::ComponentAddToUpdate   CComponentAddToUpdate;
    static dmGameObject::ComponentsUpdate       CComponentsUpdate;

public:
    uint32_t                     m_UpdateCount;
    std::map<uint64_t, uint32_t> m_CreateCountMap;
    std::map<uint64_t, uint32_t> m_DestroyCountMap;

    std::map<uint64_t, uint32_t> m_ComponentCreateCountMap;
    std::map<uint64_t, uint32_t> m_ComponentInitCountMap;
    std::map<uint64_t, uint32_t> m_ComponentFinalCountMap;
    std::map<uint64_t, uint32_t> m_ComponentDestroyCountMap;
    std::map<uint64_t, uint32_t> m_ComponentUpdateCountMap;
    std::map<uint64_t, uint32_t> m_ComponentAddToUpdateCountMap;
    std::map<uint64_t, uint32_t> m_MaxComponentCreateCountMap;

    std::map<uint64_t, uint32_t> m_ComponentUpdateOrderMap;

    std::map<uint64_t, int>      m_ComponentUserDataAcc;

    dmScript::HContext m_ScriptContext;
    dmGameObject::UpdateContext m_UpdateContext;
    dmGameObject::HRegister m_Register;
    dmGameObject::HCollection m_Collection;
    dmResource::HFactory m_Factory;
    dmGameObject::ModuleContext m_ModuleContext;
    dmHashTable64<void*> m_Contexts;
};

template <typename T>
dmResource::Result GenericDDFCreate(const dmResource::ResourceCreateParams& params)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;
    game_object_test->m_CreateCountMap[T::m_DDFHash]++;

    T* obj;
    dmDDF::Result e = dmDDF::LoadMessage<T>(params.m_Buffer, params.m_BufferSize, &obj);
    if (e == dmDDF::RESULT_OK)
    {
        params.m_Resource->m_Resource = (void*) obj;
        return dmResource::RESULT_OK;
    }
    else
    {
        return dmResource::RESULT_FORMAT_ERROR;
    }
}

template <typename T>
dmResource::Result GenericDDFDestory(const dmResource::ResourceDestroyParams& params)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;
    game_object_test->m_DestroyCountMap[T::m_DDFHash]++;

    dmDDF::FreeMessage((void*) params.m_Resource->m_Resource);
    return dmResource::RESULT_OK;
}

template <typename T, int add_to_user_data>
static dmGameObject::CreateResult GenericComponentCreate(const dmGameObject::ComponentCreateParams& params)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;

    if (params.m_UserData && add_to_user_data != -1)
    {
        *params.m_UserData += add_to_user_data;
    }

    if (game_object_test->m_MaxComponentCreateCountMap.find(T::m_DDFHash) != game_object_test->m_MaxComponentCreateCountMap.end())
    {
        if (game_object_test->m_ComponentCreateCountMap[T::m_DDFHash] >= game_object_test->m_MaxComponentCreateCountMap[T::m_DDFHash])
        {
            return dmGameObject::CREATE_RESULT_UNKNOWN_ERROR;
        }
    }

    game_object_test->m_ComponentCreateCountMap[T::m_DDFHash]++;
    return dmGameObject::CREATE_RESULT_OK;
}

template <typename T>
static dmGameObject::CreateResult GenericComponentInit(const dmGameObject::ComponentInitParams& params)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;
    game_object_test->m_ComponentInitCountMap[T::m_DDFHash]++;
    return dmGameObject::CREATE_RESULT_OK;
}

template <typename T>
static dmGameObject::CreateResult GenericComponentFinal(const dmGameObject::ComponentFinalParams& params)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;
    game_object_test->m_ComponentFinalCountMap[T::m_DDFHash]++;
    return dmGameObject::CREATE_RESULT_OK;
}

template <typename T>
static dmGameObject::CreateResult GenericComponentAddToUpdate(const dmGameObject::ComponentAddToUpdateParams& params)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;
    game_object_test->m_ComponentAddToUpdateCountMap[T::m_DDFHash]++;
    return dmGameObject::CREATE_RESULT_OK;
}

template <typename T>
static dmGameObject::UpdateResult GenericComponentsUpdate(const dmGameObject::ComponentsUpdateParams& params, dmGameObject::ComponentsUpdateResult& update_result)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;
    game_object_test->m_ComponentUpdateCountMap[T::m_DDFHash]++;
    game_object_test->m_ComponentUpdateOrderMap[T::m_DDFHash] = game_object_test->m_UpdateCount++;
    return dmGameObject::UPDATE_RESULT_OK;
}

template <typename T>
static dmGameObject::CreateResult GenericComponentDestroy(const dmGameObject::ComponentDestroyParams& params)
{
    ComponentTest* game_object_test = (ComponentTest*) params.m_Context;
    if (params.m_UserData)
    {
        game_object_test->m_ComponentUserDataAcc[T::m_DDFHash] += *params.m_UserData;
    }

    game_object_test->m_ComponentDestroyCountMap[T::m_DDFHash]++;
    return dmGameObject::CREATE_RESULT_OK;
}

dmResource::FResourceCreate ComponentTest::ACreate                      = GenericDDFCreate<TestGameObjectDDF::AResource>;
dmResource::FResourceDestroy ComponentTest::ADestroy                    = GenericDDFDestory<TestGameObjectDDF::AResource>;
dmGameObject::ComponentCreate ComponentTest::AComponentCreate           = GenericComponentCreate<TestGameObjectDDF::AResource, 1>;
dmGameObject::ComponentInit ComponentTest::AComponentInit               = GenericComponentInit<TestGameObjectDDF::AResource>;
dmGameObject::ComponentFinal ComponentTest::AComponentFinal             = GenericComponentFinal<TestGameObjectDDF::AResource>;
dmGameObject::ComponentDestroy ComponentTest::AComponentDestroy         = GenericComponentDestroy<TestGameObjectDDF::AResource>;
dmGameObject::ComponentAddToUpdate ComponentTest::AComponentAddToUpdate = GenericComponentAddToUpdate<TestGameObjectDDF::AResource>;
dmGameObject::ComponentsUpdate ComponentTest::AComponentsUpdate         = GenericComponentsUpdate<TestGameObjectDDF::AResource>;

dmResource::FResourceCreate ComponentTest::BCreate                      = GenericDDFCreate<TestGameObjectDDF::BResource>;
dmResource::FResourceDestroy ComponentTest::BDestroy                    = GenericDDFDestory<TestGameObjectDDF::BResource>;
dmGameObject::ComponentCreate ComponentTest::BComponentCreate           = GenericComponentCreate<TestGameObjectDDF::BResource, -1>;
dmGameObject::ComponentInit ComponentTest::BComponentInit               = GenericComponentInit<TestGameObjectDDF::BResource>;
dmGameObject::ComponentFinal ComponentTest::BComponentFinal             = GenericComponentFinal<TestGameObjectDDF::BResource>;
dmGameObject::ComponentDestroy ComponentTest::BComponentDestroy         = GenericComponentDestroy<TestGameObjectDDF::BResource>;
dmGameObject::ComponentAddToUpdate ComponentTest::BComponentAddToUpdate = GenericComponentAddToUpdate<TestGameObjectDDF::BResource>;
dmGameObject::ComponentsUpdate ComponentTest::BComponentsUpdate         = GenericComponentsUpdate<TestGameObjectDDF::BResource>;

dmResource::FResourceCreate ComponentTest::CCreate                      = GenericDDFCreate<TestGameObjectDDF::CResource>;
dmResource::FResourceDestroy ComponentTest::CDestroy                    = GenericDDFDestory<TestGameObjectDDF::CResource>;
dmGameObject::ComponentCreate ComponentTest::CComponentCreate           = GenericComponentCreate<TestGameObjectDDF::CResource, 10>;
dmGameObject::ComponentInit ComponentTest::CComponentInit               = GenericComponentInit<TestGameObjectDDF::CResource>;
dmGameObject::ComponentFinal ComponentTest::CComponentFinal             = GenericComponentFinal<TestGameObjectDDF::CResource>;
dmGameObject::ComponentDestroy ComponentTest::CComponentDestroy         = GenericComponentDestroy<TestGameObjectDDF::CResource>;
dmGameObject::ComponentAddToUpdate ComponentTest::CComponentAddToUpdate = GenericComponentAddToUpdate<TestGameObjectDDF::CResource>;
dmGameObject::ComponentsUpdate ComponentTest::CComponentsUpdate         = GenericComponentsUpdate<TestGameObjectDDF::CResource>;

TEST_F(ComponentTest, TestUpdate)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go1.goc");
    ASSERT_NE((void*) 0, (void*) go);
    dmGameObject::Init(m_Collection);
    bool ret = dmGameObject::Update(m_Collection, &m_UpdateContext);
    ASSERT_TRUE(ret);
    ret = dmGameObject::PostUpdate(m_Collection);
    ASSERT_TRUE(ret);

    dmGameObject::Delete(m_Collection, go, false);
    ret = dmGameObject::PostUpdate(m_Collection);
    ASSERT_TRUE(ret);
    ASSERT_EQ((uint32_t) 1, m_CreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_DestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentCreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentInitCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentAddToUpdateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentUpdateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentFinalCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentDestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
}

TEST_F(ComponentTest, TestPostDeleteUpdate)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go1.goc");
    ASSERT_NE((void*) 0, (void*) go);
    ASSERT_EQ(dmGameObject::RESULT_OK, dmGameObject::SetIdentifier(m_Collection, go, "go1"));

    dmhash_t message_id = dmHashString64("test");
    dmMessage::URL receiver;
    receiver.m_Socket = dmGameObject::GetMessageSocket(m_Collection);
    receiver.m_Path = dmGameObject::GetIdentifier(go);
    receiver.m_Fragment = dmHashString64("script");
    ASSERT_EQ(dmMessage::RESULT_OK, dmMessage::Post(0x0, &receiver, message_id, 0, 0, 0x0, 0, 0));

    dmGameObject::Delete(m_Collection, go, false);

    bool ret = dmGameObject::Update(m_Collection, &m_UpdateContext);
    ASSERT_TRUE(ret);

    ASSERT_TRUE(dmGameObject::PostUpdate(m_Collection));
}

TEST_F(ComponentTest, TestNonexistingComponent)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go2.goc");
    ASSERT_EQ((void*) 0, (void*) go);
    ASSERT_EQ((uint32_t) 0, m_CreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 0, m_DestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);

    ASSERT_EQ((uint32_t) 0, m_ComponentCreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 0, m_ComponentDestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
}

TEST_F(ComponentTest, TestPartialNonexistingComponent1)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go3.goc");
    ASSERT_EQ((void*) 0, (void*) go);

    // First one exists
    ASSERT_EQ((uint32_t) 1, m_CreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_DestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    // Even though the first a-component exits the prototype creation should fail before creating components
    ASSERT_EQ((uint32_t) 0, m_ComponentCreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 0, m_ComponentDestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
}

TEST_F(ComponentTest, TestPartialFailingComponent)
{
    // Only succeed creating the first component
    m_MaxComponentCreateCountMap[TestGameObjectDDF::AResource::m_DDFHash] = 1;
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go4.goc");
    ASSERT_EQ((void*) 0, (void*) go);

    ASSERT_EQ((uint32_t) 1, m_CreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_DestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);

    // One component should get created
    ASSERT_EQ((uint32_t) 1, m_ComponentCreateCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentDestroyCountMap[TestGameObjectDDF::AResource::m_DDFHash]);
}

TEST_F(ComponentTest, TestComponentUserdata)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go5.goc");
    ASSERT_NE((void*) 0, (void*) go);

    dmGameObject::Delete(m_Collection, go, false);
    bool ret = dmGameObject::PostUpdate(m_Collection);
    ASSERT_TRUE(ret);
    // Two a:s
    ASSERT_EQ(2, m_ComponentUserDataAcc[TestGameObjectDDF::AResource::m_DDFHash]);
    // Zero c:s
    ASSERT_EQ(0, m_ComponentUserDataAcc[TestGameObjectDDF::BResource::m_DDFHash]);
    // Three c:s
    ASSERT_EQ(30, m_ComponentUserDataAcc[TestGameObjectDDF::CResource::m_DDFHash]);
}

TEST_F(ComponentTest, TestUpdateOrder)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go1.goc");
    ASSERT_NE((void*) 0, (void*) go);
    bool ret = dmGameObject::Update(m_Collection, &m_UpdateContext);
    ASSERT_TRUE(ret);
    ASSERT_EQ((uint32_t) 2, m_ComponentUpdateOrderMap[TestGameObjectDDF::AResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 1, m_ComponentUpdateOrderMap[TestGameObjectDDF::BResource::m_DDFHash]);
    ASSERT_EQ((uint32_t) 0, m_ComponentUpdateOrderMap[TestGameObjectDDF::CResource::m_DDFHash]);
    dmGameObject::Delete(m_Collection, go, false);
}

TEST_F(ComponentTest, TestDuplicatedIds)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go6.goc");
    ASSERT_EQ((void*) 0, (void*) go);
}

TEST_F(ComponentTest, TestIndexId)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/go1.goc");

    uint16_t component_index;
    ASSERT_EQ(dmGameObject::RESULT_OK, dmGameObject::GetComponentIndex(go, dmHashString64("script"), &component_index));
    ASSERT_EQ(0u, component_index);
    ASSERT_EQ(dmGameObject::RESULT_OK, dmGameObject::GetComponentIndex(go, dmHashString64("a"), &component_index));
    ASSERT_EQ(1u, component_index);
    dmhash_t component_id;
    ASSERT_EQ(dmGameObject::RESULT_OK, dmGameObject::GetComponentId(go, 0, &component_id));
    ASSERT_EQ(dmHashString64("script"), component_id);
    ASSERT_EQ(dmGameObject::RESULT_OK, dmGameObject::GetComponentId(go, 1, &component_id));
    ASSERT_EQ(dmHashString64("a"), component_id);
    ASSERT_EQ(dmGameObject::RESULT_COMPONENT_NOT_FOUND, dmGameObject::GetComponentIndex(go, dmHashString64("does_not_exist"), &component_index));
    ASSERT_EQ(dmGameObject::RESULT_COMPONENT_NOT_FOUND, dmGameObject::GetComponentId(go, 2, &component_id));
    dmGameObject::Delete(m_Collection, go, false);
}

TEST_F(ComponentTest, TestManyComponents)
{
    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/many.goc");

    char name[64];
    uint16_t component_index;
    dmhash_t component_id;
    const uint32_t num_components = 300;
    for( uint32_t i = 0; i < num_components; ++i)
    {
        dmSnPrintf(name, sizeof(name), "script%d", i);
        dmhash_t id = dmHashString64(name);
        ASSERT_EQ(dmGameObject::RESULT_OK, dmGameObject::GetComponentIndex(go, id, &component_index));
        ASSERT_EQ(i, component_index);

        ASSERT_EQ(dmGameObject::RESULT_OK, dmGameObject::GetComponentId(go, component_index, &component_id));
        ASSERT_EQ(id, component_id);
    }
    dmSnPrintf(name, sizeof(name), "script%d", num_components);
    ASSERT_EQ(dmGameObject::RESULT_COMPONENT_NOT_FOUND, dmGameObject::GetComponentIndex(go, dmHashString64(name), &component_index));
    ASSERT_EQ(dmGameObject::RESULT_COMPONENT_NOT_FOUND, dmGameObject::GetComponentId(go, num_components, &component_id));

    dmGameObject::Delete(m_Collection, go, false);
}

static int LuaTestCompType(lua_State* L)
{
    int top = lua_gettop(L);

    dmGameObject::HInstance instance = dmGameObject::GetInstanceFromLua(L);
    uintptr_t user_data = 0;
    dmMessage::URL receiver;
    dmGameObject::GetComponentUserDataFromLua(L, 1, dmGameObject::GetCollection(instance), "a", &user_data, &receiver, 0);
    assert(user_data == 1);

    assert(top == lua_gettop(L));

    return 0;
}

TEST_F(ComponentTest, TestComponentType)
{
    lua_State* L = dmScript::GetLuaState(m_ScriptContext);
    lua_pushcfunction(L, LuaTestCompType);
    lua_setglobal(L, "test_comp_type");

    dmGameObject::HInstance go = dmGameObject::New(m_Collection, "/test_comp_type.goc");
    dmGameObject::SetIdentifier(m_Collection, go, "test_instance");

    ASSERT_TRUE(dmGameObject::Init(m_Collection));

    bool ret = dmGameObject::Update(m_Collection, &m_UpdateContext);
    ASSERT_FALSE(ret);

    dmGameObject::Delete(m_Collection, go, false);
}

// Deleting the first go should delete the second in its final callback
// The test is to verify that the final callback is called for a cascading deletion of objects.
TEST_F(ComponentTest, FinalCallsFinal)
{
    dmGameObject::HCollection collection = dmGameObject::NewCollection("test_final_collection", m_Factory, m_Register, 11, 0x0);

    dmGameObject::HInstance go_a = dmGameObject::New(collection, "/test_final_final.goc");
    dmGameObject::SetIdentifier(collection, go_a, "first");

    char buf[5];
    for (uint32_t i = 0; i < 10; ++i) {
        dmGameObject::HInstance go_b = dmGameObject::New(collection, "/test_final_final.goc");
        dmSnPrintf(buf, 5, "id%d", i);
        dmGameObject::SetIdentifier(collection, go_b, buf);
    }

    // 11 objects in total
    ASSERT_EQ(11u, collection->m_Collection->m_InstanceIndices.Size());

    dmGameObject::Init(collection); // Init is required for final
    dmGameObject::Delete(collection, go_a, false);
    dmGameObject::PostUpdate(collection);

    // One lingering due to the cap of passes in dmGameObject::PostUpdate, which is currently set to 10
    ASSERT_EQ(1u, collection->m_Collection->m_InstanceIndices.Size());
    ASSERT_EQ((uint32_t) 10, m_ComponentFinalCountMap[TestGameObjectDDF::AResource::m_DDFHash]);

    // One more pass needed to delete the last object in the chain
    dmGameObject::PostUpdate(collection);

    // All done
    ASSERT_EQ(0u, collection->m_Collection->m_InstanceIndices.Size());
    ASSERT_EQ((uint32_t) 11, m_ComponentFinalCountMap[TestGameObjectDDF::AResource::m_DDFHash]);

    dmGameObject::DeleteCollection(collection);
    dmGameObject::PostUpdate(m_Register);
}

int main(int argc, char **argv)
{
    jc_test_init(&argc, argv);

    int ret = jc_test_run_all();
    return ret;
}

max_stars_repo_name: defold/defold

max_issues_repo_name: defold/defold

max_forks_repo_name: defold/defold


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

#include <boost/simd/swar/functions/group.hpp>
#include <boost/dispatch/meta/downgrade.hpp>

namespace boost { namespace simd { namespace ext
{
  //============================================================================
  // Implementation when type A0 is double
  //============================================================================
  BOOST_DISPATCH_IMPLEMENT          ( group_
                                    , boost::simd::tag::sse2_
                                    , (A0)
                                    , ((simd_<double_<A0>,boost::simd::tag::sse_>))
                                      ((simd_<double_<A0>,boost::simd::tag::sse_>))
                                    )
  {
    typedef typename dispatch::meta::downgrade<A0>::type result_type;

    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return _mm_movelh_ps(_mm_cvtpd_ps(a0), _mm_cvtpd_ps(a1));
    }
  };
} } }

#endif
#endif


text:
#include <cstdint>
#include <algorithm>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>

#include <boost/math/distributions/gamma.hpp>
#include <boost/math/distributions/negative_binomial.hpp>
#include <boost/cast.hpp>
#include <boost/random/negative_binomial_distribution.hpp>

namespace {
    using ParamType = double;
    using ResultType = int;
    using DensityType = double;
    using RandEngine = std::mt19937;
    using SizeType = size_t;
    using SeedType = std::mt19937::result_type;

    struct ParamSet {
        ParamType size;
        ParamType prob;
    };

    struct FileSet {
        SizeType n;
        std::string filename;
    };

    const std::vector<ParamType> SizeSet {2, 4, 6, 8};
    const std::vector<ParamType> ProbSet {0.1, 0.15, 0.25, 0.5};
    const std::vector<FileSet> AllFileSet {
        {100, "nbinom100.csv"},
        {1000, "nbinom1k.csv"},
        {10000, "nbinom10k.csv"},
        {100000, "nbinom100k.csv"},
    };
}

void rnbinomCpp(const auto& paramSet, SizeType n, SeedType seed, std::ofstream& ofs) {
    const ParamType alpha = paramSet.size;
    // Notice that prob for R means 1 - prob in C++
    const ParamType prob = paramSet.prob;
    const ParamType beta = (1 - prob) / prob;
    std::mt19937 gen(seed);

    std::gamma_distribution<double> distGamma(alpha, beta);
    std::unordered_map<ResultType, SizeType> count;

    // Cannot use alpha as integers
    using StdAlpha = int;
    const auto stdAlpha = boost::numeric_cast<StdAlpha>(alpha);
    std::negative_binomial_distribution<StdAlpha> distNB(stdAlpha, beta);

    // Makes random values
    ResultType maxValue = 0;
    for (decltype(n) i=0; i<n; ++i) {
        std::poisson_distribution<ResultType> dist(distGamma(gen));
        const auto value = dist(gen);
        count[value] += 1;
        maxValue = std::max(maxValue, value);
    }

    // Can eliminate outliers
    const SizeType sizeLimit = n + 100; //  n / 100;
    SizeType totalCount = 0;
    for (ResultType value=0; value<=maxValue; ++value) {
        // Writes densities in a long format
        const auto binCount = count[value];
        totalCount += binCount;
        const DensityType density = static_cast<DensityType>(binCount) / static_cast<DensityType>(n);
        ofs << alpha << "," << beta << "," << prob << "," << value << "," << density << "\n";
        if (totalCount >= sizeLimit) {
            break;
        }
    }
    return;
}

void rnbinomCppAll(void) {
    constexpr SeedType seed = 123;

    for(const auto& fileSet :AllFileSet) {
        // Writes titles
        std::ofstream ofs(fileSet.filename);
        ofs << "alpha,beta,prob,x,density" << std::endl;

        for(const auto& size : SizeSet) {
            for(const auto& prob : ProbSet) {
                const ParamSet paramSet {size, prob};
                rnbinomCpp(paramSet, fileSet.n, seed, ofs);
            }
        }
    }
}

template <typename CdfGenerator>
std::vector<DensityType> GenerateCdf(ResultType count, CdfGenerator& cdfGenerator) {
    std::vector<DensityType> vec;
    for(ResultType i=0; i<count; ++i) {
        vec.push_back(cdfGenerator(i));
    }
    return vec;
}

template <typename Vec>
void PrintVec(const Vec& vec, std::ostream& os) {
    const auto size = vec.size();
    for(auto i = decltype(size){0}; i<size; ++i) {
        os << vec.at(i);
        if ((i + 1) < size) {
            os << ",";
        }
    }
    os << "\n";
    return;
}

void nbinomCppCdf(void) {
    constexpr DensityType nbSize = 2.0;
    constexpr DensityType nbProb = 0.25;

    boost::math::negative_binomial distNB(nbSize, nbProb);
    auto funcNB = [&distNB](ResultType i) {
        return boost::math::cdf(distNB, i);
    };

    auto cdfNB = std::bind(funcNB, std::placeholders::_1);
    constexpr ResultType count = 10;
    std::ostringstream osNB;
    const auto actualNB = GenerateCdf(count, cdfNB);
    PrintVec(actualNB, osNB);

    // R pnbinom(seq(0, 9, 1), size=2.0, prob=0.25)
    // [1] 0.0625000 0.1562500 0.2617188 0.3671875 0.4660645 0.5550537 0.6329193 0.6996613
    // [9] 0.7559748 0.8029027
    std::cout << osNB.str();

    constexpr DensityType shape = 1.0;
    constexpr DensityType scale = 2.0;

    boost::math::gamma_distribution<double> distGamma(shape, scale);
    auto funcGamma = [&distGamma](ResultType i) {
        return boost::math::cdf(distGamma, i);
    };

    auto cdfGamma = std::bind(funcGamma, std::placeholders::_1);
    const auto actualGamma = GenerateCdf(count, cdfGamma);

    // R pgamma(seq(0, 9, 1), shape=1.0, scale=2.0)
    // [1] 0.0000000 0.3934693 0.6321206 0.7768698 0.8646647 0.9179150 0.9502129 0.9698026
    // [9] 0.9816844 0.9888910
    std::ostringstream osGamma;
    PrintVec(actualGamma, osGamma);
    std::cout << osGamma.str() << std::endl;
}

void cppRandombinom(void) {
    constexpr int size = 2;
    constexpr double prob = 0.5;
    std::negative_binomial_distribution<int> dist(size, prob);
//  std::negative_binomial_distribution<double> dist(size, prob);
    std::mt19937 randGen;
    for(int i=0; i<10000; ++i) {
       std::cout << dist(randGen);
    }
}

void boostMathCppNbinom(void) {
    constexpr double size = 0.99;
    constexpr double prob = 0.5;
    boost::math::negative_binomial dist(size, prob);

    for(double p=0.1; p<0.91; p += 0.1) {
       std::cout << boost::math::cdf(dist, p);
    };
}

void boostRandombinomLarge(void) {
    constexpr int size = 2;
    constexpr double prob = 0.5;
    boost::random::negative_binomial_distribution<int, double> dist(size, prob);
//  boost::random::negative_binomial_distribution<double, double> dist(size, prob);
    std::mt19937 randGen;
    for(int i=0; i<10000; ++i) {
       std::cout << dist(randGen);
    }
}

// This code occurs a runtime assertion failure
void boostRandombinomSmall(void) {
#if 0
    constexpr int size = 0.4;
    constexpr double prob = 0.3;
    boost::random::negative_binomial_distribution<int, double> dist(size, prob);
    std::mt19937 randGen;
    for(int i=0; i<10000; ++i) {
       std::cout << dist(randGen);
    }
#endif
}

int main(int argc, char* argv[]) {
    std::cout << "BOOST_VERSION=" << BOOST_VERSION << "\n";
    cppRandombinom();
    boostMathCppNbinom();
    boostRandombinomLarge();
    boostRandombinomSmall();

    rnbinomCppAll();
    nbinomCppCdf();
    std::cout << "Everything is OK\n";
    return 0;
}

/*
Local Variables:
mode: c++
coding: utf-8-dos
tab-width: nil
c-file-style: "stroustrup"
End:
*/

max_stars_repo_name: zettsu-t/cPlusPlusFriend

max_issues_repo_name: zettsu-t/cPlusPlusFriend

max_forks_repo_name: zettsu-t/cPlusPlusFriend


text:
/**
 * @file   NMAAnalyzer.hpp
 * @author see AUTHORS
 * @brief  NMAAnalyzer header file.
 */

#ifndef NONLINEARFITTER_HPP
#define NONLINEARFITTER_HPP

#include <math.h>

#include <Eigen/Dense>

/**
 * @class NonlinearFitter
 */
class NonlinearFitter {
public:
    /**
     * @param x
     * @param y
     * @param yerr2
     */
    void exponential_fit(Eigen::VectorXd & x, Eigen::VectorXd & y, Eigen::VectorXd & yerr2); //length == ndat/S

    /**
     * @return a
     */
    double get_a();

    /**
     * @return b
     */
    double get_b();

    /**
     * @return error for a
     */
    double get_err_a();

    /**
     * @return error for b
     */
    double get_err_b();
private:
    double a = 0;
    double b = 0;
    double err_a = 0;
    double err_b = 0;
    bool calculation_completed = false;
};

#endif

// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

max_stars_repo_name: AFriemann/LowCarb

max_issues_repo_name: AFriemann/LowCarb

max_forks_repo_name: AFriemann/LowCarb


text:
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/fusion/include/std_pair.hpp>

#include <iostream>
#include <string>
#include <complex>

namespace client{
  template <typename Iterator>
    bool parse_complex(Iterator first, Iterator last, std::complex<double>& c){
      using boost::spirit::qi::double_;
      using boost::spirit::qi::_1;
      using boost::spirit::qi::phrase_parse;
      using boost::spirit::ascii::space;
      using boost::phoenix::ref;

      double rN = 0.0;
      double iN = 0.0;
      bool r = phrase_parse(first, last,
          (
            '(' >> double_[ref(rN) = _1]
                >> -(',' >> double_[ref(iN) = _1]) >> ')'
            | double_[ref(rN) = _1]
          ),
          space);

      if(!r || first != last)
        return false;
      c = std::complex<double>(rN, iN);
      return r;
    }

  template <typename OutputIterator>
    bool generate_complex(OutputIterator sink, std::complex<double> const& c){
      using boost::spirit::karma::eps;
      using boost::spirit::karma::double_;
      using boost::spirit::karma::_1;
      using boost::spirit::karma::generate;

      return generate(sink,
          (
            eps(c.imag() != 0) << '(' << double_[_1 = c.real()] << ", " << double_[_1 = c.imag()] << ')'
            | double_[_1 = c.real()]
          )
      );
    }
}

int main(){
  std::string str;
  while(getline(std::cin, str)){
    if(str.empty() || str[0] == 'q' || str[0] == 'Q')
      break;

    std::complex<double> c;
    if(client::parse_complex(str.begin(), str.end(), c)){
      std::string generated;
      std::back_insert_iterator<std::string> sink(generated);
      if(!client::generate_complex(sink, c)){
        std::cout << "Generating failed\n";
      }
      else{
        std::cout << "Generated: " << generated << std::endl;
      }
    }
    else{
      std::cout << "Parsing failed\n";
    }
  }

  return 0;
}