text:
//
// parse_update_xml.cpp - parse update xml implementation
//
// leccore library, part of the liblec library
// Copyright (c) 2019 Alec Musasa (alecmus at live dot com)
//
// Released under the MIT license. For full details see the
// file LICENSE.txt
//

#include "parse_update_xml.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

bool read_value(const std::string& xml,
	const std::string& value_name, std::string& value, std::string& error) {
	error.clear();
	value.clear();

	try{
		std::stringstream ss;
		ss << xml;
		boost::property_tree::ptree pt;
		boost::property_tree::read_xml(ss, pt);
		value = pt.get(value_name, std::string());
		return true;
	}
	catch (const std::exception& e){
		error = e.what();
		return false;
	}

	return true;
}

bool liblec::leccore::parse_update_xml(const std::string& xml,
	liblec::leccore::check_update::update_info& details,
	std::string& error) {
	error.clear();
	details = {};

	check_update::update_info _details = {};
	if (!read_value(xml, "leccore.update.title", _details.title, error))
		return false;

	if (!read_value(xml, "leccore.update.description", _details.description, error))
		return false;

	if (!read_value(xml, "leccore.update.version", _details.version, error))
		return false;

	if (!read_value(xml, "leccore.update.date", _details.date, error))
		return false;

	std::string architecture;
#ifdef _WIN64
	architecture = "x64";
#else
	architecture = "x86";
#endif

	if (!read_value(xml, "leccore.update." + architecture + ".download_url", _details.download_url, error))
		return false;

	std::string size;
	if (!read_value(xml, "leccore.update." + architecture + ".size", size, error))
		return false;
	else {
		try {
			std::stringstream ss;
			ss << size;
			ss >> _details.size;
		}
		catch (const std::exception& e) {
			error = e.what();
			return false;
		}
	}

	if (!read_value(xml, "leccore.update." + architecture + ".hash.sha256", _details.hash, error))
		return false;

	details = _details;
	return true;
}

max_stars_repo_name: alecmus/leccore

max_issues_repo_name: alecmus/leccore

max_forks_repo_name: alecmus/leccore


text:
//==================================================================================================
/*!
  @file

  @copyright 2015 NumScale SAS
  @copyright 2015 J.T. Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_MULS_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_MULS_HPP_INCLUDED

#include <boost/simd/constant/valmax.hpp>
#include <boost/simd/constant/valmin.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/scalar/abs.hpp>
#include <boost/simd/function/scalar/bitofsign.hpp>
#include <boost/simd/function/scalar/bitwise_xor.hpp>
#include <boost/simd/function/scalar/genmask.hpp>
#include <boost/simd/function/scalar/saturate.hpp>
#include <boost/dispatch/function/overload.hpp>
#include <boost/dispatch/meta/as_unsigned.hpp>
#include <boost/dispatch/meta/upgrade.hpp>
#include <boost/config.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  BOOST_DISPATCH_OVERLOAD ( muls_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::floating_<A0> >
                          , bd::scalar_< bd::floating_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      return a0*a1;
    }
  };

  BOOST_DISPATCH_OVERLOAD ( muls_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::unsigned_<A0> >
                          , bd::scalar_< bd::unsigned_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      using up_t =  bd::upgrade_t<A0>;
      up_t res = up_t(a0)*up_t(a1);
      return static_cast<A0>(res) | genmask(static_cast<A0>(res >> sizeof(A0)*CHAR_BIT));
    }
  };

  BOOST_DISPATCH_OVERLOAD ( muls_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::integer_<A0> >
                          , bd::scalar_< bd::integer_<A0> >
                          )
  {

    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      using up_t =  bd::upgrade_t<A0>;
      return A0(saturate<A0>(static_cast<up_t>(a0)*static_cast<up_t>(a1)));
    }
  };

  BOOST_DISPATCH_OVERLOAD ( muls_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::int32_<A0> >
                          , bd::scalar_< bd::int32_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      using un_t = bd::as_unsigned_t<A0>;
      using up_t = bd::upgrade_t<A0>;

      up_t res = up_t(a0)*up_t(a1);
      un_t res2 = (un_t(a0 ^ a1) >> (sizeof(A0)*CHAR_BIT-1)) + Valmax<A0>();

      A0 hi = (res >> sizeof( A0)*CHAR_BIT);
      A0 lo = res;

      if(hi != (lo >> (sizeof( A0)*CHAR_BIT-1)))
        res = res2;

      return res;
    }
  };

  BOOST_DISPATCH_OVERLOAD ( muls_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::uint64_<A0> >
                          , bd::scalar_< bd::uint64_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      if (a1 == 0 || a0 == 0) return Zero<A0>();
      if (a1 >= a0)
        return aux(a0, a1);
      else
        return aux(a1, a0);
    }
  private :
    static BOOST_FORCEINLINE A0 aux(const A0& mini,  const A0& maxi)
    {
      A0 z = Valmax<A0>()/maxi;
      return (z < mini) ? Valmax<A0>() : mini*maxi;
    }
  };

  BOOST_DISPATCH_OVERLOAD ( muls_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::int64_<A0> >
                          , bd::scalar_< bd::int64_<A0> >
                          )
  {
    using un_t = bd::as_unsigned_t<A0>;
    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT
    {
      if (a1 == 0 || a0 == 0) return Zero<A0>();
      A0 sign =  bitwise_xor(bitofsign(a0), bitofsign(a1));
      un_t aa0 = simd::abs(a0);
      un_t aa1 = simd::abs(a1);
      if (aa1 >= aa0)
        return aux(a0, a1, sign, aa0, aa1);
      else
        return aux(a1, a0, sign, aa1, aa0);
    }
    static BOOST_FORCEINLINE A0 aux(const A0& mini,  const A0& maxi,
                                    const A0& sign,
                                    const un_t& amini, const un_t& amaxi)
    {
      un_t z = Valmax<A0>()/amaxi;
      return (z < amini)
        ? ( sign ? Valmin<A0>():Valmax<A0>())
        : mini*maxi;
    }
  };
} } }

#endif

ext: hpp


text:
// Copyright (c) 2006, Niels Martin Hansen
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Aegisub Group nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Aegisub Project http://www.aegisub.org/

/// @file auto4_base.cpp
/// @brief Baseclasses for Automation 4 scripting framework
/// @ingroup scripting
///

#include "config.h"

#include "auto4_base.h"

#include "ass_file.h"
#include "ass_style.h"
#include "command/command.h"
#include "dialog_progress.h"
#include "include/aegisub/context.h"
#include "options.h"
#include "string_codec.h"
#include "subs_controller.h"
#include "subtitle_format.h"
#include "utils.h"

#include <libaegisub/dispatch.h>
#include <libaegisub/fs.h>
#include <libaegisub/path.h>
#include <libaegisub/util.h>

#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/format.hpp>
#include <boost/tokenizer.hpp>
#include <future>

#include <wx/dcmemory.h>
#include <wx/log.h>
#include <wx/sizer.h>
#include <wx/msgdlg.h>

#ifdef __WINDOWS__
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include <libaegisub/charset_conv_win.h>
#endif

namespace Automation4 {
	bool CalculateTextExtents(AssStyle *style, std::string const& text, double &width, double &height, double &descent, double &extlead)
	{
		width = height = descent = extlead = 0;

		double fontsize = style->fontsize * 64;
		double spacing = style->spacing * 64;

#ifdef WIN32
		// This is almost copypasta from TextSub
		HDC thedc = CreateCompatibleDC(0);
		if (!thedc) return false;
		SetMapMode(thedc, MM_TEXT);

		LOGFONTW lf;
		ZeroMemory(&lf, sizeof(lf));
		lf.lfHeight = (LONG)fontsize;
		lf.lfWeight = style->bold ? FW_BOLD : FW_NORMAL;
		lf.lfItalic = style->italic;
		lf.lfUnderline = style->underline;
		lf.lfStrikeOut = style->strikeout;
		lf.lfCharSet = style->encoding;
		lf.lfOutPrecision = OUT_TT_PRECIS;
		lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
		lf.lfQuality = ANTIALIASED_QUALITY;
		lf.lfPitchAndFamily = DEFAULT_PITCH|FF_DONTCARE;
		wcsncpy(lf.lfFaceName, agi::charset::ConvertW(style->font).c_str(), 32);

		HFONT thefont = CreateFontIndirect(&lf);
		if (!thefont) return false;
		SelectObject(thedc, thefont);

		std::wstring wtext(agi::charset::ConvertW(text));
		SIZE sz;
		if (spacing != 0 ) {
			width = 0;
			for (auto c : wtext) {
				GetTextExtentPoint32(thedc, &c, 1, &sz);
				width += sz.cx + spacing;
				height = sz.cy;
			}
		}
		else {
			GetTextExtentPoint32(thedc, &wtext[0], (int)wtext.size(), &sz);
			width = sz.cx;
			height = sz.cy;
		}

		TEXTMETRIC tm;
		GetTextMetrics(thedc, &tm);
		descent = tm.tmDescent;
		extlead= tm.tmExternalLeading;

		DeleteObject(thedc);
		DeleteObject(thefont);

#else // not WIN32
		wxMemoryDC thedc;

		// fix fontsize to be 72 DPI
		//fontsize = -FT_MulDiv((int)(fontsize+0.5), 72, thedc.GetPPI().y);

		// now try to get a font!
		// use the font list to get some caching... (chance is the script will need the same font very often)
		// USING wxTheFontList SEEMS TO CAUSE BAD LEAKS!
		//wxFont *thefont = wxTheFontList->FindOrCreateFont(
		wxFont thefont(
			(int)fontsize,
			wxFONTFAMILY_DEFAULT,
			style->italic ? wxFONTSTYLE_ITALIC : wxFONTSTYLE_NORMAL,
			style->bold ? wxFONTWEIGHT_BOLD : wxFONTWEIGHT_NORMAL,
			style->underline,
			to_wx(style->font),
			wxFONTENCODING_SYSTEM); // FIXME! make sure to get the right encoding here, make some translation table between windows and wx encodings
		thedc.SetFont(thefont);

		wxString wtext(to_wx(text));
		if (spacing) {
			// If there's inter-character spacing, kerning info must not be used, so calculate width per character
			// NOTE: Is kerning actually done either way?!
			for (auto const& wc : wtext) {
				int a, b, c, d;
				thedc.GetTextExtent(wc, &a, &b, &c, &d);
				double scaling = fontsize / (double)(b > 0 ? b : 1); // semi-workaround for missing OS/2 table data for scaling
				width += (a + spacing)*scaling;
				height = b > height ? b*scaling : height;
				descent = c > descent ? c*scaling : descent;
				extlead = d > extlead ? d*scaling : extlead;
			}
		} else {
			// If the inter-character spacing should be zero, kerning info can (and must) be used, so calculate everything in one go
			wxCoord lwidth, lheight, ldescent, lextlead;
			thedc.GetTextExtent(wtext, &lwidth, &lheight, &ldescent, &lextlead);
			double scaling = fontsize / (double)(lheight > 0 ? lheight : 1); // semi-workaround for missing OS/2 table data for scaling
			width = lwidth*scaling; height = lheight*scaling; descent = ldescent*scaling; extlead = lextlead*scaling;
		}
#endif

		// Compensate for scaling
		width = style->scalex / 100 * width / 64;
		height = style->scaley / 100 * height / 64;
		descent = style->scaley / 100 * descent / 64;
		extlead = style->scaley / 100 * extlead / 64;

		return true;
	}

	ExportFilter::ExportFilter(std::string const& name, std::string const& description, int priority)
	: AssExportFilter(name, description, priority)
	{
	}

	std::string ExportFilter::GetScriptSettingsIdentifier()
	{
		return inline_string_encode("Automation Settings " + GetName());
	}

	wxWindow* ExportFilter::GetConfigDialogWindow(wxWindow *parent, agi::Context *c) {
		config_dialog.reset(GenerateConfigDialog(parent, c));

		if (config_dialog) {
			std::string val = c->ass->GetScriptInfo(GetScriptSettingsIdentifier());
			if (!val.empty())
				config_dialog->Unserialise(val);
			return config_dialog->CreateWindow(parent);
		}

		return nullptr;
	}

	void ExportFilter::LoadSettings(bool is_default, agi::Context *c) {
		if (config_dialog) {
			std::string val = config_dialog->Serialise();
			if (!val.empty())
				c->ass->SetScriptInfo(GetScriptSettingsIdentifier(), val);
		}
	}

	// ProgressSink
	ProgressSink::ProgressSink(agi::ProgressSink *impl, BackgroundScriptRunner *bsr)
	: impl(impl)
	, bsr(bsr)
	, trace_level(OPT_GET("Automation/Trace Level")->GetInt())
	{
	}

	void ProgressSink::ShowDialog(ScriptDialog *config_dialog)
	{
		agi::dispatch::Main().Sync([=] {
			wxDialog w; // container dialog box
			w.SetExtraStyle(wxWS_EX_VALIDATE_RECURSIVELY);
			w.Create(bsr->GetParentWindow(), -1, to_wx(bsr->GetTitle()));
			auto s = new wxBoxSizer(wxHORIZONTAL); // sizer for putting contents in
			wxWindow *ww = config_dialog->CreateWindow(&w); // generate actual dialog contents
			s->Add(ww, 0, wxALL, 5); // add contents to dialog
			w.SetSizerAndFit(s);
			w.CenterOnParent();
			w.ShowModal();
		});
	}

	int ProgressSink::ShowDialog(wxDialog *dialog)
	{
		int ret = 0;
		agi::dispatch::Main().Sync([&] { ret = dialog->ShowModal(); });
		return ret;
	}

	BackgroundScriptRunner::BackgroundScriptRunner(wxWindow *parent, std::string const& title)
	: impl(new DialogProgress(parent, to_wx(title)))
	{
	}

	BackgroundScriptRunner::~BackgroundScriptRunner()
	{
	}

	void BackgroundScriptRunner::Run(std::function<void (ProgressSink*)> task)
	{
		int prio = OPT_GET("Automation/Thread Priority")->GetInt();
		if (prio == 0) prio = 50; // normal
		else if (prio == 1) prio = 30; // below normal
		else if (prio == 2) prio = 10; // lowest
		else prio = 50; // fallback normal

		impl->Run([&](agi::ProgressSink *ps) {
			ProgressSink aps(ps, this);
			task(&aps);
		}, prio);
	}

	wxWindow *BackgroundScriptRunner::GetParentWindow() const
	{
		return impl.get();
	}

	std::string BackgroundScriptRunner::GetTitle() const
	{
		return from_wx(impl->GetTitle());
	}

	// Script
	Script::Script(agi::fs::path const& filename)
	: filename(filename)
	{
		include_path.emplace_back(filename.parent_path());

		std::string include_paths = OPT_GET("Path/Automation/Include")->GetString();
		boost::char_separator<char> sep("|");
		for (auto const& tok : boost::tokenizer<boost::char_separator<char>>(include_paths, sep)) {
			auto path = config::path->Decode(tok);
			if (path.is_absolute() && agi::fs::DirectoryExists(path))
				include_path.emplace_back(std::move(path));
		}
	}

	// ScriptManager
	ScriptManager::~ScriptManager()
	{
	}

	void ScriptManager::Add(std::unique_ptr<Script> script)
	{
		if (find(scripts.begin(), scripts.end(), script) == scripts.end())
			scripts.emplace_back(std::move(script));

		ScriptsChanged();
	}

	void ScriptManager::Remove(Script *script)
	{
		auto i = find_if(scripts.begin(), scripts.end(), [&](std::unique_ptr<Script> const& s) { return s.get() == script; });
		if (i != scripts.end())
			scripts.erase(i);

		ScriptsChanged();
	}

	void ScriptManager::RemoveAll()
	{
		scripts.clear();
		ScriptsChanged();
	}

	void ScriptManager::Reload(Script *script)
	{
		script->Reload();
		ScriptsChanged();
	}

	const std::vector<cmd::Command*>& ScriptManager::GetMacros()
	{
		macros.clear();
		for (auto& script : scripts) {
			std::vector<cmd::Command*> sfs = script->GetMacros();
			copy(sfs.begin(), sfs.end(), back_inserter(macros));
		}
		return macros;
	}

	// AutoloadScriptManager
	AutoloadScriptManager::AutoloadScriptManager(std::string path)
	: path(std::move(path))
	{
		Reload();
	}

	void AutoloadScriptManager::Reload()
	{
		scripts.clear();

		std::vector<std::future<std::unique_ptr<Script>>> script_futures;

		boost::char_separator<char> sep("|");
		for (auto const& tok : boost::tokenizer<boost::char_separator<char>>(path, sep)) {
			auto dirname = config::path->Decode(tok);
			if (!agi::fs::DirectoryExists(dirname)) continue;

			for (auto filename : agi::fs::DirectoryIterator(dirname, "*.*"))
				script_futures.emplace_back(std::async(std::launch::async, [=] {
					return ScriptFactory::CreateFromFile(dirname/filename, false, false);
				}));
		}

		int error_count = 0;
		for (auto& future : script_futures) {
			auto s = future.get();
			if (s) {
				if (!s->GetLoadedState()) ++error_count;
				scripts.emplace_back(std::move(s));
			}
		}

		if (error_count == 1) {
			wxLogWarning("A script in the Automation autoload directory failed to load.\nPlease review the errors, fix them and use the Rescan Autoload Dir button in Automation Manager to load the scripts again.");
		}
		else if (error_count > 1) {
			wxLogWarning("Multiple scripts in the Automation autoload directory failed to load.\nPlease review the errors, fix them and use the Rescan Autoload Dir button in Automation Manager to load the scripts again.");
		}

		ScriptsChanged();
	}

	LocalScriptManager::LocalScriptManager(agi::Context *c)
	: context(c)
	{
		slots.push_back(c->subsController->AddFileSaveListener(&LocalScriptManager::OnSubtitlesSave, this));
		slots.push_back(c->subsController->AddFileOpenListener(&LocalScriptManager::Reload, this));
	}

	void LocalScriptManager::Reload()
	{
		scripts.clear();

		auto local_scripts = context->ass->GetScriptInfo("Automation Scripts");
		if (local_scripts.empty()) {
			ScriptsChanged();
			return;
		}

		auto autobasefn(OPT_GET("Path/Automation/Base")->GetString());

		boost::char_separator<char> sep("|");
		for (auto const& cur : boost::tokenizer<boost::char_separator<char>>(local_scripts, sep)) {
			auto trimmed = boost::trim_copy(cur);
			char first_char = trimmed[0];
			trimmed.erase(0, 1);

			agi::fs::path basepath;
			if (first_char == '~') {
				basepath = context->subsController->Filename().parent_path();
			} else if (first_char == '$') {
				basepath = autobasefn;
			} else if (first_char == '/') {
			} else {
				wxLogWarning("Automation Script referenced with unknown location specifier character.\nLocation specifier found: %c\nFilename specified: %s",
					first_char, to_wx(trimmed));
				continue;
			}
			auto sfname = basepath/trimmed;
			if (agi::fs::FileExists(sfname))
				scripts.emplace_back(Automation4::ScriptFactory::CreateFromFile(sfname, true));
			else {
				wxLogWarning("Automation Script referenced could not be found.\nFilename specified: %c%s\nSearched relative to: %s\nResolved filename: %s",
					first_char, to_wx(trimmed), basepath.wstring(), sfname.wstring());
			}
		}

		ScriptsChanged();
	}

	void LocalScriptManager::OnSubtitlesSave()
	{
		// Store Automation script data
		// Algorithm:
		// 1. If script filename has Automation Base Path as a prefix, the path is relative to that (ie. "$")
		// 2. Otherwise try making it relative to the ass filename
		// 3. If step 2 failed, or absolute path is shorter than path relative to ass, use absolute path ("/")
		// 4. Otherwise, use path relative to ass ("~")
		std::string scripts_string;
		agi::fs::path autobasefn(OPT_GET("Path/Automation/Base")->GetString());

		for (auto& script : GetScripts()) {
			if (!scripts_string.empty())
				scripts_string += "|";

			auto scriptfn(script->GetFilename().string());
			auto autobase_rel = config::path->MakeRelative(scriptfn, autobasefn);
			auto assfile_rel = config::path->MakeRelative(scriptfn, "?script");

			if (autobase_rel.string().size() <= scriptfn.size() && autobase_rel.string().size() <= assfile_rel.string().size()) {
				scriptfn = "$" + autobase_rel.generic_string();
			} else if (assfile_rel.string().size() <= scriptfn.size() && assfile_rel.string().size() <= autobase_rel.string().size()) {
				scriptfn = "~" + assfile_rel.generic_string();
			} else {
				scriptfn = "/" + script->GetFilename().generic_string();
			}

			scripts_string += scriptfn;
		}
		context->ass->SetScriptInfo("Automation Scripts", scripts_string);
	}

	// ScriptFactory
	ScriptFactory::ScriptFactory(std::string engine_name, std::string filename_pattern)
	: engine_name(std::move(engine_name))
	, filename_pattern(std::move(filename_pattern))
	{
	}

	void ScriptFactory::Register(std::unique_ptr<ScriptFactory> factory)
	{
		if (find(Factories().begin(), Factories().end(), factory) != Factories().end())
			throw agi::InternalError("Automation 4: Attempt to register the same script factory multiple times. This should never happen.", nullptr);

		Factories().emplace_back(std::move(factory));
	}

	std::unique_ptr<Script> ScriptFactory::CreateFromFile(agi::fs::path const& filename, bool complain_about_unrecognised, bool create_unknown)
	{
		for (auto& factory : Factories()) {
			auto s = factory->Produce(filename);
			if (s) {
				if (!s->GetLoadedState()) {
					wxLogError(_("Failed to load Automation script '%s':\n%s"), filename.wstring(), s->GetDescription());
				}
				return s;
			}
		}

		if (complain_about_unrecognised) {
			wxLogError(_("The file was not recognised as an Automation script: %s"), filename.wstring());
		}

		return create_unknown ? agi::util::make_unique<UnknownScript>(filename) : nullptr;
	}

	std::vector<std::unique_ptr<ScriptFactory>>& ScriptFactory::Factories()
	{
		static std::vector<std::unique_ptr<ScriptFactory>> factories;
		return factories;
	}

	const std::vector<std::unique_ptr<ScriptFactory>>& ScriptFactory::GetFactories()
	{
		return Factories();
	}

	std::string ScriptFactory::GetWildcardStr()
	{
		std::string fnfilter, catchall;
		for (auto& fact : Factories()) {
			if (fact->GetEngineName().empty() || fact->GetFilenamePattern().empty())
				continue;

			std::string filter(fact->GetFilenamePattern());
			boost::replace_all(filter, ",", ";");
			fnfilter += str(boost::format("%s scripts (%s)|%s|") % fact->GetEngineName() % fact->GetFilenamePattern() % filter);
			catchall += filter + ";";
		}
		fnfilter += from_wx(_("All Files")) + " (*.*)|*.*";

		if (!catchall.empty())
			catchall.pop_back();

		if (Factories().size() > 1)
			fnfilter = from_wx(_("All Supported Formats")) + "|" + catchall + "|" + fnfilter;

		return fnfilter;
	}
}

ext: cpp

max_stars_repo_name: rcombs/Aegisub

max_issues_repo_name: rcombs/Aegisub

max_forks_repo_name: rcombs/Aegisub


text:
/*!
 * @file
 * Contains unit tests for `boost::mpl11::datatype`.
 */

#include <boost/mpl11/core.hpp>

#include <boost/mpl11/detail/std_is_same.hpp>

using namespace boost::mpl11;
using detail::std_is_same;

struct with_nested_datatype { struct mpl_datatype; };
static_assert(std_is_same<
    datatype<with_nested_datatype>::type,
    with_nested_datatype::mpl_datatype
>::value, "");

struct without_nested_datatype { };
static_assert(std_is_same<
    datatype<without_nested_datatype>::type,
    Foreign
>::value, "");

static_assert(std_is_same<
    datatype<void>::type,
    Foreign
>::value, "");

int main() { }


text:
#define BOOST_TEST_MODULE hash_multimap test
#include <boost/test/unit_test.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/functional/hash.hpp>

#include <string>
#include <cstring>

#include <iostream>

#include "hash_multimap.hpp"

using namespace boost::interprocess;

BOOST_AUTO_TEST_CASE( adding_test ) {
    HashMultiMap<int, int> h(8, 932874231);
    BOOST_CHECK(h.capacity() >= 8);

    BOOST_CHECK_EQUAL(h.put(10, 100), true);
    BOOST_CHECK_EQUAL(h.put(10, 101), true);
    BOOST_CHECK_EQUAL(h.put(0, 12), true);

    std::vector<int> v1, v2, v3;
    v1.push_back(100); v1.push_back(101);
    v2.push_back(12);

    BOOST_CHECK(h.get_all(10) == v1);
    BOOST_CHECK(h.get_all(0) == v2);
    BOOST_CHECK(h.get_all(3) == v3);
}

ext: cc

max_stars_repo_name: ivartb/itmo-assembler

max_issues_repo_name: ivartb/itmo-assembler

max_forks_repo_name: ivartb/itmo-assembler


text:
#include "LogItem.h"

#include "LogLevel.h"
#include "LogHelper.h"

#include <boost/algorithm/string/trim.hpp>
#include <boost\property_tree\detail\xml_parser_write.hpp>
#include <boost\property_tree\xml_parser.hpp>

namespace
{
	std::string timeStampToString(std::chrono::system_clock::time_point timeStamp)
	{
		std::string result;
		result.reserve(28);

		const auto time = std::chrono::system_clock::to_time_t(timeStamp);
		std::tm buf;
		localtime_s(&buf, &time);

		result += std::to_string(buf.tm_year + 1900);
		result += '/';
		result += std::to_string(buf.tm_mon);
		result += '/';
		result += std::to_string(buf.tm_mday);

		result += '-';

		result += std::to_string(buf.tm_hour);
		result += ':';
		result += std::to_string(buf.tm_min);
		result += ':';
		result += std::to_string(buf.tm_sec);
		result += ':';
		result += std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(timeStamp - std::chrono::time_point_cast<std::chrono::seconds>(timeStamp)).count());

		return result;
	}

	class LogThreadIdParserPolicy
	{
	public:
		template<class SrcPolicy>
		static std::string parse(const std::thread::id thId)
		{
			std::stringstream thStream;
			thStream << 'T' << thId << " (0x" << std::hex << thId << ')';
			return std::move(thStream).str();
		}
	};
}

Storm::LogItem::LogItem(const std::string_view &moduleName, const Storm::LogLevel level, const std::string_view &function, const int line, std::string &&msg) :
	_moduleName{ moduleName },
	_level{ level },
	_function{ function },
	_line{ line },
	_timestamp{ std::chrono::system_clock::now() },
	_threadId{ std::this_thread::get_id() },
	_msg{ std::move(msg) }
{

}

void Storm::LogItem::prepare(bool xmlToo, unsigned int processID)
{
	const std::string_view levelStr = Storm::parseLogLevel(_level);
	const std::string timestampStr = timeStampToString(_timestamp);
	const std::string codeLocationStr = _function + " - " + std::to_string(_line);
	const std::string lineStr = std::to_string(_line);
	const std::string threadIdStr = Storm::toStdString<LogThreadIdParserPolicy>(_threadId);

	const std::size_t levelStrSize = levelStr.size();
	const std::size_t timestampStrSize = timestampStr.size();
	const std::size_t codeLocationStrSize = codeLocationStr.size();
	const std::size_t threadIdStrSize = threadIdStr.size();
	const std::size_t msgSize = _msg.size();
	const std::size_t moduleNameStrSize = _moduleName.size();

	if (_finalMsg.empty())
	{
		_finalMsg.reserve(msgSize + moduleNameStrSize + codeLocationStrSize + levelStrSize + timestampStrSize + threadIdStrSize + 18);

		_finalMsg += '[';
		_finalMsg += levelStr;
		_finalMsg += "][";
		_finalMsg += _moduleName;
		_finalMsg += "][";
		_finalMsg += timestampStr;
		_finalMsg += "][";
		_finalMsg += codeLocationStr;
		_finalMsg += "][";
		_finalMsg += threadIdStr;
		_finalMsg += "] : ";

		_finalMsg += _msg;

		_finalMsg += '\n';
	}

	if (xmlToo && _finalXml.empty())
	{
		std::stringstream str;
		boost::property_tree::ptree logXml;

		logXml.add<decltype(levelStr)>("<xmlattr>.logLevel", levelStr);
		logXml.add<decltype(_moduleName)>("<xmlattr>.module", _moduleName);
		logXml.add<decltype(timestampStr)>("<xmlattr>.timestamp", timestampStr);
		logXml.add<decltype(threadIdStr)>("<xmlattr>.thread", threadIdStr);
		logXml.add<decltype(codeLocationStr)>("<xmlattr>.codeLocation", codeLocationStr);
		logXml.add<decltype(processID)>("<xmlattr>.PID", processID);
		logXml.put_value(boost::algorithm::trim_copy_if(_msg, [](const char charact) { return charact == '\0'; }));

		boost::property_tree::xml_parser::write_xml_element(str, "log", logXml, 0, boost::property_tree::xml_writer_make_settings<std::string>('\n', 1));

		_finalXml = str.str();
	}
}

const std::string& Storm::LogItem::rawMessage() const
{
	assert(!_finalMsg.empty() && "The LogItem should have been prepared before coming here!");
	return _finalMsg;
}

const std::string& Storm::LogItem::toXml() const
{
	assert(!_finalXml.empty() && "The LogItem should have been prepared before coming here!");
	return _finalXml;
}

max_stars_repo_name: SunlayGGX/Storm

max_issues_repo_name: SunlayGGX/Storm

max_forks_repo_name: SunlayGGX/Storm


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 *************************************************************/

#ifndef REPORT_REPORTSECTION_HXX
#define REPORT_REPORTSECTION_HXX

#include <vcl/window.hxx>
#include "RptPage.hxx"
#include <com/sun/star/beans/NamedValue.hpp>
#include <comphelper/propmultiplex.hxx>
#include "cppuhelper/basemutex.hxx"
#include "ReportDefines.hxx"
#include "dlgedfunc.hxx"
#include <svtools/transfer.hxx>
#include <rtl/ref.hxx>
#include <boost/shared_ptr.hpp>
#include <memory>

namespace rptui
{
	class OReportModel;
	class OReportPage;
	class OSectionView;
	class OSectionWindow;

	class OReportSection :	 public Window
						,	public ::cppu::BaseMutex
						,	public ::comphelper::OPropertyChangeListener
                        ,   public DropTargetHelper
	{
		OReportPage*				        m_pPage;
		OSectionView*				        m_pView;
		OSectionWindow*				        m_pParent;
		::std::auto_ptr<DlgEdFunc>	        m_pFunc;
        ::boost::shared_ptr<OReportModel>   m_pModel;
		::rtl::Reference< comphelper::OPropertyChangeMultiplexer>				            m_pMulti;
		::rtl::Reference< comphelper::OPropertyChangeMultiplexer>				            m_pReportListener;
        ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >              m_xSection;
        sal_Int32                   m_nPaintEntranceCount;

		DlgEdMode					m_eMode;
		sal_Bool						m_bDialogModelChanged;
		sal_Bool					m_bInDrag;

		/** fills the section with all control from the report section
		*/
		void fill();
        /** checks all objects if they fit in the new paper width.
        */
        void impl_adjustObjectSizePosition(sal_Int32 i_nPaperWidth,sal_Int32 i_nLeftMargin,sal_Int32 i_nRightMargin);

        OReportSection(OReportSection&);
        void operator =(OReportSection&);
    protected:
        // DropTargetHelper overridables
		virtual sal_Int8	AcceptDrop( const AcceptDropEvent& _rEvt );
		virtual sal_Int8	ExecuteDrop( const ExecuteDropEvent& _rEvt );

		// window overrides
		virtual void        Paint( const Rectangle& rRect );
		virtual void 		MouseMove( const MouseEvent& rMEvt );
		virtual void		Command( const CommandEvent& rCEvt );
		virtual void		Resize();

		// OPropertyChangeListener
		virtual void	_propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& _rEvent) throw( ::com::sun::star::uno::RuntimeException);
	public:
		OReportSection(OSectionWindow* _pParent,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection);
		virtual ~OReportSection();

        // window overrides
		virtual void 		MouseButtonDown( const MouseEvent& rMEvt );
        virtual void 		MouseButtonUp( const MouseEvent& rMEvt );

		/** copies the current selection in this section
            @param  _rAllreadyCopiedObjects This is an out/in put param which contains all already copied objects.
		*/
		void Copy(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rAllreadyCopiedObjects);

        void Copy(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rAllreadyCopiedObjects,bool _bEraseAnddNoClone);

		/** paste a new control in this section
            @param  _aAllreadyCopiedObjects objects to paste into the section. Only objects are pasted where the name is equal to the section name.
            @param  _bForce If set to <TRUE/> than the objects will be copied into this section. The name is not compared in this case.
		*/
		void Paste(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _aAllreadyCopiedObjects,bool _bForce = false);

		/** Deletes the current selection in this section
		*
		*/
		void Delete();

		/** All objects will be marked.
		*/
		void SelectAll(const sal_uInt16 _nObjectType);

		/** makes the grid visible
		*
		* \param _bVisible when <TRUE/> the grid is made visible
		*/
		void SetGridVisible(sal_Bool _bVisible);

		inline OSectionWindow*		getSectionWindow() const { return m_pParent; }
		inline OSectionView&		getSectionView() const { return *m_pView; }
		inline OReportPage*			getPage() const { return m_pPage; }
		inline ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection > getSection() const { return m_xSection; }

		void			SetDialogModelChanged( sal_Bool bChanged = sal_True ) { m_bDialogModelChanged = bChanged; }
		sal_Bool			IsDialogModelChanged() const { return m_bDialogModelChanged; }
		DlgEdMode   	GetMode() const { return m_eMode; }
		void 			SetMode( DlgEdMode m_eMode );

		/** checks if the keycode is known by the child windows
			@param	_rCode	the keycode
			@return <TRUE/> if the keycode is handled otherwise <FALSE/>
		*/
		sal_Bool		handleKeyEvent(const KeyEvent& _rEvent);

		/** returns the current control report model or <NULL/>
		*/
		::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent > getCurrentControlModel() const;

        /** fills the vector with all selected control models
            /param  _rSelection The vector will be filled and will not be cleared before.
        */
        void fillControlModelSelection(::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rSelection) const;

        /** creates a default object (custom shape)
        *
        * @param _sType
        */
        void createDefault(const ::rtl::OUString& _sType);

        /** creates a new default custom shape
        *
        * \param _sType
        * \param _pObj
        */
        void createDefault(const ::rtl::OUString& _sType,SdrObject* _pObj);
        void stopScrollTimer();

        /** deactivate the currect active ole object if any
        */
        void    deactivateOle();

        /** returns true when an ole object is currently active
        */
        bool isUiActive() const;
	};
//==================================================================
}	//rptui
//==================================================================
#endif // REPORT_REPORTSECTION_HXX

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#ifndef SWISSARMYKNIFE_BITS_UTILS_HPP
#define SWISSARMYKNIFE_BITS_UTILS_HPP

#include <pre/detail/namespace_compatibility.hpp>

#include <iostream>
#include <bitset>
#include <string>
#include <sstream>
#include <math.h>
#include <boost/assert.hpp>
#include <boost/cstdint.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/container/vector.hpp>

namespace pre { namespace bits {

    /**
     * \brief Create string representation of the dynamic bitset given
     * \param bitset
     */
    inline std::string to_string(const boost::dynamic_bitset<boost::uint8_t> & bitset) {
        std::string result;
	    boost::to_string(bitset, result);
        return result;
    }

    /**
     * \brief Returns a string representation in bits of the int given.
     * \param value
     * \return The string representing the int given
     */
    template <typename uintX_t>
    inline std::string to_binstring(uintX_t value) {
        std::stringstream bitsRepresentation;
        const int shift = 8 * sizeof( uintX_t ) - 1;
        uintX_t one = 1;
        const uintX_t mask = one << shift;

        for ( size_t i = 1; i <= shift + 1; i++ ) {
          bitsRepresentation << ( value & mask ? '1' : '0' );
          value <<= 1;
        }

       return bitsRepresentation.str();
    }

    template <typename uintX_t, size_t bitsetSize>
    inline uintX_t to_uint(const std::bitset<bitsetSize> value) {
        const size_t uintX_t_size = 8 * sizeof ( uintX_t );

        BOOST_ASSERT(uintX_t_size >= bitsetSize);

        const uintX_t one = 1;
        const uintX_t zero = 0;
        uintX_t result = 0x0;

        for (size_t i=0; i < value.size(); ++i) {
            result |= (value.test(i)) ? (one << i) : (zero << i);
        }

        return result;
    }

    /**
     * \brief This function pads the given client bitset in the host by making a copy of clientBitset,
     * resizing the clientBitset or-ing it in the hostBitset and returning the hostBitset
     * \param hostBitset Which will get the clientBitset or-ed in it (i.e. The hostBitset get shifted to the left of the size of the clientBitset) hostBitset should be bigger than clientBitset
     * \param clientBitset The bitset which will be integrated in the host bitset
     * \return The hostBitset
     */
    inline boost::dynamic_bitset<boost::uint8_t> & shift_in_bitset(boost::dynamic_bitset<boost::uint8_t> &hostBitset, const boost::dynamic_bitset<boost::uint8_t> & clientBitset) {
        boost::dynamic_bitset<boost::uint8_t> clientBitsetCopy = clientBitset;
        clientBitsetCopy.resize(hostBitset.size()); // Resize to have the hostBitset size

        hostBitset <<= clientBitset.size();
        hostBitset |= clientBitsetCopy;

        return hostBitset;
    }

    /**
     * \brief This converts the given boost::dynamic_bitset to an array of 8-bit wide bytes.
     * \param bitset to convert
     * \return The vector of bytes resulting of the conversion in fixed byte width
     */
    inline boost::container::vector<boost::uint8_t> to_bytearray(const boost::dynamic_bitset<boost::uint8_t> &bitset) {
        size_t sizeBytesPadded = static_cast<size_t>(ceil(static_cast<double>(bitset.size()) / CHAR_BIT));
        boost::container::vector<boost::uint8_t> bytes(sizeBytesPadded);
        boost::container::vector<boost::uint8_t>::reverse_iterator iter = bytes.rbegin();
        boost::to_block_range(bitset, iter);

        return bytes;
    }

    /**
     * \brief Converts a byte array into a bitset
     * \param byteArray
     * \return The bitset corresponding to the given byte array
     */
    inline boost::dynamic_bitset<boost::uint8_t> to_bitset(const boost::container::vector<boost::uint8_t> &byteArray, size_t resultingBitSetSize = 0) {
        boost::dynamic_bitset<boost::uint8_t> bitset((resultingBitSetSize == 0) ? (byteArray.size() * CHAR_BIT) : resultingBitSetSize);
        boost::from_block_range(byteArray.rbegin(), byteArray.rend(), bitset);

        return bitset;
    }
}}

#endif

max_stars_repo_name: xplorfin/lib-cpp-pre

max_issues_repo_name: xplorfin/lib-cpp-pre

max_forks_repo_name: xplorfin/lib-cpp-pre


text:
#include "shuffled_range.h"
#include <boost/range/algorithm_ext/iota.hpp>
#include <boost/range/algorithm/random_shuffle.hpp>

namespace ann
{
    ShuffledRange::ShuffledRange(size_t rangeEnd)
    {
        mRange.resize(rangeEnd);
        boost::iota(mRange, 0);
        shuffle();
    }

    void ShuffledRange::shuffle()
    {
        boost::random_shuffle(mRange);
        mLastElement = mRange.begin();
    }

    ShuffledRange::IndexedRange ShuffledRange::getNextN(size_t nextRangeSize)
    {
        ShuffledRange::IndexedRange result(nextRangeSize);

        auto it = result.begin();
        while (it != result.end())
        {
            if (mLastElement == mRange.cend())
            {
                result.erase(it, result.end());
                break;
            }
            *it = *mLastElement;
            ++it;
            ++mLastElement;
        }
        return result;
    }

    bool ShuffledRange::hasMoreElements() const
    {
        return mLastElement != mRange.end();
    }
}


text:
/*********************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2020 Fabian Schoettler
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ********************************************************************************/

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

#include "../inc/gparser.hpp"

//BOOST_AUTO_TEST_SUITE( GSTATUS )

using namespace grblconnector;

BOOST_AUTO_TEST_CASE(gstatus_parse_modal_state)
{
    GParser gStatus;

    std::string line = "[GC:G1 G55 G18 G20 G91 G93 M4 M8 T1 F10 S10000]";

    gStatus.ParseLine(line);

    GModal modal = gStatus.GetMachineStatus();

    BOOST_CHECK_EQUAL(modal.motion, GModal::MOTION::motion_linear);
    BOOST_CHECK_EQUAL(modal.wcs, GModal::WCS::wcs_2);
    BOOST_CHECK_EQUAL(modal.plane, GModal::PLANE::plane_zx);
    BOOST_CHECK_EQUAL(modal.unit, GModal::UNIT::unit_inch);
    BOOST_CHECK_EQUAL(modal.distance, GModal::DISTANCE::distance_incremental);
    BOOST_CHECK_EQUAL(modal.feed, GModal::FEED::feed_inverse_time);
    BOOST_CHECK_EQUAL(modal.spindle, GModal::SPINDLE::spindle_ccw);
    BOOST_CHECK_EQUAL(modal.coolant, GModal::COOLANT::coolant_flood);
    BOOST_CHECK_EQUAL(modal.tool_number, 1);
    BOOST_CHECK_EQUAL(modal.feed_rate, 10);
    BOOST_CHECK_EQUAL(modal.spindle_speed, 10000);
}

BOOST_AUTO_TEST_CASE(gstatus_parse_status_report)
{
    GParser gStatus;

    std::string line = "[GC:G1 G55 G18 G20 G91 G93 M4 M8 T1 F10 S10000]";

    gStatus.ParseLine(line);

    GModal modal = gStatus.GetMachineStatus();

    BOOST_CHECK_EQUAL(modal.motion, GModal::MOTION::motion_linear);
    BOOST_CHECK_EQUAL(modal.wcs, GModal::WCS::wcs_2);
    BOOST_CHECK_EQUAL(modal.plane, GModal::PLANE::plane_zx);
    BOOST_CHECK_EQUAL(modal.unit, GModal::UNIT::unit_inch);
    BOOST_CHECK_EQUAL(modal.distance, GModal::DISTANCE::distance_incremental);
    BOOST_CHECK_EQUAL(modal.feed, GModal::FEED::feed_inverse_time);
    BOOST_CHECK_EQUAL(modal.spindle, GModal::SPINDLE::spindle_ccw);
    BOOST_CHECK_EQUAL(modal.coolant, GModal::COOLANT::coolant_flood);
    BOOST_CHECK_EQUAL(modal.tool_number, 1);
    BOOST_CHECK_EQUAL(modal.feed_rate, 10);
    BOOST_CHECK_EQUAL(modal.spindle_speed, 10000);
}

//BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ScotteC/GrblConnector

max_issues_repo_name: ScotteC/GrblConnector

max_forks_repo_name: ScotteC/GrblConnector


text:
// Copyright (c) 2012-2016 The Jobecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <util.h>

#include <support/allocators/secure.h>
#include <test/test_jobecoin.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(arena_tests)
{
    // Fake memory base address for testing
    // without actually using memory.
    void *synth_base = reinterpret_cast<void*>(0x08000000);
    const size_t synth_size = 1024*1024;
    Arena b(synth_base, synth_size, 16);
    void *chunk = b.alloc(1000);
#ifdef ARENA_DEBUG
    b.walk();
#endif
    BOOST_CHECK(chunk != nullptr);
    BOOST_CHECK(b.stats().used == 1008); // Aligned to 16
    BOOST_CHECK(b.stats().total == synth_size); // Nothing has disappeared?
    b.free(chunk);
#ifdef ARENA_DEBUG
    b.walk();
#endif
    BOOST_CHECK(b.stats().used == 0);
    BOOST_CHECK(b.stats().free == synth_size);
    try { // Test exception on double-free
        b.free(chunk);
        BOOST_CHECK(0);
    } catch(std::runtime_error &)
    {
    }

    void *a0 = b.alloc(128);
    void *a1 = b.alloc(256);
    void *a2 = b.alloc(512);
    BOOST_CHECK(b.stats().used == 896);
    BOOST_CHECK(b.stats().total == synth_size);
#ifdef ARENA_DEBUG
    b.walk();
#endif
    b.free(a0);
#ifdef ARENA_DEBUG
    b.walk();
#endif
    BOOST_CHECK(b.stats().used == 768);
    b.free(a1);
    BOOST_CHECK(b.stats().used == 512);
    void *a3 = b.alloc(128);
#ifdef ARENA_DEBUG
    b.walk();
#endif
    BOOST_CHECK(b.stats().used == 640);
    b.free(a2);
    BOOST_CHECK(b.stats().used == 128);
    b.free(a3);
    BOOST_CHECK(b.stats().used == 0);
    BOOST_CHECK_EQUAL(b.stats().chunks_used, 0);
    BOOST_CHECK(b.stats().total == synth_size);
    BOOST_CHECK(b.stats().free == synth_size);
    BOOST_CHECK_EQUAL(b.stats().chunks_free, 1);

    std::vector<void*> addr;
    BOOST_CHECK(b.alloc(0) == nullptr); // allocating 0 always returns nullptr
#ifdef ARENA_DEBUG
    b.walk();
#endif
    // Sweeping allocate all memory
    for (int x=0; x<1024; ++x)
        addr.push_back(b.alloc(1024));
    BOOST_CHECK(b.stats().free == 0);
    BOOST_CHECK(b.alloc(1024) == nullptr); // memory is full, this must return nullptr
    BOOST_CHECK(b.alloc(0) == nullptr);
    for (int x=0; x<1024; ++x)
        b.free(addr[x]);
    addr.clear();
    BOOST_CHECK(b.stats().total == synth_size);
    BOOST_CHECK(b.stats().free == synth_size);

    // Now in the other direction...
    for (int x=0; x<1024; ++x)
        addr.push_back(b.alloc(1024));
    for (int x=0; x<1024; ++x)
        b.free(addr[1023-x]);
    addr.clear();

    // Now allocate in smaller unequal chunks, then deallocate haphazardly
    // Not all the chunks will succeed allocating, but freeing nullptr is
    // allowed so that is no problem.
    for (int x=0; x<2048; ++x)
        addr.push_back(b.alloc(x+1));
    for (int x=0; x<2048; ++x)
        b.free(addr[((x*23)%2048)^242]);
    addr.clear();

    // Go entirely wild: free and alloc interleaved,
    // generate targets and sizes using pseudo-randomness.
    for (int x=0; x<2048; ++x)
        addr.push_back(0);
    uint32_t s = 0x12345678;
    for (int x=0; x<5000; ++x) {
        int idx = s & (addr.size()-1);
        if (s & 0x80000000) {
            b.free(addr[idx]);
            addr[idx] = 0;
        } else if(!addr[idx]) {
            addr[idx] = b.alloc((s >> 16) & 2047);
        }
        bool lsb = s & 1;
        s >>= 1;
        if (lsb)
            s ^= 0xf00f00f0; // LFSR period 0xf7ffffe0
    }
    for (void *ptr: addr)
        b.free(ptr);
    addr.clear();

    BOOST_CHECK(b.stats().total == synth_size);
    BOOST_CHECK(b.stats().free == synth_size);
}

/** Mock LockedPageAllocator for testing */
class TestLockedPageAllocator: public LockedPageAllocator
{
public:
    TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {}
    void* AllocateLocked(size_t len, bool *lockingSuccess) override
    {
        *lockingSuccess = false;
        if (count > 0) {
            --count;

            if (lockedcount > 0) {
                --lockedcount;
                *lockingSuccess = true;
            }

            return reinterpret_cast<void*>(0x08000000 + (count<<24)); // Fake address, do not actually use this memory
        }
        return 0;
    }
    void FreeLocked(void* addr, size_t len) override
    {
    }
    size_t GetLimit() override
    {
        return std::numeric_limits<size_t>::max();
    }
private:
    int count;
    int lockedcount;
};

BOOST_AUTO_TEST_CASE(lockedpool_tests_mock)
{
    // Test over three virtual arenas, of which one will succeed being locked
    std::unique_ptr<LockedPageAllocator> x(new TestLockedPageAllocator(3, 1));
    LockedPool pool(std::move(x));
    BOOST_CHECK(pool.stats().total == 0);
    BOOST_CHECK(pool.stats().locked == 0);

    // Ensure unreasonable requests are refused without allocating anything
    void *invalid_toosmall = pool.alloc(0);
    BOOST_CHECK(invalid_toosmall == nullptr);
    BOOST_CHECK(pool.stats().used == 0);
    BOOST_CHECK(pool.stats().free == 0);
    void *invalid_toobig = pool.alloc(LockedPool::ARENA_SIZE+1);
    BOOST_CHECK(invalid_toobig == nullptr);
    BOOST_CHECK(pool.stats().used == 0);
    BOOST_CHECK(pool.stats().free == 0);

    void *a0 = pool.alloc(LockedPool::ARENA_SIZE / 2);
    BOOST_CHECK(a0);
    BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE);
    void *a1 = pool.alloc(LockedPool::ARENA_SIZE / 2);
    BOOST_CHECK(a1);
    void *a2 = pool.alloc(LockedPool::ARENA_SIZE / 2);
    BOOST_CHECK(a2);
    void *a3 = pool.alloc(LockedPool::ARENA_SIZE / 2);
    BOOST_CHECK(a3);
    void *a4 = pool.alloc(LockedPool::ARENA_SIZE / 2);
    BOOST_CHECK(a4);
    void *a5 = pool.alloc(LockedPool::ARENA_SIZE / 2);
    BOOST_CHECK(a5);
    // We've passed a count of three arenas, so this allocation should fail
    void *a6 = pool.alloc(16);
    BOOST_CHECK(!a6);

    pool.free(a0);
    pool.free(a2);
    pool.free(a4);
    pool.free(a1);
    pool.free(a3);
    pool.free(a5);
    BOOST_CHECK(pool.stats().total == 3*LockedPool::ARENA_SIZE);
    BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE);
    BOOST_CHECK(pool.stats().used == 0);
}

// These tests used the live LockedPoolManager object, this is also used
// by other tests so the conditions are somewhat less controllable and thus the
// tests are somewhat more error-prone.
BOOST_AUTO_TEST_CASE(lockedpool_tests_live)
{
    LockedPoolManager &pool = LockedPoolManager::Instance();
    LockedPool::Stats initial = pool.stats();

    void *a0 = pool.alloc(16);
    BOOST_CHECK(a0);
    // Test reading and writing the allocated memory
    *((uint32_t*)a0) = 0x1234;
    BOOST_CHECK(*((uint32_t*)a0) == 0x1234);

    pool.free(a0);
    try { // Test exception on double-free
        pool.free(a0);
        BOOST_CHECK(0);
    } catch(std::runtime_error &)
    {
    }
    // If more than one new arena was allocated for the above tests, something is wrong
    BOOST_CHECK(pool.stats().total <= (initial.total + LockedPool::ARENA_SIZE));
    // Usage must be back to where it started
    BOOST_CHECK(pool.stats().used == initial.used);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Arinerron/jobecoin

max_issues_repo_name: Arinerron/jobecoin

max_forks_repo_name: Arinerron/jobecoin


text:
/** @file "/owlcpp/lib/rdf/test/std_nodes_custom_run.cpp"
part of owlcpp project.
@n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt.
@n Copyright Mikhail K Levin 2013
*******************************************************************************/
#define CATCH_CONFIG_MAIN

#include <catch2/catch.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>

#include <owlcpp/rdf/map_std.hpp>
#include <owlcpp/terms/node_tags_system.hpp>
#include <owlcpp/terms/node_tags_owl.hpp>
#include <owlcpp/terms/node_iri_tag_macro.hpp>
#include <string>
#include <iri_tag_vector.hpp>
#include <node_tag_vector_system.hpp>
#include <node_tag_vector_owl.hpp>

OWLCPP_NAMESPACE_TAG_TYPE(
         custom, "cst", "http://custom-ns.net", OWLCPP_NAMESPACE_TAGS_TOTAL
);

#define TUPLE(z, n, text) ((custom)(BOOST_PP_CAT(text, n)))

#define CUSTOM_TERMS_1_N0_ OWLCPP_NODE_TAGS_TOTAL
#define CUSTOM_TERMS_1 BOOST_PP_REPEAT_FROM_TO_1ST(0, 50, TUPLE, term)
#define CUSTOM_TERMS_2_N0_ (OWLCPP_NODE_TAGS_TOTAL + 50)
#define CUSTOM_TERMS_2 BOOST_PP_REPEAT_FROM_TO_1ST(50, 100, TUPLE, term)
#define CUSTOM_TERMS_3_N0_ (OWLCPP_NODE_TAGS_TOTAL + 100)
#define CUSTOM_TERMS_3 BOOST_PP_REPEAT_FROM_TO_1ST(100, 150, TUPLE, term)
#define CUSTOM_TERMS_4_N0_ (OWLCPP_NODE_TAGS_TOTAL + 150)
#define CUSTOM_TERMS_4 BOOST_PP_REPEAT_FROM_TO_1ST(150, 200, TUPLE, term)

#define OWLCPP_MANY_NODE_TAG_TYPE_MACRO_(r, n0, i, e) \
OWLCPP_NODE_TAG_TYPE( \
         OWLCPP_NODE_TYPE_NAME(e), \
         BOOST_PP_SEQ_ELEM(0,e), \
         BOOST_PP_STRINGIZE(BOOST_PP_SEQ_HEAD(BOOST_PP_SEQ_REVERSE(e))), \
         (n0 + i) \
); \
BOOST_PP_EMPTY() \
/* */

#define OWLCPP_GENERATE_MANY_NODE_TAGS(seq, n0) \
         BOOST_PP_SEQ_FOR_EACH_I(OWLCPP_MANY_NODE_TAG_TYPE_MACRO_, n0, seq)

OWLCPP_GENERATE_MANY_NODE_TAGS(CUSTOM_TERMS_1, CUSTOM_TERMS_1_N0_)
OWLCPP_GENERATE_MANY_NODE_TAGS(CUSTOM_TERMS_2, CUSTOM_TERMS_2_N0_)
OWLCPP_GENERATE_MANY_NODE_TAGS(CUSTOM_TERMS_3, CUSTOM_TERMS_3_N0_)
OWLCPP_GENERATE_MANY_NODE_TAGS(CUSTOM_TERMS_4, CUSTOM_TERMS_4_N0_)
#include OWLCPP_MPL_VECTORnn_HPP(CUSTOM_TERMS_1)

typedef OWLCPP_TERM_MPL_VECTOR(CUSTOM_TERMS_1) mpl_vector_terms_custom1_t;
typedef OWLCPP_TERM_MPL_VECTOR(CUSTOM_TERMS_2) mpl_vector_terms_custom2_t;
typedef OWLCPP_TERM_MPL_VECTOR(CUSTOM_TERMS_3) mpl_vector_terms_custom3_t;
typedef OWLCPP_TERM_MPL_VECTOR(CUSTOM_TERMS_4) mpl_vector_terms_custom4_t;

using owlcpp::Map_std;

struct Custom_nodes {
   void operator()(Map_std& map) const {
      owlcpp::detail::Ns_inserter ns_ins(map);
      boost::mpl::for_each<owlcpp::terms::mpl_vector_iris_t>(ns_ins);

      owlcpp::detail::Node_inserter node_ins(map);
      boost::mpl::for_each<owlcpp::terms::mpl_vector_terms_rdfs_t>(node_ins);
      boost::mpl::for_each<owlcpp::terms::mpl_vector_terms_rdf_t>(node_ins);
      boost::mpl::for_each<owlcpp::terms::mpl_vector_terms_xsd_t>(node_ins);
      boost::mpl::for_each<owlcpp::terms::mpl_vector_terms_owl1_t>(node_ins);
      boost::mpl::for_each<owlcpp::terms::mpl_vector_terms_owl2_t>(node_ins);
      boost::mpl::for_each<mpl_vector_terms_custom1_t>(node_ins);
      boost::mpl::for_each<mpl_vector_terms_custom2_t>(node_ins);
      boost::mpl::for_each<mpl_vector_terms_custom3_t>(node_ins);
      boost::mpl::for_each<mpl_vector_terms_custom4_t>(node_ins);
   }
};

namespace t = owlcpp::terms;

SCENARIO("Custom node test") {

    GIVEN("I have a map std.") {

        Map_std const& ms = Map_std::get(Custom_nodes());

        THEN("It should work as expected.") {

            REQUIRE( ms.find(t::owl_Class::id()) );
            REQUIRE(ms[t::owl_Class::id()].fragment().compare("Class") == 0);
            REQUIRE(custom_term190::id()() > 300U);
            REQUIRE( ms.find(custom_term190::id()) );
            REQUIRE(ms[custom_term190::id()].fragment() == "term190");
        }
    }
}


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

#include "bencode_string_parser.h"
#include <boost/lexical_cast.hpp>
#include <cassert>
#include <cctype>

namespace decof {

namespace scgi {

bencode_string_parser::bencode_string_parser()
{
    reset();
}

void bencode_string_parser::reset()
{
    data.clear();
    state_ = string_length;
    length_str_.clear();
}

bencode_string_parser::result_type bencode_string_parser::consume(char input) noexcept
{
    try {
        switch (state_) {
            case string_length:
                if (std::isdigit(input))
                    length_str_.push_back(input);
                else if (input == ':') {
                    length_ = boost::lexical_cast<size_t>(length_str_);
                    state_  = string;
                    if (length_ == 0)
                        return good;
                } else
                    return bad;
                break;
            case string:
                data.push_back(input);
                length_ -= 1;
                if (length_ == 0)
                    return good;
                break;
            default:
                assert(false);
        }
    } catch (...) {
        return bad;
    }

    return indeterminate;
}

} // namespace scgi

} // namespace decof


text:
#pragma once

#include "../error.hpp"
#include "../http/request.hpp"
#include "../type_traits.hpp"
#include "../utils.hpp"
#include "../websocket/stream.hpp"
#include "malloy/core/detail/action_queue.hpp"

#include <boost/asio/io_context.hpp>
#include <boost/asio/post.hpp>
#include <boost/beast/core/error.hpp>
#include <fmt/format.h>
#include <spdlog/spdlog.h>

#include <concepts>
#include <functional>
#include <memory>

namespace malloy::websocket
{

    /**
     * @class connection
     * @tparam isClient: Whether it is the client end of a websocket connection
     * @brief Represents a connection via the WebSocket protocol
     * @details Provides basic management of a websocket connection. Will close the
     * connection on destruction. The interface is entirely asynchronous and uses
     * callback functions
     * @note The functions: connect, accept, disconnect, send, and read are fully threadsafe. Calls to these functions will wait asynchronously until all other
     * queued actions are completed.
     */
    template<bool isClient>
    class connection :
        public std::enable_shared_from_this<connection<isClient>>
    {
        using ws_executor_t = std::invoke_result_t<decltype(&stream::get_executor), stream*>;
        using act_queue_t = malloy::detail::action_queue<ws_executor_t>;

    public:
        using handler_t = std::function<void(const malloy::http::request<>&, const std::shared_ptr<connection>&)>;

        /**
         * The connection state.
         */
        enum class state
        {
            handshaking,
            active,
            closing,
            closed,
            inactive, // Initial state
        };

        /**
         * See stream::set_binary(bool)
         */
        void set_binary(const bool enabled) { m_ws.set_binary(enabled); }

        /**
         * See stream::binary()
         */
        [[nodiscard]] bool binary() { return m_ws.binary(); }

        /**
         * @brief Construct a new connection object
         * @param logger Logger to use. Must not be `nullptr`
         * @param ws Stream to use. May be unopened/connected but in that case
         * `connect` must be called before this connection can be used
         */
        static
        std::shared_ptr<connection>
        make(const std::shared_ptr<spdlog::logger> logger, stream&& ws, const std::string& agent_string)
        {
            // We have to emulate make_shared here because the ctor is private
            connection* me = nullptr;
            try {
                me = new connection{logger, std::move(ws), agent_string};
                return std::shared_ptr<connection>{me};
            }
            catch (...) {
                delete me;
                throw;
            }
        }

        /**
         * @brief Connect to a remote (websocket) endpoint
         * @note Only available if isClient == true
         * @param target The list of resolved endpoints to connect to
         * @param resource A suburl to make the connection on (e.g. `/api/websocket`)
         * @param done Callback invoked on accepting the handshake or an error
         * occurring
         */
        template<concepts::accept_handler Callback>
        void
        connect(const boost::asio::ip::tcp::resolver::results_type& target, const std::string& resource, Callback&& done) requires(isClient)
        {

            if (m_state != state::inactive) {
                throw std::logic_error{"connect() called on already active websocket connection"};
            }
                // Set the timeout for the operation
                m_ws.get_lowest_layer([&, me = this->shared_from_this(), this, done = std::forward<Callback>(done), resource](auto& sock) mutable {
                    sock.expires_after(std::chrono::seconds(30));

                    // Make the connection on the IP address we get from a lookup
                    sock.async_connect(
                        target,
                        [this, me, target, done = std::forward<Callback>(done), resource](auto ec, auto ep) mutable {
                            if (ec) {
                                done(ec);
                            } else {
                            me->on_connect(ec, ep, resource, [this, done = std::forward<Callback>(done)](auto ec) mutable {
                                go_active();
                                std::invoke(std::forward<decltype(done)>(done), ec);
                                    });
                            }
                        });
                });
        }

        /**
         * @brief Accept an incoming connection
         * @note This is only available if isClient == false
         * @note Calling this function is only valid if `make` was passed a
         * connected stream ready to be accepted (e.g. http stream that `req` was
         * read from)
         * @warning `done` is only invoked on successful connection
         * @param req The request to accept. boost::beast::websocket::is_upgrade(req) must be true
         * @param done Callback invoked on successful accepting of the request. NOT
         * invoked on failure. Must be invocable without any parameters (i.e. `f()`)
         */
        template<class Body, class Fields, std::invocable<> Callback>
        void
        accept(const boost::beast::http::request<Body, Fields>& req, Callback&& done) requires(!isClient)
        {
            if (m_state != state::inactive) {
                throw std::logic_error{"accept() called on already active websocket connection"};
            }

            // Update state
            m_state = state::handshaking;

            m_logger->trace("accept()");

            setup_connection();

            // Accept the websocket handshake
            m_ws.async_accept(req, [this, me = this->shared_from_this(), done = std::forward<decltype(done)>(done)](malloy::error_code ec) mutable {
                m_logger->trace("on_accept()");

                // Check for errors
                if (ec) {
                    m_logger->error("on_accept(): {}", ec.message());
                    return;
                }

                // We're good to go
                go_active();

                std::invoke(std::forward<decltype(done)>(done));
            });
        }

        /**
         * @brief Disconnect/stop/close the connection.
         * @note Attempting to send or receive after calling this will result in error(s).
         *
         * @param why Reason why the connection is being closed.
         *
         * @sa force_disconnect()
         */
        void
        disconnect(boost::beast::websocket::close_reason why = boost::beast::websocket::normal)
        {
            if (m_state == state::closed || m_state == state::closing) {
                throw std::logic_error{"disconnect() called on closed or closing websocket connection"};
            }
            auto build_act = [this, why, me = this->shared_from_this()](const auto& on_done) mutable {
                // Check we haven't been beaten
                if (m_state == state::closed || m_state == state::closing) {
                    on_done();
                    return;
                }
                do_disconnect(why, on_done);
            };

            // We queue in both read and write, and whichever gets there first wins
            m_write_queue.push(build_act);
            m_read_queue.push(build_act);
        }

        /**
         * @brief Same as disconnect, but bypasses all queues and runs immediately
         *
         * @sa disconnect()
         */
        void
        force_disconnect(boost::beast::websocket::close_reason why = boost::beast::websocket::normal)
        {
            if (m_state == state::inactive)
                throw std::logic_error{"force_disconnect() called on inactive websocket connection"};

            else if (m_state == state::closed || m_state == state::closing)
                return; // Already disconnecting

            do_disconnect(why, []{});
        }

        /**
         * @brief Read a complete message into a buffer
         * @warning The caller is responsible for keeping the memory used by `buff`
         * alive until `done` is called
         *
         * @param buff Buffer to put the message into. Must satisfy dynamic_buffer @ref general_concepts
         * @param done Callback invoked on the message being read
         * (successfully or otherwise). Must satisfy async_read_handler @ref
         * general_concepts. Will NOT be invoked on the websocket being closed
         * before the message could be fully or partially read
         *
         */
        void
        read(concepts::dynamic_buffer auto& buff, concepts::async_read_handler auto&& done)
        {
            m_logger->trace("read()");
            m_read_queue.push(
                [this, me = this->shared_from_this(),
                 buff = &buff /* Capturing reference by value copies the object */,
                 done = std::forward<decltype(done)>(done)](const auto& on_done) mutable {
                    assert(buff != nullptr);
                    m_ws.async_read(*buff, [me, on_done, done = std::forward<decltype(done)>(done)](auto ec, auto size) mutable {
                        std::invoke(std::forward<decltype(done)>(done), ec, size);
                        on_done();
                    });
                });
        }

        /**
         * @brief Send the contents of a buffer to the client.
         * @warning The caller is responsible for keeping the memory of `payload`
         * alive until `done` is invoked
         *
         * @param payload The payload to send. Must satisfy const_buffer_sequence
         *  @ref general_concepts
         * @param done Callback invoked after the message is written (successfully
         * or otherwise). Must satisfy async_read_handler @ref general_concepts
         */
        template<concepts::async_read_handler Callback>
        void
        send(const concepts::const_buffer_sequence auto& payload, Callback&& done)
        {
                m_logger->trace("send(). payload size: {}", payload.size());
                m_write_queue.push([buff = payload, done = std::forward<Callback>(done), this, me = this->shared_from_this()](const auto& on_done) mutable {
                    m_ws.async_write(buff, [this, me, on_done, done = std::forward<decltype(done)>(done)](auto ec, auto size) mutable {
                        on_write(ec, size);
                        std::invoke(std::forward<Callback>(done), ec, size);
                        on_done();
                    });
                });
        }

    private:
        enum class sending_state
        {
            idling,
            sending
        };

        enum sending_state m_sending_state = sending_state::idling;
        std::shared_ptr<spdlog::logger> m_logger;
        stream m_ws;
        std::string m_agent_string;
        act_queue_t m_write_queue;
        act_queue_t m_read_queue;

        std::atomic<state> m_state{state::inactive};

        connection(
            std::shared_ptr<spdlog::logger> logger, stream&& ws, std::string agent_str) :
            m_logger(std::move(logger)),
            m_ws{std::move(ws)},
            m_agent_string{std::move(agent_str)},
            m_write_queue{boost::asio::make_strand(m_ws.get_executor())},
            m_read_queue{boost::asio::make_strand(m_ws.get_executor())}
        {
            // Sanity check logger
            if (!m_logger)
                throw std::invalid_argument("no valid logger provided.");
        }

        void
        go_active()
        {
            m_state = state::active;
            m_read_queue.run();
            m_write_queue.run();
        }

        void
        setup_connection()
        {
            // Set suggested timeout settings for the websocket
            m_ws.set_option(
                boost::beast::websocket::stream_base::timeout::suggested(
                    isClient ? boost::beast::role_type::client : boost::beast::role_type::server));

            const auto agent_field = isClient ? malloy::http::field::user_agent : malloy::http::field::server;
            m_ws.set_option(
                boost::beast::websocket::stream_base::decorator(
                    [this, agent_field](boost::beast::websocket::request_type& req) {
                        req.set(agent_field, m_agent_string);
                    }));
        }

        void
        do_disconnect(boost::beast::websocket::close_reason why, const std::invocable<> auto& on_done)
        {
            // Update state
            m_state = state::closing;

            m_ws.async_close(why, [me = this->shared_from_this(), this, on_done](auto ec){
                if (ec) {
                    m_logger->error("could not close websocket: '{}'", ec.message());    // TODO: See #40
                } else {
                    on_close();
                }
                on_done();
            });
        }

        void
        on_connect(
            boost::beast::error_code ec,
            boost::asio::ip::tcp::resolver::results_type::endpoint_type ep,
            const std::string& resource,
            concepts::accept_handler auto&& on_handshake)
        {
            m_logger->trace("on_connect()");

            if (ec) {
                m_logger->error("on_connect(): {}", ec.message());
                return;
            }
            m_ws.get_lowest_layer([](auto& s) { s.expires_never(); }); // websocket has its own timeout system that conflicts

            // Update the m_host string. This will provide the value of the
            // Host HTTP header during the WebSocket handshake.
            // See https://tools.ietf.org/html/rfc7230#section-5.4
            const std::string host = fmt::format("{}:{}", ep.address().to_string(), ep.port());

#if MALLOY_FEATURE_TLS
            if constexpr (isClient) {
                if (m_ws.is_tls()) {
                    // TODO: Should this be a seperate method?
                    m_ws.async_handshake_tls(boost::asio::ssl::stream_base::handshake_type::client, [on_handshake = std::forward<decltype(on_handshake)>(on_handshake),
                                                                                resource, host, me = this->shared_from_this()](auto ec) mutable {
                        if (ec)
                            on_handshake(ec);

                        me->on_ready_for_handshake(host, resource, std::forward<decltype(on_handshake)>(on_handshake));
                    });
                    return;
                }
            }
#endif
            on_ready_for_handshake(host, resource, std::forward<decltype(on_handshake)>(on_handshake));
        }

        void
        on_ready_for_handshake(const std::string& host, const std::string& resource, concepts::accept_handler auto&& on_handshake)
        {
            // Turn off the timeout on the tcp_stream, because
            // the websocket stream has its own timeout system.
            m_ws.get_lowest_layer([](auto& s) { s.expires_never(); });
            setup_connection();

            // Perform the websocket handshake
            m_ws.async_handshake(
                host,
                resource,
                std::forward<decltype(on_handshake)>(on_handshake));
        }

        void
        on_write(auto ec, auto size)
        {
            if (ec) {
                m_logger->error("on_write failed for websocket connection: '{}'", ec.message());
                return;
            }

            m_logger->trace("on_write() wrote: '{}' bytes", size);

        }

        void
        on_close()
        {
            m_logger->trace("on_close()");

            m_state = state::closed;
        }
    };

}    // namespace malloy::websocket

max_stars_repo_name: Tectu/malloy

max_issues_repo_name: Tectu/malloy

max_forks_repo_name: Tectu/malloy


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//

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

#include <boost/compute/lambda.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/functional.hpp>
#include <boost/compute/algorithm/reduce.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/iterator/constant_iterator.hpp>
#include <boost/compute/iterator/counting_iterator.hpp>
#include <boost/compute/iterator/transform_iterator.hpp>
#include <boost/compute/types/complex.hpp>

#include "check_macros.hpp"
#include "context_setup.hpp"

namespace compute = boost::compute;

BOOST_AUTO_TEST_CASE(reduce_int)
{
    int data[] = { 1, 5, 9, 13, 17 };
    compute::vector<int> vector(data, data + 5, queue);
    int sum;
    compute::reduce(vector.begin(), vector.end(), &sum, compute::plus<int>(), queue);
    BOOST_CHECK_EQUAL(sum, 45);

    int product;
    compute::reduce(vector.begin(), vector.end(), &product, compute::multiplies<int>(), queue);
    BOOST_CHECK_EQUAL(product, 9945);
}

BOOST_AUTO_TEST_CASE(reduce_empty_vector)
{
    compute::vector<short> vector(context);

    short sum = 0;
    compute::reduce(vector.begin(), vector.end(), &sum, queue);
    BOOST_CHECK_EQUAL(sum, short(0));
}

BOOST_AUTO_TEST_CASE(reduce_doctest)
{
    int data[] = { 1, 2, 3, 4 };
    boost::compute::vector<int> vec(data, data + 4, queue);

//! [sum_int]
int sum = 0;
boost::compute::reduce(vec.begin(), vec.end(), &sum, queue);
//! [sum_int]

    BOOST_CHECK_EQUAL(sum, 10);
}

BOOST_AUTO_TEST_CASE(reduce_twos)
{
    using compute::uint_;

    compute::vector<uint_> vector(8, context);
    compute::fill(vector.begin(), vector.end(), uint_(2), queue);

    uint_ sum;
    compute::reduce(vector.begin(), vector.end(), &sum, compute::plus<uint_>(), queue);
    BOOST_CHECK_EQUAL(sum, uint_(16));

    uint_ product;
    compute::reduce(vector.begin(), vector.end(), &product, compute::multiplies<uint_>(), queue);
    BOOST_CHECK_EQUAL(product, uint_(256));
}

BOOST_AUTO_TEST_CASE(reduce_on_device)
{
    int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    compute::vector<int> input(data, data + 8, queue);
    compute::vector<int> result(2, context);
    compute::reduce(input.begin(), input.begin() + 4, result.begin(), queue);
    compute::reduce(input.begin() + 4, input.end(), result.end() - 1, queue);
    CHECK_RANGE_EQUAL(int, 2, result, (10, 26));
}

BOOST_AUTO_TEST_CASE(reduce_int_min_max)
{
    int data[] = { 11, 5, 92, 13, 42 };
    compute::vector<int> vector(data, data + 5, queue);
    int min_value;
    compute::reduce(
        vector.begin(),
        vector.end(),
        &min_value,
        compute::min<int>(),
        queue
    );
    BOOST_CHECK_EQUAL(min_value, 5);

    int max_value;
    compute::reduce(
        vector.begin(),
        vector.end(),
        &max_value,
        compute::max<int>(),
        queue
    );
    BOOST_CHECK_EQUAL(max_value, 92);
}

BOOST_AUTO_TEST_CASE(reduce_int2)
{
    std::vector<compute::int2_> data;
    for(int i = 0; i < 6; i++){
        compute::int2_ value;
        value[0] = i + 1;
        value[1] = 2 * i + 1;
        data.push_back(value);
    }

    compute::vector<compute::int2_> vector(data.begin(), data.end(), queue);

    compute::int2_ sum;
    compute::reduce(
        vector.begin(),
        vector.end(),
        &sum,
        queue
    );
    BOOST_CHECK_EQUAL(sum, compute::int2_(21, 36));
}

BOOST_AUTO_TEST_CASE(reduce_pinned_vector)
{
    int data[] = { 2, 5, 8, 11, 15 };
    std::vector<int> vector(data, data + 5);

    compute::buffer buffer(context,
                           vector.size() * sizeof(int),
                           compute::buffer::read_only | compute::buffer::use_host_ptr,
                           &vector[0]);

    int sum;
    compute::reduce(
        compute::make_buffer_iterator<int>(buffer, 0),
        compute::make_buffer_iterator<int>(buffer, 5),
        &sum,
        compute::plus<int>()
    );
    BOOST_CHECK_EQUAL(sum, 41);
}

BOOST_AUTO_TEST_CASE(reduce_constant_iterator)
{
    int result;
    compute::reduce(
        compute::make_constant_iterator(1, 0),
        compute::make_constant_iterator(1, 5),
        &result,
        queue
    );
    BOOST_CHECK_EQUAL(result, 5);

    compute::reduce(
        compute::make_constant_iterator(3, 0),
        compute::make_constant_iterator(3, 5),
        &result,
        queue
    );
    BOOST_CHECK_EQUAL(result, 15);

    compute::reduce(
        compute::make_constant_iterator(2, 0),
        compute::make_constant_iterator(2, 5),
        &result,
        compute::multiplies<int>(),
        queue
    );
    BOOST_CHECK_EQUAL(result, 32);
}

BOOST_AUTO_TEST_CASE(reduce_counting_iterator)
{
    int result;
    compute::reduce(
        compute::make_counting_iterator(1),
        compute::make_counting_iterator(10),
        &result,
        queue
    );
    BOOST_CHECK_EQUAL(result, 45);

    compute::reduce(
        compute::make_counting_iterator(1),
        compute::make_counting_iterator(5),
        &result,
        compute::multiplies<int>(),
        queue
    );
    BOOST_CHECK_EQUAL(result, 24);
}

BOOST_AUTO_TEST_CASE(reduce_transform_iterator)
{
    using ::boost::compute::_1;

    int data[] = { 1, 3, 5, 7, 9 };
    compute::vector<int> vector(data, data + 5, queue);

    int sum;
    compute::reduce(
        compute::make_transform_iterator(vector.begin(), _1 + 1),
        compute::make_transform_iterator(vector.end(), _1 + 1),
        &sum,
        queue
    );
    BOOST_CHECK_EQUAL(sum, 30);

    compute::reduce(
        compute::make_transform_iterator(vector.begin(), _1 > 4),
        compute::make_transform_iterator(vector.end(), _1 > 4),
        &sum,
        compute::plus<int>(),
        queue
    );
    BOOST_CHECK_EQUAL(sum, 3);

    compute::reduce(
        compute::make_transform_iterator(vector.begin(), _1 * _1),
        compute::make_transform_iterator(vector.end(), _1 * _1),
        &sum,
        queue
    );
    BOOST_CHECK_EQUAL(sum, 165);
}

BOOST_AUTO_TEST_CASE(reduce_complex)
{
    std::vector<std::complex<float> > data;
    data.push_back(std::complex<float>(1, 2));
    data.push_back(std::complex<float>(2, 4));
    data.push_back(std::complex<float>(3, 6));
    data.push_back(std::complex<float>(4, 8));

    compute::vector<std::complex<float> > vector(data.size(), context);
    compute::copy(data.begin(), data.end(), vector.begin(), queue);

    std::complex<float> result;
    compute::reduce(
        vector.begin(), vector.end(), &result, queue
    );
    BOOST_CHECK(result == std::complex<float>(10, 20));

    compute::reduce(
        vector.begin(), vector.end(), &result, compute::plus<std::complex<float> >(), queue
    );
    BOOST_CHECK(result == std::complex<float>(10, 20));

    compute::reduce(
        vector.begin(), vector.end(), &result, compute::multiplies<std::complex<float> >(), queue
    );
    BOOST_CHECK(result == std::complex<float>(-168, -576));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mikestaub/arangodb


text:
#include <actionlib/server/simple_action_server.h>
#include <geometry_msgs/PoseStamped.h>
#include <nav_msgs/Odometry.h>
#include <ros/ros.h>
#include <tf/transform_listener.h>

#include <mil_msgs/PoseTwistStamped.h>
#include <mil_tools/msg_helpers.hpp>
#include <mil_tools/param_helpers.hpp>
#include <ros_alarms/listener.hpp>

#include <mil_msgs/MoveToAction.h>
#include "C3Trajectory.h"
#include "c3_trajectory_generator/SetDisabled.h"

#include <waypoint_validity.hpp>

#include <boost/assign/list_of.hpp>
#include <boost/unordered_map.hpp>

using namespace std;
using namespace geometry_msgs;
using namespace nav_msgs;
using namespace mil_msgs;
using namespace mil_tools;
using namespace c3_trajectory_generator;

const boost::unordered_map<WAYPOINT_ERROR_TYPE, const std::string> WAYPOINT_ERROR_TO_STRING =
    boost::assign::map_list_of(WAYPOINT_ERROR_TYPE::OCCUPIED, "OCCUPIED")(WAYPOINT_ERROR_TYPE::UNKNOWN, "UNKNOWN")(
        WAYPOINT_ERROR_TYPE::UNOCCUPIED, "UNOCCUPIED")(WAYPOINT_ERROR_TYPE::ABOVE_WATER, "ABOVE_WATER")(
        WAYPOINT_ERROR_TYPE::NO_OGRID, "NO_OGRID")(WAYPOINT_ERROR_TYPE::NOT_CHECKED, "NOT_CHECKED")(
        WAYPOINT_ERROR_TYPE::OCCUPIED_TRAJECTORY, "OCCUPIED_TRAJECTORY");

subjugator::C3Trajectory::Point Point_from_PoseTwist(const Pose &pose, const Twist &twist)
{
  tf::Quaternion q;
  tf::quaternionMsgToTF(pose.orientation, q);

  subjugator::C3Trajectory::Point res;

  res.q.head(3) = xyz2vec(pose.position);
  tf::Matrix3x3(q).getRPY(res.q[3], res.q[4], res.q[5]);

  // clang-format off
  res.qdot.head(3) = vec2vec(tf::Matrix3x3(q) * vec2vec(xyz2vec(twist.linear)));
  res.qdot.tail(3) = (Eigen::Matrix3d() << 1, sin(res.q[3]) * tan(res.q[4]),
                        cos(res.q[3]) * tan(res.q[4]), 0, cos(res.q[3]), -sin(res.q[3]), 0,
                        sin(res.q[3]) / cos(res.q[4]), cos(res.q[3]) / cos(res.q[4])).finished() *
                      xyz2vec(twist.angular);
  // clang-format on
  return res;
}

PoseTwist PoseTwist_from_PointWithAcceleration(const subjugator::C3Trajectory::PointWithAcceleration &p)
{
  tf::Quaternion orient = tf::createQuaternionFromRPY(p.q[3], p.q[4], p.q[5]);

  PoseTwist res;

  res.pose.position = vec2xyz<Point>(p.q.head(3));
  quaternionTFToMsg(orient, res.pose.orientation);

  Eigen::Matrix3d worldangvel_from_eulerrates = (Eigen::Matrix3d() << 1, 0, -sin(p.q[4]), 0, cos(p.q[3]),
                                                 sin(p.q[3]) * cos(p.q[4]), 0, -sin(p.q[3]), cos(p.q[3]) * cos(p.q[4]))
                                                    .finished();

  res.twist.linear = vec2xyz<Vector3>(tf::Matrix3x3(orient.inverse()) * vec2vec(p.qdot.head(3)));
  res.twist.angular = vec2xyz<Vector3>(worldangvel_from_eulerrates * p.qdot.tail(3));

  res.acceleration.linear = vec2xyz<Vector3>(tf::Matrix3x3(orient.inverse()) * vec2vec(p.qdotdot.head(3)));
  res.acceleration.angular = vec2xyz<Vector3>(worldangvel_from_eulerrates * p.qdotdot.tail(3));

  return res;
}

Pose Pose_from_Waypoint(const subjugator::C3Trajectory::Waypoint &wp)
{
  Pose res;

  res.position = vec2xyz<Point>(wp.r.q.head(3));
  quaternionTFToMsg(tf::createQuaternionFromRPY(wp.r.q[3], wp.r.q[4], wp.r.q[5]), res.orientation);

  return res;
}

struct Node
{
  ros::NodeHandle nh;
  ros::NodeHandle private_nh;
  tf::TransformListener tf_listener;
  ros_alarms::AlarmListener<> kill_listener;

  string body_frame;
  string fixed_frame;
  subjugator::C3Trajectory::Limits limits;
  ros::Duration traj_dt;

  ros::Subscriber odom_sub;
  actionlib::SimpleActionServer<mil_msgs::MoveToAction> actionserver;
  ros::Publisher trajectory_pub;
  ros::Publisher trajectory_vis_pub;
  ros::Publisher waypoint_pose_pub;
  ros::ServiceServer set_disabled_service;

  ros::Timer update_timer;

  // Action result for waypoint validation
  mil_msgs::MoveToResult actionresult_;

  bool disabled;
  boost::scoped_ptr<subjugator::C3Trajectory> c3trajectory;
  ros::Time c3trajectory_t;

  subjugator::C3Trajectory::Waypoint current_waypoint;
  ros::Time current_waypoint_t;

  double linear_tolerance, angular_tolerance;

  WaypointValidity waypoint_validity_;

  bool set_disabled(SetDisabledRequest &request, SetDisabledResponse &response)
  {
    disabled = request.disabled;
    if (disabled)
    {
      c3trajectory.reset();
    }
    return true;
  }

  Node()
    : private_nh("~")
    , actionserver(nh, "moveto", false)
    , disabled(false)
    , kill_listener(nh, "kill")
    , waypoint_validity_(nh)
  {
    // Callback to reset trajectory when (un)killing
    auto reset_traj = [this](ros_alarms::AlarmProxy a) { this->c3trajectory.reset(); };
    kill_listener.addRaiseCb(reset_traj);

    // Make sure alarm integration is ok
    kill_listener.waitForConnection(ros::Duration(2));
    if (kill_listener.getNumConnections() < 1)
      throw std::runtime_error("The kill listener isn't connected to the alarm server");
    kill_listener.start();  // Fuck.

    fixed_frame = mil_tools::getParam<std::string>(private_nh, "fixed_frame");
    body_frame = mil_tools::getParam<std::string>(private_nh, "body_frame");

    limits.vmin_b = mil_tools::getParam<subjugator::Vector6d>(private_nh, "vmin_b");
    limits.vmax_b = mil_tools::getParam<subjugator::Vector6d>(private_nh, "vmax_b");
    limits.amin_b = mil_tools::getParam<subjugator::Vector6d>(private_nh, "amin_b");
    limits.amax_b = mil_tools::getParam<subjugator::Vector6d>(private_nh, "amax_b");
    limits.arevoffset_b = mil_tools::getParam<Eigen::Vector3d>(private_nh, "arevoffset_b");
    limits.umax_b = mil_tools::getParam<subjugator::Vector6d>(private_nh, "umax_b");
    traj_dt = mil_tools::getParam<ros::Duration>(private_nh, "traj_dt", ros::Duration(0.0001));

    odom_sub = nh.subscribe<Odometry>("odom", 1, boost::bind(&Node::odom_callback, this, _1));

    trajectory_pub = nh.advertise<PoseTwistStamped>("trajectory", 1);
    trajectory_vis_pub = private_nh.advertise<PoseStamped>("trajectory_v", 1);
    waypoint_pose_pub = private_nh.advertise<PoseStamped>("waypoint", 1);

    update_timer = nh.createTimer(ros::Duration(1. / 50), boost::bind(&Node::timer_callback, this, _1));

    actionserver.start();

    set_disabled_service = private_nh.advertiseService<SetDisabledRequest, SetDisabledResponse>(
        "set_disabled", boost::bind(&Node::set_disabled, this, _1, _2));
  }

  void odom_callback(const OdometryConstPtr &odom)
  {
    if (c3trajectory)
      return;  // already initialized
    if (kill_listener.isRaised() || disabled)
      return;  // only initialize when unkilled

    ros::Time now = ros::Time::now();

    subjugator::C3Trajectory::Point current = Point_from_PoseTwist(odom->pose.pose, odom->twist.twist);
    current.q[3] = current.q[4] = 0;              // zero roll and pitch
    current.qdot = subjugator::Vector6d::Zero();  // zero velocities

    c3trajectory.reset(new subjugator::C3Trajectory(current, limits));
    c3trajectory_t = now;

    current_waypoint = current;
    current_waypoint_t = now;
  }

  void timer_callback(const ros::TimerEvent &)
  {
    if (!c3trajectory)
      return;

    ros::Time now = ros::Time::now();

    auto old_waypoint = current_waypoint;

    if (actionserver.isNewGoalAvailable())
    {
      boost::shared_ptr<const mil_msgs::MoveToGoal> goal = actionserver.acceptNewGoal();
      current_waypoint =
          subjugator::C3Trajectory::Waypoint(Point_from_PoseTwist(goal->posetwist.pose, goal->posetwist.twist),
                                             goal->speed, !goal->uncoordinated, !goal->blind);
      current_waypoint_t = now;
      this->linear_tolerance = goal->linear_tolerance;
      this->angular_tolerance = goal->angular_tolerance;

      // Check if waypoint is valid
      std::pair<bool, WAYPOINT_ERROR_TYPE> checkWPResult = waypoint_validity_.is_waypoint_valid(
          Pose_from_Waypoint(current_waypoint), current_waypoint.do_waypoint_validation);
      actionresult_.error = WAYPOINT_ERROR_TO_STRING.at(checkWPResult.second);
      actionresult_.success = checkWPResult.first;
      if (checkWPResult.first == false)  // got a point that we should not move to
      {
        if (checkWPResult.second ==
            WAYPOINT_ERROR_TYPE::UNKNOWN)  // if unknown, check if there's a huge displacement with the new waypoint
        {
          auto a_point = Pose_from_Waypoint(current_waypoint);
          auto b_point = Pose_from_Waypoint(old_waypoint);
          // If moved more than .5m, then don't allow
          if (abs(a_point.position.x - b_point.position.x) > .5 || abs(a_point.position.y - b_point.position.y) > .5)
          {
            ROS_ERROR("can't move there! - need to rotate");
            current_waypoint = old_waypoint;
          }
        }
        // if point is occupied, reject move
        if (checkWPResult.second == WAYPOINT_ERROR_TYPE::OCCUPIED)
        {
          ROS_ERROR("can't move there! - waypoint is occupied");
          current_waypoint = old_waypoint;
        }
        // if point is above water, reject move
        if (checkWPResult.second == WAYPOINT_ERROR_TYPE::ABOVE_WATER)
        {
          ROS_ERROR("can't move there! - waypoint is above water");
          current_waypoint = old_waypoint;
        }
        if (checkWPResult.second == WAYPOINT_ERROR_TYPE::NO_OGRID)
        {
          ROS_ERROR("WaypointValidity - Did not recieve any ogrid");
        }
      }
    }
    if (actionserver.isPreemptRequested())
    {
      current_waypoint = c3trajectory->getCurrentPoint();
      current_waypoint.do_waypoint_validation = false;
      current_waypoint.r.qdot = subjugator::Vector6d::Zero();  // zero velocities
      current_waypoint_t = now;

      // don't try to make output c3 continuous when cancelled - instead stop as quickly as possible
      c3trajectory.reset(new subjugator::C3Trajectory(current_waypoint.r, limits));
      c3trajectory_t = now;
    }

    // Remember the previous trajectory
    auto old_trajectory = c3trajectory->getCurrentPoint();

    while (c3trajectory_t + traj_dt < now)
    {
      c3trajectory->update(traj_dt.toSec(), current_waypoint, (c3trajectory_t - current_waypoint_t).toSec());
      c3trajectory_t += traj_dt;
    }

    // Check if we will hit something while in trajectory the new trajectory
    geometry_msgs::Pose traj_point;  // Convert messages to correct type
    auto p = c3trajectory->getCurrentPoint();
    traj_point.position = vec2xyz<Point>(p.q.head(3));
    quaternionTFToMsg(tf::createQuaternionFromRPY(p.q[3], p.q[4], p.q[5]), traj_point.orientation);

    std::pair<bool, WAYPOINT_ERROR_TYPE> checkWPResult =
        waypoint_validity_.is_waypoint_valid(Pose_from_Waypoint(p), c3trajectory->do_waypoint_validation);

    if (checkWPResult.first == false && checkWPResult.second == WAYPOINT_ERROR_TYPE::OCCUPIED)
    {  // New trajectory will hit an occupied goal, so reject
      ROS_ERROR("can't move there! - bad trajectory");
      current_waypoint = old_trajectory;
      current_waypoint.do_waypoint_validation = false;
      current_waypoint.r.qdot = subjugator::Vector6d::Zero();  // zero velocities
      current_waypoint_t = now;

      c3trajectory.reset(new subjugator::C3Trajectory(current_waypoint.r, limits));
      c3trajectory_t = now;
      actionresult_.success = false;
      actionresult_.error = WAYPOINT_ERROR_TO_STRING.at(WAYPOINT_ERROR_TYPE::OCCUPIED_TRAJECTORY);
    }

    PoseTwistStamped msg;
    msg.header.stamp = c3trajectory_t;
    msg.header.frame_id = fixed_frame;
    msg.posetwist = PoseTwist_from_PointWithAcceleration(c3trajectory->getCurrentPoint());
    trajectory_pub.publish(msg);

    PoseStamped msgVis;
    msgVis.header = msg.header;
    msgVis.pose = msg.posetwist.pose;
    trajectory_vis_pub.publish(msgVis);

    PoseStamped posemsg;
    posemsg.header.stamp = c3trajectory_t;
    posemsg.header.frame_id = fixed_frame;
    posemsg.pose = Pose_from_Waypoint(current_waypoint);
    waypoint_pose_pub.publish(posemsg);

    if (actionserver.isActive() &&
        c3trajectory->getCurrentPoint().is_approximately(current_waypoint.r, max(1e-3, linear_tolerance),
                                                         max(1e-3, angular_tolerance)) &&
        current_waypoint.r.qdot == subjugator::Vector6d::Zero())
    {
      actionserver.setSucceeded(actionresult_);
    }
  }
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "c3_trajectory_generator");

  Node n;

  ros::spin();

  return 0;
}

max_stars_repo_name: DSsoto/SubjuGator

max_issues_repo_name: DSsoto/SubjuGator

max_forks_repo_name: DSsoto/SubjuGator


text:
/*! \file svg_test_2d_boxplot.cpp
   \brief Tests for svg 2d boxplot.
   \details
   \author Jacob Voytko and Paul A. Bristow
*/

// Copyright Jacob Voytko 2007
// Copyright Paul A. Bristow 2007

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

#include <boost/svg_plot/svg_2d_plot.hpp>
#include <boost/svg_plot/svg_boxplot.hpp>

#include <map>
#include <cmath>

using std::multimap;

double h(double x)
{
    return 50 / (x);
}

double f(double x)
{
    return 40 + 25 * sin(x * 50);
}

using std::cout;
using std::cin;

int main()
{
    using namespace boost::svg;
    std::multimap<double, double> data1;

    svg_boxplot my_plot;
    svg_2d_plot my_2d_plot;

    my_2d_plot.background_border_color(black)
           .title("Y axis label experiment")
           .y_major_labels_on(true)
           .y_label_on(true)
           .x_label_on(true)
           .x_major_labels_on(true)
           .plot_window_on(true)
           .y_external_style_on(true);

    for(double i=.1; i < 10; i+=.1)
    {
        data1.insert(std::pair<double, double>(i, h(i)));
    }

    my_2d_plot.plot(data1, "[50 / x]");

    my_2d_plot.write("D:\\axislabel_test.svg");

    return 0;
}


text:
/* p_integrand.c */
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <boost/math/special_functions/gamma.hpp>
extern "C"

/* Survival function for R^phi*W */
int RW_marginal_C(double *xval, double phi, double gamma, int n_xval, double *result){
    double tmp2 = pow(gamma/2, phi)/boost::math::tgamma(0.5);
    double tmp1, tmp0, a;
    a = 0.5-phi;

    for(int i=0; i<n_xval; i++){
        tmp1 = gamma/(2*pow(xval[i],1/phi));
        tmp0 = tmp2/(a*xval[i]);
        result[i] = boost::math::gamma_p(0.5L,tmp1) + boost::math::tgamma((long double)(a+1),tmp1)*tmp0-pow(tmp1,a)*exp(-tmp1)*tmp0; /*boost::math::gamma_p(0.5L,tmp1)+ tmp2*boost::math::tgamma(0.5-phi,tmp1)/xval[i];*/
    }
    return 1;
}