<commit_before>#include "AppInfo.h"
#include "FileUtils.h"
#include "Log.h"
#include "Platform.h"
#include "ProcessUtils.h"
#include "StringUtils.h"
#include "UpdateScript.h"
#include "UpdaterOptions.h"

#include "tinythread.h"

#if defined(PLATFORM_LINUX)
  #include "UpdateDialogGtkWrapper.h"
  #include "UpdateDialogAscii.h"
#endif

#if defined(PLATFORM_MAC)
  #include "MacBundle.h"
  #include "UpdateDialogCocoa.h"
#endif

#if defined(PLATFORM_WINDOWS)
  #include "UpdateDialogWin32.h"
#endif

#include <iostream>

#define UPDATER_VERSION "0.7"

void runWithUi(int argc, char** argv, UpdateInstaller* installer);

void runUpdaterThread(void* arg)
{
#ifdef PLATFORM_MAC
	// create an autorelease pool to free any temporary objects
	// created by Cocoa whilst handling notifications from the UpdateInstaller
	void* pool = UpdateDialogCocoa::createAutoreleasePool();
#endif

	try
	{
		UpdateInstaller* installer = static_cast<UpdateInstaller*>(arg);
		installer->run();
	}
	catch (const std::exception& ex)
	{
		LOG(Error,"Unexpected exception " + std::string(ex.what()));
	}

#ifdef PLATFORM_MAC
	UpdateDialogCocoa::releaseAutoreleasePool(pool);
#endif
}

#ifdef PLATFORM_MAC
extern unsigned char Info_plist[];
extern unsigned int Info_plist_len;

extern unsigned char mac_icns[];
extern unsigned int mac_icns_len;

bool unpackBundle(int argc, char** argv)
{
	MacBundle bundle(FileUtils::tempPath(),AppInfo::name());
	std::string currentExePath = ProcessUtils::currentProcessPath();

	if (currentExePath.find(bundle.bundlePath()) != std::string::npos)
	{
		// already running from a bundle
		return false;
	}
	LOG(Info,"Creating bundle " + bundle.bundlePath());

	// create a Mac app bundle
	std::string plistContent(reinterpret_cast<const char*>(Info_plist),Info_plist_len);
	std::string iconContent(reinterpret_cast<const char*>(mac_icns),mac_icns_len);
	bundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath());

	std::list<std::string> args;
	for (int i = 1; i < argc; i++)
	{
		args.push_back(argv[i]);
	}
	ProcessUtils::runSync(bundle.executablePath(),args);
	return true;
}
#endif

int main(int argc, char** argv)
{
#ifdef PLATFORM_MAC
	void* pool = UpdateDialogCocoa::createAutoreleasePool();
#endif

	Log::instance()->open(AppInfo::logFilePath());

#ifdef PLATFORM_MAC
	// when the updater is run for the first time, create a Mac app bundle
	// and re-launch the application from the bundle.  This permits
	// setting up bundle properties (such as application icon)
	if (unpackBundle(argc,argv))
	{
		return 0;
	}
#endif

	UpdaterOptions options;
	options.parse(argc,argv);
	if (options.showVersion)
	{
		std::cout << "Update installer version " << UPDATER_VERSION << std::endl;
		return 0;
	}

	UpdateInstaller installer;
	UpdateScript script;

	if (!options.scriptPath.empty())
	{
		script.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str()));
	}

	LOG(Info,"started updater. install-dir: " + options.installDir
	         + ", package-dir: " + options.packageDir
	         + ", wait-pid: " + intToStr(options.waitPid)
	         + ", script-path: " + options.scriptPath
	         + ", mode: " + intToStr(options.mode));

	installer.setMode(options.mode);
	installer.setInstallDir(options.installDir);
	installer.setPackageDir(options.packageDir);
	installer.setScript(&script);
	installer.setWaitPid(options.waitPid);
	installer.setForceElevated(options.forceElevated);

	if (options.mode == UpdateInstaller::Main)
	{
		runWithUi(argc,argv,&installer);
	}
	else
	{
		installer.run();
	}

#ifdef PLATFORM_MAC
	UpdateDialogCocoa::releaseAutoreleasePool(pool);
#endif

	return 0;
}

#ifdef PLATFORM_LINUX
void runWithUi(int argc, char** argv, UpdateInstaller* installer)
{
	UpdateDialogAscii asciiDialog;
	UpdateDialogGtkWrapper dialog;
	bool useGtk = dialog.init(argc,argv);
	if (useGtk)
	{
		installer->setObserver(&dialog);
	}
	else
	{
		asciiDialog.init();
		installer->setObserver(&asciiDialog);
	}
	tthread::thread updaterThread(runUpdaterThread,installer);
	if (useGtk)
	{
		dialog.exec();
	}
	updaterThread.join();
}
#endif

#ifdef PLATFORM_MAC
void runWithUi(int argc, char** argv, UpdateInstaller* installer)
{
	UpdateDialogCocoa dialog;
	installer->setObserver(&dialog);
	dialog.init();
	tthread::thread updaterThread(runUpdaterThread,installer);
	dialog.exec();
	updaterThread.join();
}
#endif

#ifdef PLATFORM_WINDOWS
// application entry point under Windows
int CALLBACK WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR lpCmdLine,
                     int nCmdShow)
{
	int argc = 0;
	char** argv;
	ProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv);
	return main(argc,argv);
}

void runWithUi(int argc, char** argv, UpdateInstaller* installer)
{
	UpdateDialogWin32 dialog;
	installer->setObserver(&dialog);
	dialog.init();
	tthread::thread updaterThread(runUpdaterThread,installer);
	dialog.exec();
	updaterThread.join();
}
#endif
<commit_msg>Bump the trunk version number to 0.8<commit_after>#include "AppInfo.h"
#include "FileUtils.h"
#include "Log.h"
#include "Platform.h"
#include "ProcessUtils.h"
#include "StringUtils.h"
#include "UpdateScript.h"
#include "UpdaterOptions.h"

#include "tinythread.h"

#if defined(PLATFORM_LINUX)
  #include "UpdateDialogGtkWrapper.h"
  #include "UpdateDialogAscii.h"
#endif

#if defined(PLATFORM_MAC)
  #include "MacBundle.h"
  #include "UpdateDialogCocoa.h"
#endif

#if defined(PLATFORM_WINDOWS)
  #include "UpdateDialogWin32.h"
#endif

#include <iostream>

#define UPDATER_VERSION "0.8"

void runWithUi(int argc, char** argv, UpdateInstaller* installer);

void runUpdaterThread(void* arg)
{
#ifdef PLATFORM_MAC
	// create an autorelease pool to free any temporary objects
	// created by Cocoa whilst handling notifications from the UpdateInstaller
	void* pool = UpdateDialogCocoa::createAutoreleasePool();
#endif

	try
	{
		UpdateInstaller* installer = static_cast<UpdateInstaller*>(arg);
		installer->run();
	}
	catch (const std::exception& ex)
	{
		LOG(Error,"Unexpected exception " + std::string(ex.what()));
	}

#ifdef PLATFORM_MAC
	UpdateDialogCocoa::releaseAutoreleasePool(pool);
#endif
}

#ifdef PLATFORM_MAC
extern unsigned char Info_plist[];
extern unsigned int Info_plist_len;

extern unsigned char mac_icns[];
extern unsigned int mac_icns_len;

bool unpackBundle(int argc, char** argv)
{
	MacBundle bundle(FileUtils::tempPath(),AppInfo::name());
	std::string currentExePath = ProcessUtils::currentProcessPath();

	if (currentExePath.find(bundle.bundlePath()) != std::string::npos)
	{
		// already running from a bundle
		return false;
	}
	LOG(Info,"Creating bundle " + bundle.bundlePath());

	// create a Mac app bundle
	std::string plistContent(reinterpret_cast<const char*>(Info_plist),Info_plist_len);
	std::string iconContent(reinterpret_cast<const char*>(mac_icns),mac_icns_len);
	bundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath());

	std::list<std::string> args;
	for (int i = 1; i < argc; i++)
	{
		args.push_back(argv[i]);
	}
	ProcessUtils::runSync(bundle.executablePath(),args);
	return true;
}
#endif

int main(int argc, char** argv)
{
#ifdef PLATFORM_MAC
	void* pool = UpdateDialogCocoa::createAutoreleasePool();
#endif

	Log::instance()->open(AppInfo::logFilePath());

#ifdef PLATFORM_MAC
	// when the updater is run for the first time, create a Mac app bundle
	// and re-launch the application from the bundle.  This permits
	// setting up bundle properties (such as application icon)
	if (unpackBundle(argc,argv))
	{
		return 0;
	}
#endif

	UpdaterOptions options;
	options.parse(argc,argv);
	if (options.showVersion)
	{
		std::cout << "Update installer version " << UPDATER_VERSION << std::endl;
		return 0;
	}

	UpdateInstaller installer;
	UpdateScript script;

	if (!options.scriptPath.empty())
	{
		script.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str()));
	}

	LOG(Info,"started updater. install-dir: " + options.installDir
	         + ", package-dir: " + options.packageDir
	         + ", wait-pid: " + intToStr(options.waitPid)
	         + ", script-path: " + options.scriptPath
	         + ", mode: " + intToStr(options.mode));

	installer.setMode(options.mode);
	installer.setInstallDir(options.installDir);
	installer.setPackageDir(options.packageDir);
	installer.setScript(&script);
	installer.setWaitPid(options.waitPid);
	installer.setForceElevated(options.forceElevated);

	if (options.mode == UpdateInstaller::Main)
	{
		runWithUi(argc,argv,&installer);
	}
	else
	{
		installer.run();
	}

#ifdef PLATFORM_MAC
	UpdateDialogCocoa::releaseAutoreleasePool(pool);
#endif

	return 0;
}

#ifdef PLATFORM_LINUX
void runWithUi(int argc, char** argv, UpdateInstaller* installer)
{
	UpdateDialogAscii asciiDialog;
	UpdateDialogGtkWrapper dialog;
	bool useGtk = dialog.init(argc,argv);
	if (useGtk)
	{
		installer->setObserver(&dialog);
	}
	else
	{
		asciiDialog.init();
		installer->setObserver(&asciiDialog);
	}
	tthread::thread updaterThread(runUpdaterThread,installer);
	if (useGtk)
	{
		dialog.exec();
	}
	updaterThread.join();
}
#endif

#ifdef PLATFORM_MAC
void runWithUi(int argc, char** argv, UpdateInstaller* installer)
{
	UpdateDialogCocoa dialog;
	installer->setObserver(&dialog);
	dialog.init();
	tthread::thread updaterThread(runUpdaterThread,installer);
	dialog.exec();
	updaterThread.join();
}
#endif

#ifdef PLATFORM_WINDOWS
// application entry point under Windows
int CALLBACK WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR lpCmdLine,
                     int nCmdShow)
{
	int argc = 0;
	char** argv;
	ProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv);
	return main(argc,argv);
}

void runWithUi(int argc, char** argv, UpdateInstaller* installer)
{
	UpdateDialogWin32 dialog;
	installer->setObserver(&dialog);
	dialog.init();
	tthread::thread updaterThread(runUpdaterThread,installer);
	dialog.exec();
	updaterThread.join();
}
#endif
<|endoftext|>


<commit_before>#include "global_include.h"
#include "action_impl.h"
#include "dronelink_impl.h"
#include "telemetry.h"
#include <unistd.h>

namespace dronelink {

ActionImpl::ActionImpl() :
    _in_air_state_known(false),
    _in_air(false)
{
}

ActionImpl::~ActionImpl()
{

}

void ActionImpl::init()
{
    using namespace std::placeholders; // for `_1`

    _parent->register_mavlink_message_handler(
        MAVLINK_MSG_ID_EXTENDED_SYS_STATE,
        std::bind(&ActionImpl::process_extended_sys_state, this, _1), (void *)this);
}

void ActionImpl::deinit()
{
    _parent->unregister_all_mavlink_message_handlers((void *)this);
}

Action::Result ActionImpl::arm() const
{
    if (!is_arm_allowed()) {
        return Action::Result::COMMAND_DENIED;
    }

    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_COMPONENT_ARM_DISARM,
                   DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::disarm() const
{
    if (!is_disarm_allowed()) {
        return Action::Result::COMMAND_DENIED;
    }

    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_COMPONENT_ARM_DISARM,
                   DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::kill() const
{
    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_COMPONENT_ARM_DISARM,
                   DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::takeoff() const
{
    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_NAV_TAKEOFF,
                   DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::land() const
{
    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_NAV_LAND,
                   DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::return_to_land() const
{
    uint8_t mode = MAV_MODE_AUTO_ARMED | VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED;
    uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;
    uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;

    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_DO_SET_MODE,
                   DeviceImpl::CommandParams {float(mode),
                                              float(custom_mode),
                                              float(custom_sub_mode),
                                              NAN, NAN, NAN, NAN}));
}

void ActionImpl::arm_async(const Action::result_callback_t &callback)
{
    if (!is_arm_allowed()) {
        callback(Action::Result::COMMAND_DENIED);
        return;
    }

    _parent->send_command_with_ack_async(
        MAV_CMD_COMPONENT_ARM_DISARM,
        DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::disarm_async(const Action::result_callback_t &callback)
{
    if (!is_disarm_allowed()) {
        callback(Action::Result::COMMAND_DENIED);
        return;
    }

    _parent->send_command_with_ack_async(
        MAV_CMD_COMPONENT_ARM_DISARM,
        DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::kill_async(const Action::result_callback_t &callback)
{
    _parent->send_command_with_ack_async(
        MAV_CMD_COMPONENT_ARM_DISARM,
        DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::takeoff_async(const Action::result_callback_t &callback)
{
    _parent->send_command_with_ack_async(
        MAV_CMD_NAV_TAKEOFF,
        DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::land_async(const Action::result_callback_t &callback)
{
    _parent->send_command_with_ack_async(
        MAV_CMD_NAV_LAND,
        DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::return_to_land_async(const Action::result_callback_t &callback)
{

    uint8_t mode = MAV_MODE_AUTO_ARMED | VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED;
    uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;
    uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;

    _parent->send_command_with_ack_async(
        MAV_CMD_DO_SET_MODE,
        DeviceImpl::CommandParams {float(mode),
                                   float(custom_mode),
                                   float(custom_sub_mode),
                                   NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

bool ActionImpl::is_arm_allowed() const
{
    if (!_in_air_state_known) {
        return false;
    }

    if (_in_air) {
        return false;
    }

    return true;
}

bool ActionImpl::is_disarm_allowed() const
{
    if (!_in_air_state_known) {
        Debug() << "in air state unknown";
        return false;
    }

    if (_in_air) {
        Debug() << "still in air";
        return false;
    }

    return true;
}

void ActionImpl::process_extended_sys_state(const mavlink_message_t &message)
{
    mavlink_extended_sys_state_t extended_sys_state;
    mavlink_msg_extended_sys_state_decode(&message, &extended_sys_state);
    if (extended_sys_state.landed_state == MAV_LANDED_STATE_IN_AIR) {
        _in_air = true;
    } else if (extended_sys_state.landed_state == MAV_LANDED_STATE_ON_GROUND) {
        _in_air = false;
    }
    _in_air_state_known = true;
}

Action::Result
ActionImpl::action_result_from_command_result(DeviceImpl::CommandResult result)
{
    switch (result) {
        case DeviceImpl::CommandResult::SUCCESS:
            return Action::Result::SUCCESS;
        case DeviceImpl::CommandResult::NO_DEVICE:
            return Action::Result::NO_DEVICE;
        case DeviceImpl::CommandResult::CONNECTION_ERROR:
            return Action::Result::CONNECTION_ERROR;
        case DeviceImpl::CommandResult::BUSY:
            return Action::Result::BUSY;
        case DeviceImpl::CommandResult::COMMAND_DENIED:
            return Action::Result::COMMAND_DENIED;
        case DeviceImpl::CommandResult::TIMEOUT:
            return Action::Result::TIMEOUT;
        default:
            return Action::Result::UNKNOWN;
    }
}

void ActionImpl::command_result_callback(DeviceImpl::CommandResult command_result,
                                         const Action::result_callback_t &callback)
{
    Action::Result action_result = action_result_from_command_result(command_result);

    callback(action_result);
}

} // namespace dronelink
<commit_msg>action: put armed flag correctly in DO_SET_MODE<commit_after>#include "global_include.h"
#include "action_impl.h"
#include "dronelink_impl.h"
#include "telemetry.h"
#include <unistd.h>

namespace dronelink {

ActionImpl::ActionImpl() :
    _in_air_state_known(false),
    _in_air(false)
{
}

ActionImpl::~ActionImpl()
{

}

void ActionImpl::init()
{
    using namespace std::placeholders; // for `_1`

    _parent->register_mavlink_message_handler(
        MAVLINK_MSG_ID_EXTENDED_SYS_STATE,
        std::bind(&ActionImpl::process_extended_sys_state, this, _1), (void *)this);
}

void ActionImpl::deinit()
{
    _parent->unregister_all_mavlink_message_handlers((void *)this);
}

Action::Result ActionImpl::arm() const
{
    if (!is_arm_allowed()) {
        return Action::Result::COMMAND_DENIED;
    }

    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_COMPONENT_ARM_DISARM,
                   DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::disarm() const
{
    if (!is_disarm_allowed()) {
        return Action::Result::COMMAND_DENIED;
    }

    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_COMPONENT_ARM_DISARM,
                   DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::kill() const
{
    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_COMPONENT_ARM_DISARM,
                   DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::takeoff() const
{
    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_NAV_TAKEOFF,
                   DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::land() const
{
    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_NAV_LAND,
                   DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN}));
}

Action::Result ActionImpl::return_to_land() const
{
    // Note: the safety flag is not needed in future versions of the PX4 Firmware
    //       but want to be rather safe than sorry.
    uint8_t flag_safety_armed = _parent->is_armed() ? MAV_MODE_FLAG_SAFETY_ARMED : 0;

    uint8_t mode = VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED |
                   flag_safety_armed;
    uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;
    uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;

    return action_result_from_command_result(
               _parent->send_command_with_ack(
                   MAV_CMD_DO_SET_MODE,
                   DeviceImpl::CommandParams {float(mode),
                                              float(custom_mode),
                                              float(custom_sub_mode),
                                              NAN, NAN, NAN, NAN}));
}

void ActionImpl::arm_async(const Action::result_callback_t &callback)
{
    if (!is_arm_allowed()) {
        callback(Action::Result::COMMAND_DENIED);
        return;
    }

    _parent->send_command_with_ack_async(
        MAV_CMD_COMPONENT_ARM_DISARM,
        DeviceImpl::CommandParams {1.0f, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::disarm_async(const Action::result_callback_t &callback)
{
    if (!is_disarm_allowed()) {
        callback(Action::Result::COMMAND_DENIED);
        return;
    }

    _parent->send_command_with_ack_async(
        MAV_CMD_COMPONENT_ARM_DISARM,
        DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::kill_async(const Action::result_callback_t &callback)
{
    _parent->send_command_with_ack_async(
        MAV_CMD_COMPONENT_ARM_DISARM,
        DeviceImpl::CommandParams {0.0f, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::takeoff_async(const Action::result_callback_t &callback)
{
    _parent->send_command_with_ack_async(
        MAV_CMD_NAV_TAKEOFF,
        DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::land_async(const Action::result_callback_t &callback)
{
    _parent->send_command_with_ack_async(
        MAV_CMD_NAV_LAND,
        DeviceImpl::CommandParams {NAN, NAN, NAN, NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

void ActionImpl::return_to_land_async(const Action::result_callback_t &callback)
{
    // Note: the safety flag is not needed in future versions of the PX4 Firmware
    //       but want to be rather safe than sorry.
    uint8_t flag_safety_armed = _parent->is_armed() ? MAV_MODE_FLAG_SAFETY_ARMED : 0;

    uint8_t mode = VEHICLE_MODE_FLAG_CUSTOM_MODE_ENABLED |
                   flag_safety_armed;
    uint8_t custom_mode = PX4_CUSTOM_MAIN_MODE_AUTO;
    uint8_t custom_sub_mode = PX4_CUSTOM_SUB_MODE_AUTO_RTL;

    _parent->send_command_with_ack_async(
        MAV_CMD_DO_SET_MODE,
        DeviceImpl::CommandParams {float(mode),
                                   float(custom_mode),
                                   float(custom_sub_mode),
                                   NAN, NAN, NAN, NAN},
        std::bind(&ActionImpl::command_result_callback,
                  std::placeholders::_1,
                  callback));
}

bool ActionImpl::is_arm_allowed() const
{
    if (!_in_air_state_known) {
        return false;
    }

    if (_in_air) {
        return false;
    }

    return true;
}

bool ActionImpl::is_disarm_allowed() const
{
    if (!_in_air_state_known) {
        Debug() << "in air state unknown";
        return false;
    }

    if (_in_air) {
        Debug() << "still in air";
        return false;
    }

    return true;
}

void ActionImpl::process_extended_sys_state(const mavlink_message_t &message)
{
    mavlink_extended_sys_state_t extended_sys_state;
    mavlink_msg_extended_sys_state_decode(&message, &extended_sys_state);
    if (extended_sys_state.landed_state == MAV_LANDED_STATE_IN_AIR) {
        _in_air = true;
    } else if (extended_sys_state.landed_state == MAV_LANDED_STATE_ON_GROUND) {
        _in_air = false;
    }
    _in_air_state_known = true;
}

Action::Result
ActionImpl::action_result_from_command_result(DeviceImpl::CommandResult result)
{
    switch (result) {
        case DeviceImpl::CommandResult::SUCCESS:
            return Action::Result::SUCCESS;
        case DeviceImpl::CommandResult::NO_DEVICE:
            return Action::Result::NO_DEVICE;
        case DeviceImpl::CommandResult::CONNECTION_ERROR:
            return Action::Result::CONNECTION_ERROR;
        case DeviceImpl::CommandResult::BUSY:
            return Action::Result::BUSY;
        case DeviceImpl::CommandResult::COMMAND_DENIED:
            return Action::Result::COMMAND_DENIED;
        case DeviceImpl::CommandResult::TIMEOUT:
            return Action::Result::TIMEOUT;
        default:
            return Action::Result::UNKNOWN;
    }
}

void ActionImpl::command_result_callback(DeviceImpl::CommandResult command_result,
                                         const Action::result_callback_t &callback)
{
    Action::Result action_result = action_result_from_command_result(command_result);

    callback(action_result);
}

} // namespace dronelink
<|endoftext|>


<commit_before>#include <exception>
#include <iostream>
#include <sstream>
#include <TFormula.h>
#include <pqxx/pqxx>
#include "../DBHandler/HeaderFiles/DBHandler.h"
#include "JPetCalibration.h"
namespace JPetCalibration {
	using namespace std;
	class Exception:public exception{
	public:
		Exception(const string&&msg);
		virtual ~Exception() throw();
		virtual const char* what() const throw();
	private:
		string m_msg;
	};

	using namespace std;
	using namespace pqxx;
	using namespace DB::SERVICES;
	Exception::Exception(const string&& msg):m_msg(msg){}
	Exception::~Exception()throw(){}
	const char* Exception::what() const throw(){
		return m_msg.c_str();
	}

	CalibrationType::CalibrationType(const CalibrationType& source)
	:m_name(source.m_name),m_id(source.m_id),m_count(source.m_count),m_formula(source.m_formula){}

	CalibrationType::CalibrationType(const result::const_iterator&row)
	:m_name(row["name"].as<string>()),m_id(row["type_id"].as<size_t>())
	,m_count(row["param_count"].as<size_t>()),m_formula(row["formula"].as<string>()){}

	CalibrationType::CalibrationType(const string& n,const size_t count, const string& f)
	:m_name(n),m_id(0),m_count(count),m_formula(f){}

	CalibrationType::CalibrationType(const string&&n,const size_t count,const string&&f)
	:m_name(n),m_id(0),m_count(count),m_formula(f){}

	CalibrationType::~CalibrationType(){}
	const size_t CalibrationType::id()const{return m_id;}
	const string& CalibrationType::name()const{return m_name;}
	const size_t CalibrationType::param_count()const{return m_count;}
	const string& CalibrationType::formula()const{return m_formula;}

	CalibrationTypeEdit::CalibrationTypeEdit(){}
	CalibrationTypeEdit::~CalibrationTypeEdit(){}
	const vector<CalibrationType> CalibrationTypeEdit::GetTypes()const{
		result data=DBHandler::getInstance().querry("SELECT * FROM getcalibrationtypes();");
		vector<CalibrationType> res;
		for(const auto&row:data)res.push_back(CalibrationType(row));
		return res;
	}
	void CalibrationTypeEdit::AddType(const CalibrationType& type){
		if(type.id()>0)throw Exception("CalibrationInterface: attempt to insert CalibrationType that already exists");
		string req="SELECT * FROM insert_calibrationtype(";
		req+="'"+type.name()+"',"+to_string(type.param_count())+",'"+type.formula()+"');";
		DBHandler::getInstance().querry(req);
	}
	void CalibrationTypeEdit::AddType(const CalibrationType&& type){AddType(type);}

	Calibration::Calibration(const string&n,const size_t count,const string& f,const string&params)
	:m_name(n),m_formula(f),m_encoded_params(params){
		stringstream ss(params);
		vector<string> tokens;
		copy(istream_iterator<string>(ss),
		     istream_iterator<string>(),
		     back_inserter(tokens));
		for(const string&token:tokens)
			if(m_params.size()<count)
				m_params.push_back(stod(token));
		if(m_params.size()<count)
			throw Exception("PhmAmplCalibration: the number of decoded parameters is bad");
		init_formula();
	}
	Calibration::Calibration(const string&&n,const size_t count,const string&&f,const string&&params):Calibration(n,count,f,params){}
	Calibration::Calibration(const result::const_iterator&row,const vector<string>&field_names)
	:Calibration(row[field_names[0]].as<string>(),row[field_names[1]].as<size_t>(),row[field_names[2]].as<string>(),row[field_names[3]].as<string>()){}
	Calibration::Calibration(const CalibrationType&type,const parameter_set&values):m_name(type.name()),m_formula(type.formula()){
		if(0==type.id())throw Exception("Calibration: attempt to create calibration of type that is not present in database");
		if(values.size()!=type.param_count())
			throw Exception("Calibration: parameters count is not good for selected calibration type");
		m_encoded_params="";
		for(double p:values){
			m_params.push_back(p);
			m_encoded_params+=to_string(p)+" ";
		}
		init_formula();
	}
	Calibration::Calibration(const Calibration& source)
	:m_name(source.m_name),m_formula(source.m_formula),m_encoded_params(source.m_encoded_params){
		for(double p:source.m_params)m_params.push_back(p);
		init_formula();
	}
	Calibration::~Calibration(){deinit_formula();}
	const string& Calibration::name() const{return m_name;}
	const string& Calibration::formula() const{return m_formula;}
	const vector<double>&Calibration::params() const{return m_params;}
	const string& Calibration::encoded_params() const{return m_encoded_params;}
	void Calibration::init_formula(){
		buf=new double[m_params.size()];
		for(size_t i=0;i<m_params.size();i++)buf[i]=m_params[i];
		m_tformula= new TFormula(formula().c_str(),formula().c_str());
	}
	void Calibration::deinit_formula(){
		delete[] buf;
		delete m_tformula;
	}
	double Calibration::operator()(const parameter_set& X) const{
		double x[X.size()];
		for(size_t i=0,n=X.size();i<n;i++)x[i]=X[i];
		return m_tformula->EvalPar(x,buf);
	}
	double Calibration::operator()(const parameter_set&& X) const{return operator()(X);}

	CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&field_names)
	:Calibration(row, field_names), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&&field_names)
	:CalibrationForEquipment(eq_id,row,field_names), m_type_id(0), m_cal_id(0){}
	CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const CalibrationType&type,const parameter_set&values)
	:Calibration(type, values), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipment::CalibrationForEquipment(const id_set& eq_id,const CalibrationType&type,const parameter_set&&values)
	:CalibrationForEquipment(eq_id,type,values){}
	CalibrationForEquipment::CalibrationForEquipment(const CalibrationForEquipment&source)
	:Calibration(source), m_type_id(0), m_cal_id(0){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipment::~CalibrationForEquipment(){}

	const size_t CalibrationForEquipment::calibration_id()const{return m_cal_id;}
	const id_set& CalibrationForEquipment::equipment_ids()const{return m_eq_id;}
	const size_t CalibrationForEquipment::type_id()const{return m_type_id;}

	CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&field_names)
	:Calibration(row, field_names),m_run_id(run_id){for(const auto&item:eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&&field_names)
	:CalibrationForEquipmentAndRun(eq_id,run_id,row,field_names){}
	CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const CalibrationForEquipmentAndRun& source)
	:Calibration(source),m_run_id(source.m_run_id){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipmentAndRun::~CalibrationForEquipmentAndRun(){}
	const id_set&CalibrationForEquipmentAndRun::equipment_ids()const{return m_eq_id;}
	const size_t CalibrationForEquipmentAndRun::run_id()const{return m_run_id;}

	AmplificationCalibrationEdit::AmplificationCalibrationEdit()
	:m_fields{"name","param_count","formula","param_values"}{}
	AmplificationCalibrationEdit::~AmplificationCalibrationEdit(){}
	const vector<CalibrationForEquipment> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id)const{
		vector<CalibrationForEquipment> res;
		for(const auto&row:DBHandler::getInstance().querry("select * from getcalibrations_phmampl_allphm("+to_string(eq_id[0])+");"))
			res.push_back(CalibrationForEquipment(eq_id,row,m_fields));
		return res;
	}
	const vector<CalibrationForEquipmentAndRun> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id,const size_t setup_id)const{
		vector<CalibrationForEquipmentAndRun> res;
		for(const auto&row:DBHandler::getInstance()
			.querry("select * from getcalibrations_phmampl_setupandphm("+to_string(setup_id)+","+to_string(eq_id[0])+");"))
			res.push_back(CalibrationForEquipmentAndRun(eq_id,setup_id,row,m_fields));
		return res;
	}
	bool AmplificationCalibrationEdit::AddCalibration(const CalibrationForEquipment&&new_calibration){
		if(
			(new_calibration.calibration_id()==0)&&
			(new_calibration.type_id()!=0)&&
			(new_calibration.equipment_ids()[0]!=0)
		){
			DBHandler::getInstance().querry("select * from insert_calibration_phmampl("
				+to_string(new_calibration.equipment_ids()[0])+","
				+to_string(new_calibration.type_id())+","
				+new_calibration.encoded_params()+");"
			);
			return true;
		}else return false;
	}
	bool AmplificationCalibrationEdit::ConnectCalibrationToRun(const CalibrationForEquipment&cal,const size_t run_id){
		if(
			(cal.calibration_id()!=0)&&(cal.type_id()==0)&&
			(cal.equipment_ids()[0]!=0)
		){
			DBHandler::getInstance().querry(
				"select * from connect_calibration_phmampl("
				+to_string(cal.calibration_id())+","+to_string(run_id)+");"
			);
			return true;
		}else return false;
	}

	AmplificationCalibration::AmplificationCalibration()
		:m_fields{"name","param_count","formula","param_values"}{}
	AmplificationCalibration::~AmplificationCalibration(){}
	const vector<CalibrationForEquipmentAndRun> AmplificationCalibration::ForRun(const size_t run_id) const{
		vector<CalibrationForEquipmentAndRun> res;
		for(const auto&row:
			DBHandler::getInstance().querry(
				"select * from getcalibrations_phmampl_run("+to_string(run_id)+");"
			)
		)
			res.push_back(CalibrationForEquipmentAndRun(
				{row["id_phm"].as<size_t>()},run_id,row,m_fields
			));
		return res;
	}

}
<commit_msg>Change position of variable initialization in constructors<commit_after>#include <exception>
#include <iostream>
#include <sstream>
#include <TFormula.h>
#include <pqxx/pqxx>
#include "../DBHandler/HeaderFiles/DBHandler.h"
#include "JPetCalibration.h"
namespace JPetCalibration {
	using namespace std;
	class Exception:public exception{
	public:
		Exception(const string&&msg);
		virtual ~Exception() throw();
		virtual const char* what() const throw();
	private:
		string m_msg;
	};

	using namespace std;
	using namespace pqxx;
	using namespace DB::SERVICES;
	Exception::Exception(const string&& msg):m_msg(msg){}
	Exception::~Exception()throw(){}
	const char* Exception::what() const throw(){
		return m_msg.c_str();
	}

	CalibrationType::CalibrationType(const CalibrationType& source)
	:m_id(source.m_id), m_count(source.m_count), m_name(source.m_name),m_formula(source.m_formula){}

	CalibrationType::CalibrationType(const result::const_iterator&row)
	:m_id(row["type_id"].as<size_t>()), m_count(row["param_count"].as<size_t>()),
  m_name(row["name"].as<string>()), m_formula(row["formula"].as<string>()){}

	CalibrationType::CalibrationType(const string& n,const size_t count, const string& f)
	:m_id(0), m_count(count), m_name(n), m_formula(f){}

	CalibrationType::CalibrationType(const string&&n,const size_t count,const string&&f)
	:m_id(0), m_count(count), m_name(n), m_formula(f){}

	CalibrationType::~CalibrationType(){}
	const size_t CalibrationType::id()const{return m_id;}
	const string& CalibrationType::name()const{return m_name;}
	const size_t CalibrationType::param_count()const{return m_count;}
	const string& CalibrationType::formula()const{return m_formula;}

	CalibrationTypeEdit::CalibrationTypeEdit(){}
	CalibrationTypeEdit::~CalibrationTypeEdit(){}
	const vector<CalibrationType> CalibrationTypeEdit::GetTypes()const{
		result data=DBHandler::getInstance().querry("SELECT * FROM getcalibrationtypes();");
		vector<CalibrationType> res;
		for(const auto&row:data)res.push_back(CalibrationType(row));
		return res;
	}
	void CalibrationTypeEdit::AddType(const CalibrationType& type){
		if(type.id()>0)throw Exception("CalibrationInterface: attempt to insert CalibrationType that already exists");
		string req="SELECT * FROM insert_calibrationtype(";
		req+="'"+type.name()+"',"+to_string(type.param_count())+",'"+type.formula()+"');";
		DBHandler::getInstance().querry(req);
	}
	void CalibrationTypeEdit::AddType(const CalibrationType&& type){AddType(type);}

	Calibration::Calibration(const string&n,const size_t count,const string& f,const string&params)
	:m_name(n),m_formula(f),m_encoded_params(params){
		stringstream ss(params);
		vector<string> tokens;
		copy(istream_iterator<string>(ss),
		     istream_iterator<string>(),
		     back_inserter(tokens));
		for(const string&token:tokens)
			if(m_params.size()<count)
				m_params.push_back(stod(token));
		if(m_params.size()<count)
			throw Exception("PhmAmplCalibration: the number of decoded parameters is bad");
		init_formula();
	}
	Calibration::Calibration(const string&&n,const size_t count,const string&&f,const string&&params):Calibration(n,count,f,params){}
	Calibration::Calibration(const result::const_iterator&row,const vector<string>&field_names)
	:Calibration(row[field_names[0]].as<string>(),row[field_names[1]].as<size_t>(),row[field_names[2]].as<string>(),row[field_names[3]].as<string>()){}
	Calibration::Calibration(const CalibrationType&type,const parameter_set&values):m_name(type.name()),m_formula(type.formula()){
		if(0==type.id())throw Exception("Calibration: attempt to create calibration of type that is not present in database");
		if(values.size()!=type.param_count())
			throw Exception("Calibration: parameters count is not good for selected calibration type");
		m_encoded_params="";
		for(double p:values){
			m_params.push_back(p);
			m_encoded_params+=to_string(p)+" ";
		}
		init_formula();
	}
	Calibration::Calibration(const Calibration& source)
	:m_name(source.m_name),m_formula(source.m_formula),m_encoded_params(source.m_encoded_params){
		for(double p:source.m_params)m_params.push_back(p);
		init_formula();
	}
	Calibration::~Calibration(){deinit_formula();}
	const string& Calibration::name() const{return m_name;}
	const string& Calibration::formula() const{return m_formula;}
	const vector<double>&Calibration::params() const{return m_params;}
	const string& Calibration::encoded_params() const{return m_encoded_params;}
	void Calibration::init_formula(){
		buf=new double[m_params.size()];
		for(size_t i=0;i<m_params.size();i++)buf[i]=m_params[i];
		m_tformula= new TFormula(formula().c_str(),formula().c_str());
	}
	void Calibration::deinit_formula(){
		delete[] buf;
		delete m_tformula;
	}
	double Calibration::operator()(const parameter_set& X) const{
		double x[X.size()];
		for(size_t i=0,n=X.size();i<n;i++)x[i]=X[i];
		return m_tformula->EvalPar(x,buf);
	}
	double Calibration::operator()(const parameter_set&& X) const{return operator()(X);}

	CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&field_names)
	:Calibration(row, field_names), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&&field_names)
	:CalibrationForEquipment(eq_id,row,field_names){}
	CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const CalibrationType&type,const parameter_set&values)
	:Calibration(type, values), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipment::CalibrationForEquipment(const id_set& eq_id,const CalibrationType&type,const parameter_set&&values)
	:CalibrationForEquipment(eq_id,type,values){}
	CalibrationForEquipment::CalibrationForEquipment(const CalibrationForEquipment&source)
	:Calibration(source),m_type_id(0), m_cal_id(0){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipment::~CalibrationForEquipment(){}

	const size_t CalibrationForEquipment::calibration_id()const{return m_cal_id;}
	const id_set& CalibrationForEquipment::equipment_ids()const{return m_eq_id;}
	const size_t CalibrationForEquipment::type_id()const{return m_type_id;}

	CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&field_names)
	:Calibration(row, field_names),m_run_id(run_id){for(const auto&item:eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&&field_names)
	:CalibrationForEquipmentAndRun(eq_id,run_id,row,field_names){}
	CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const CalibrationForEquipmentAndRun& source)
	:Calibration(source),m_run_id(source.m_run_id){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);}
	CalibrationForEquipmentAndRun::~CalibrationForEquipmentAndRun(){}
	const id_set&CalibrationForEquipmentAndRun::equipment_ids()const{return m_eq_id;}
	const size_t CalibrationForEquipmentAndRun::run_id()const{return m_run_id;}

	AmplificationCalibrationEdit::AmplificationCalibrationEdit()
	:m_fields{"name","param_count","formula","param_values"}{}
	AmplificationCalibrationEdit::~AmplificationCalibrationEdit(){}
	const vector<CalibrationForEquipment> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id)const{
		vector<CalibrationForEquipment> res;
		for(const auto&row:DBHandler::getInstance().querry("select * from getcalibrations_phmampl_allphm("+to_string(eq_id[0])+");"))
			res.push_back(CalibrationForEquipment(eq_id,row,m_fields));
		return res;
	}
	const vector<CalibrationForEquipmentAndRun> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id,const size_t setup_id)const{
		vector<CalibrationForEquipmentAndRun> res;
		for(const auto&row:DBHandler::getInstance()
			.querry("select * from getcalibrations_phmampl_setupandphm("+to_string(setup_id)+","+to_string(eq_id[0])+");"))
			res.push_back(CalibrationForEquipmentAndRun(eq_id,setup_id,row,m_fields));
		return res;
	}
	bool AmplificationCalibrationEdit::AddCalibration(const CalibrationForEquipment&&new_calibration){
		if(
			(new_calibration.calibration_id()==0)&&
			(new_calibration.type_id()!=0)&&
			(new_calibration.equipment_ids()[0]!=0)
		){
			DBHandler::getInstance().querry("select * from insert_calibration_phmampl("
				+to_string(new_calibration.equipment_ids()[0])+","
				+to_string(new_calibration.type_id())+","
				+new_calibration.encoded_params()+");"
			);
			return true;
		}else return false;
	}
	bool AmplificationCalibrationEdit::ConnectCalibrationToRun(const CalibrationForEquipment&cal,const size_t run_id){
		if(
			(cal.calibration_id()!=0)&&(cal.type_id()==0)&&
			(cal.equipment_ids()[0]!=0)
		){
			DBHandler::getInstance().querry(
				"select * from connect_calibration_phmampl("
				+to_string(cal.calibration_id())+","+to_string(run_id)+");"
			);
			return true;
		}else return false;
	}

	AmplificationCalibration::AmplificationCalibration()
		:m_fields{"name","param_count","formula","param_values"}{}
	AmplificationCalibration::~AmplificationCalibration(){}
	const vector<CalibrationForEquipmentAndRun> AmplificationCalibration::ForRun(const size_t run_id) const{
		vector<CalibrationForEquipmentAndRun> res;
		for(const auto&row:
			DBHandler::getInstance().querry(
				"select * from getcalibrations_phmampl_run("+to_string(run_id)+");"
			)
		)
			res.push_back(CalibrationForEquipmentAndRun(
				{row["id_phm"].as<size_t>()},run_id,row,m_fields
			));
		return res;
	}

}
<|endoftext|>


<commit_before>#include <iostream>
#include <array>
#include <string>
#include <vector>
#include <random>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

#define ELEMENT_COUNT (50)

static SDL_Window* window;
static SDL_Renderer* renderer;
static int windowWidth, windowHeight;
static TTF_Font* font;

template <typename T> constexpr static inline
T Map(T x, T minIn, T maxIn, T minOut, T maxOut)
{
    return (x - minIn) * (maxOut - minOut) / (maxIn - minIn) + minOut;
}

static inline
int Round(float value)
{
    int result = static_cast<int>(roundf(value));

    return result;
}

struct Element
{
    float val;
    int r, g, b;

    friend inline bool
    operator <(const Element& lhs, const Element& rhs)
    {
        return lhs.val < rhs.val;
    }

    friend inline bool
    operator >(const Element& lhs, const Element& rhs)
    {
        return lhs.val > rhs.val;
    }
};

using Elements = std::array<Element, ELEMENT_COUNT>;

static
void Render(Elements& elements, const char* name)
{
    auto* nameSurface = TTF_RenderText_Solid(font, name, { 255, 255, 255, 255 });
    auto  nameTexture = SDL_CreateTextureFromSurface(renderer, nameSurface);

    SDL_FreeSurface(nameSurface);

    SDL_Rect r;
    r.x = r.y = 10;

    SDL_QueryTexture(nameTexture, 0, 0, &r.w, &r.h);

    const auto ELEMENT_WIDTH = (windowWidth / ELEMENT_COUNT);

    SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
    SDL_RenderClear(renderer);
    for (size_t i = 0; i < elements.size(); ++i)
    {
        SDL_Rect rect;
        rect.x = i * ELEMENT_WIDTH;
        rect.y = windowHeight;
        rect.w = ELEMENT_WIDTH;
        rect.h = Round(-Map(elements[i].val, 0.0f, static_cast<float>(elements.size()), 100.0f,
                            static_cast<float>(windowHeight)));

        SDL_SetRenderDrawColor(renderer, elements[i].r, elements[i].g, elements[i].b, 0xff);
        SDL_RenderFillRect(renderer, &rect);
    }

    SDL_RenderCopy(renderer, nameTexture, NULL, &r);
    SDL_RenderPresent(renderer);
}

static
void Update()
{
    SDL_Event e;
    while (SDL_PollEvent(&e))
    {
        if (e.type == SDL_QUIT)
        {
            exit(0);
        }
    }
}

class Sort
{
public:
    Sort() { _name = ""; }
    Sort(std::string name_) : _name(name_) {}

    virtual void
    Run(Elements&, size_t, size_t) = 0;

    inline void
    SetName(std::string s) { _name = s; }

    inline std::string
    GetName() { return _name; }

protected:
    std::string _name;
};

class InsertionSort : public Sort
{
public:
    InsertionSort() { _name = "Insertion Sort"; }

    void
    Run(Elements& elements, size_t, size_t)
    {
        Render(elements, _name.c_str());

        size_t sortedIndex = 0;

        for (size_t i = sortedIndex; i < elements.size(); ++i)
        {
            auto j = i;

            while ((j > 0) && (elements[j] < elements[j - 1]))
            {
                for (auto& e : elements)
                {
                    e.r = 0xff;
                    e.g = 0xff;
                    e.b = 0xff;
                }

                std::swap(elements[j], elements[j - 1]);
                --j;

                elements[j].r = 0xee;
                elements[j].g = 0x00;
                elements[j].b = 0x00;

                Render(elements, _name.c_str());
                Update();
                SDL_Delay(25);
                Update();
            }
        }
    }
};

class SelectionSort : public Sort
{
public:
    SelectionSort() { _name = "Selection Sort"; }

    void
    Run(Elements& elements, size_t, size_t)
    {
        Render(elements, _name.c_str());

        for (size_t i = 0; i < elements.size(); ++i)
        {
            for (size_t j = 0; j < elements.size(); ++j)
            {
                elements[j].r = 0xff;
                elements[j].g = 0xff;
                elements[j].b = 0xff;
            }

            auto minIndex = i;

            elements[i].r = 0xee;
            elements[i].g = 0x00;
            elements[i].b = 0x00;

            for (auto j = i; j < elements.size(); ++j)
            {
                auto oldR = elements[j].r;
                auto oldG = elements[j].g;
                auto oldB = elements[j].b;

                elements[j].r = 0x00;
                elements[j].g = 0x00;
                elements[j].b = 0xee;

                if (elements[j] < elements[minIndex])
                {
                    elements[minIndex].r = 0xff;
                    elements[minIndex].g = 0xff;
                    elements[minIndex].b = 0xff;

                    minIndex = j;

                    oldR = 0xee;
                    oldG = 0;
                    oldB = 0;

                    elements[minIndex].r = 0xee;
                    elements[minIndex].g = 0x00;
                    elements[minIndex].b = 0x00;
                }

                Render(elements, _name.c_str());

                elements[j].r = oldR;
                elements[j].g = oldG;
                elements[j].b = oldB;

                Update();
                SDL_Delay(35);
                Update();
            }

            std::swap(elements[i], elements[minIndex]);
        }
    };
};

class BubbleSort : public Sort
{
public:
    BubbleSort() { _name = "Bubble Sort"; }

    void
    Run(Elements& elements, size_t left, size_t right)
    {
        Render(elements, _name.c_str());

        for (size_t i = left; i < right - 1; ++i)
        {
            for (size_t j = left; j < elements.size() - i - 1; ++j)
            {
                if (elements[j].val > elements[j + 1].val)
                {
                    std::swap(elements[j].val, elements[j + 1].val);

                    for (Element& e : elements)
                    {
                        e.r = 0xff;
                        e.g = 0xff;
                        e.b = 0xff;
                    }

                    elements[j].r = 0x00;
                    elements[j].g = 0xee;
                    elements[j].b = 0x00;

                    Render(elements, _name.c_str());
                    Update();
                }
            }
       }
    };
};

class QuickSort : public Sort
{
public:
    QuickSort() { _name = "Quick Sort"; }

    void
    Run(Elements& elements, size_t left, size_t right)
    {
        auto i = left;
        auto j = right;
        auto pivot = elements[(left + right) / 2].val;

        Render(elements, _name.c_str());
        SDL_Delay(20);

        while (i <= j)
        {
            while (elements[i].val < pivot)
            {
                i++;
            }

            while (elements[j].val > pivot)
            {
                j--;
            }

            if (i <= j)
            {
                std::swap(elements[i], elements[j]);

                i++;
                j--;
            }

            for (Element& e : elements)
            {
                e.r = 0xff;
                e.g = 0xff;
                e.b = 0xff;
            }

            if (left > 0 && left < elements.size())
            {
                elements[left].r = 0x00;
                elements[left].g = 0xee;
                elements[left].b = 0x00;
            }

            if (right > 0 && right < elements.size())
            {
                elements[right].r = 0x00;
                elements[right].g = 0xee;
                elements[right].b = 0x00;
            }

            if (pivot > 0 && pivot < elements.size())
            {
                elements[pivot].r = 0xee;
                elements[pivot].g = 0x00;
                elements[pivot].g = 0x00;
            }

            Render(elements, _name.c_str());
            SDL_Delay(60);
            Update();
        }

        if (left < j)
        {
            Run(elements, left, j);
        }

        if (i < right)
        {
            Run(elements, i, right);
        }
    };
};

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    TTF_Init();

    font = TTF_OpenFont("./OpenSans-Regular.ttf", 32);

    if (!font)
    {
        std::cerr << "Could not load font!" << std::endl;
    }

    window = SDL_CreateWindow("Visual Sort", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1920, 1080,
                              SDL_WINDOW_FULLSCREEN_DESKTOP);
    SDL_GetWindowSize(window, &windowWidth, &windowHeight);

    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    Elements elements = {};

    std::array<Sort*, 4> sortingFunctions;
    sortingFunctions[0] = new QuickSort();
    sortingFunctions[1] = new BubbleSort();
    sortingFunctions[2] = new SelectionSort();
    sortingFunctions[3] = new InsertionSort();

    for (auto& func : sortingFunctions)
    {
        std::srand(static_cast<unsigned>(time(0)));

        for (size_t i = 0; i < elements.size(); ++i)
        {
            elements[i].r = 0xff;
            elements[i].g = 0xff;
            elements[i].b = 0xff;

            auto val = static_cast<float>(std::rand() % ELEMENT_COUNT);

            for (size_t j = 0; j < i; ++j)
            {
                if (val == elements[j].val)
                {
                    val = static_cast<float>(std::rand() % ELEMENT_COUNT);
                    j = 0;
                }
            }

            elements[i].val = val;
        }

        func->Run(elements, 0, elements.size());

        Update();
        SDL_Delay(1000);
        Update();
    }
}
<commit_msg>Bumped element count up to 75<commit_after>#include <iostream>
#include <array>
#include <string>
#include <vector>
#include <random>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

#define ELEMENT_COUNT (75)

static SDL_Window* window;
static SDL_Renderer* renderer;
static int windowWidth, windowHeight;
static TTF_Font* font;

template <typename T> constexpr static inline
T Map(T x, T minIn, T maxIn, T minOut, T maxOut)
{
    return (x - minIn) * (maxOut - minOut) / (maxIn - minIn) + minOut;
}

static inline
int Round(float value)
{
    int result = static_cast<int>(roundf(value));

    return result;
}

struct Element
{
    float val;
    int r, g, b;

    friend inline bool
    operator <(const Element& lhs, const Element& rhs)
    {
        return lhs.val < rhs.val;
    }

    friend inline bool
    operator >(const Element& lhs, const Element& rhs)
    {
        return lhs.val > rhs.val;
    }
};

using Elements = std::array<Element, ELEMENT_COUNT>;

static
void Render(Elements& elements, const char* name)
{
    auto* nameSurface = TTF_RenderText_Solid(font, name, { 255, 255, 255, 255 });
    auto  nameTexture = SDL_CreateTextureFromSurface(renderer, nameSurface);

    SDL_FreeSurface(nameSurface);

    SDL_Rect r;
    r.x = r.y = 10;

    SDL_QueryTexture(nameTexture, 0, 0, &r.w, &r.h);

    const auto ELEMENT_WIDTH = (windowWidth / ELEMENT_COUNT);

    SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
    SDL_RenderClear(renderer);
    for (size_t i = 0; i < elements.size(); ++i)
    {
        SDL_Rect rect;
        rect.x = i * ELEMENT_WIDTH;
        rect.y = windowHeight;
        rect.w = ELEMENT_WIDTH;
        rect.h = Round(-Map(elements[i].val, 0.0f, static_cast<float>(elements.size()), 100.0f,
                            static_cast<float>(windowHeight)));

        SDL_SetRenderDrawColor(renderer, elements[i].r, elements[i].g, elements[i].b, 0xff);
        SDL_RenderFillRect(renderer, &rect);
    }

    SDL_RenderCopy(renderer, nameTexture, NULL, &r);
    SDL_RenderPresent(renderer);
}

static
void Update()
{
    SDL_Event e;
    while (SDL_PollEvent(&e))
    {
        if (e.type == SDL_QUIT)
        {
            exit(0);
        }
    }
}

class Sort
{
public:
    Sort() { _name = ""; }
    Sort(std::string name_) : _name(name_) {}

    virtual void
    Run(Elements&, size_t, size_t) = 0;

    inline void
    SetName(std::string s) { _name = s; }

    inline std::string
    GetName() { return _name; }

protected:
    std::string _name;
};

class InsertionSort : public Sort
{
public:
    InsertionSort() { _name = "Insertion Sort"; }

    void
    Run(Elements& elements, size_t, size_t)
    {
        Render(elements, _name.c_str());

        size_t sortedIndex = 0;

        for (size_t i = sortedIndex; i < elements.size(); ++i)
        {
            auto j = i;

            while ((j > 0) && (elements[j] < elements[j - 1]))
            {
                for (auto& e : elements)
                {
                    e.r = 0xff;
                    e.g = 0xff;
                    e.b = 0xff;
                }

                std::swap(elements[j], elements[j - 1]);
                --j;

                elements[j].r = 0xee;
                elements[j].g = 0x00;
                elements[j].b = 0x00;

                Render(elements, _name.c_str());
                Update();
                SDL_Delay(25);
                Update();
            }
        }
    }
};

class SelectionSort : public Sort
{
public:
    SelectionSort() { _name = "Selection Sort"; }

    void
    Run(Elements& elements, size_t, size_t)
    {
        Render(elements, _name.c_str());

        for (size_t i = 0; i < elements.size(); ++i)
        {
            for (size_t j = 0; j < elements.size(); ++j)
            {
                elements[j].r = 0xff;
                elements[j].g = 0xff;
                elements[j].b = 0xff;
            }

            auto minIndex = i;

            elements[i].r = 0xee;
            elements[i].g = 0x00;
            elements[i].b = 0x00;

            for (auto j = i; j < elements.size(); ++j)
            {
                auto oldR = elements[j].r;
                auto oldG = elements[j].g;
                auto oldB = elements[j].b;

                elements[j].r = 0x00;
                elements[j].g = 0x00;
                elements[j].b = 0xee;

                if (elements[j] < elements[minIndex])
                {
                    elements[minIndex].r = 0xff;
                    elements[minIndex].g = 0xff;
                    elements[minIndex].b = 0xff;

                    minIndex = j;

                    oldR = 0xee;
                    oldG = 0;
                    oldB = 0;

                    elements[minIndex].r = 0xee;
                    elements[minIndex].g = 0x00;
                    elements[minIndex].b = 0x00;
                }

                Render(elements, _name.c_str());

                elements[j].r = oldR;
                elements[j].g = oldG;
                elements[j].b = oldB;

                Update();
                SDL_Delay(35);
                Update();
            }

            std::swap(elements[i], elements[minIndex]);
        }
    };
};

class BubbleSort : public Sort
{
public:
    BubbleSort() { _name = "Bubble Sort"; }

    void
    Run(Elements& elements, size_t left, size_t right)
    {
        Render(elements, _name.c_str());

        for (size_t i = left; i < right - 1; ++i)
        {
            for (size_t j = left; j < elements.size() - i - 1; ++j)
            {
                if (elements[j].val > elements[j + 1].val)
                {
                    std::swap(elements[j].val, elements[j + 1].val);

                    for (Element& e : elements)
                    {
                        e.r = 0xff;
                        e.g = 0xff;
                        e.b = 0xff;
                    }

                    elements[j].r = 0x00;
                    elements[j].g = 0xee;
                    elements[j].b = 0x00;

                    Render(elements, _name.c_str());
                    Update();
                }
            }
       }
    };
};

class QuickSort : public Sort
{
public:
    QuickSort() { _name = "Quick Sort"; }

    void
    Run(Elements& elements, size_t left, size_t right)
    {
        auto i = left;
        auto j = right;
        auto pivot = elements[(left + right) / 2].val;

        Render(elements, _name.c_str());
        SDL_Delay(20);

        while (i <= j)
        {
            while (elements[i].val < pivot)
            {
                i++;
            }

            while (elements[j].val > pivot)
            {
                j--;
            }

            if (i <= j)
            {
                std::swap(elements[i], elements[j]);

                i++;
                j--;
            }

            for (Element& e : elements)
            {
                e.r = 0xff;
                e.g = 0xff;
                e.b = 0xff;
            }

            if (left > 0 && left < elements.size())
            {
                elements[left].r = 0x00;
                elements[left].g = 0xee;
                elements[left].b = 0x00;
            }

            if (right > 0 && right < elements.size())
            {
                elements[right].r = 0x00;
                elements[right].g = 0xee;
                elements[right].b = 0x00;
            }

            if (pivot > 0 && pivot < elements.size())
            {
                elements[pivot].r = 0xee;
                elements[pivot].g = 0x00;
                elements[pivot].g = 0x00;
            }

            Render(elements, _name.c_str());
            SDL_Delay(60);
            Update();
        }

        if (left < j)
        {
            Run(elements, left, j);
        }

        if (i < right)
        {
            Run(elements, i, right);
        }
    };
};

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    TTF_Init();

    font = TTF_OpenFont("./OpenSans-Regular.ttf", 36);

    if (!font)
    {
        std::cerr << "Could not load font!" << std::endl;
    }

    window = SDL_CreateWindow("Visual Sort", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1920, 1080,
                              SDL_WINDOW_FULLSCREEN_DESKTOP);
    SDL_GetWindowSize(window, &windowWidth, &windowHeight);

    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    Elements elements = {};

    std::array<Sort*, 4> sortingFunctions;
    sortingFunctions[0] = new QuickSort();
    sortingFunctions[1] = new BubbleSort();
    sortingFunctions[2] = new SelectionSort();
    sortingFunctions[3] = new InsertionSort();

    for (auto& sortingFunc : sortingFunctions)
    {
        std::srand(static_cast<unsigned>(time(0)));

        for (size_t i = 0; i < elements.size(); ++i)
        {
            elements[i].r = 0xff;
            elements[i].g = 0xff;
            elements[i].b = 0xff;

            auto val = static_cast<float>(std::rand() % ELEMENT_COUNT);

            for (size_t j = 0; j < i; ++j)
            {
                if (val == elements[j].val)
                {
                    val = static_cast<float>(std::rand() % ELEMENT_COUNT);
                    j = 0;
                }
            }

            elements[i].val = val;
        }

        sortingFunc->Run(elements, 0, elements.size());

        Update();
        SDL_Delay(1000);
        Update();
    }
}
<|endoftext|>


<commit_before>#include "protocolsupport.h"
#include "protocolparser.h"

ProtocolSupport::ProtocolSupport() :
    maxdatasize(0),
    int64(true),
    float64(true),
    specialFloat(true),
    bitfield(true),
    longbitfield(false),
    bitfieldtest(false),
    disableunrecognized(false),
    bigendian(true),
    packetStructureSuffix("PacketStructure"),
    packetParameterSuffix("Packet")
{
}

//! Return the list of attributes understood by ProtocolSupport
QStringList ProtocolSupport::getAttriblist(void) const
{
    QStringList attribs;

    attribs << "maxSize" << "supportInt64" << "supportFloat64" << "supportSpecialFloat" << "supportBitfield" << "supportLongBitfield" << "bitfieldTest" << "file" << "prefix" << "packetStructureSuffix" << "packetParameterSuffix" << "endian";

    return attribs;
}

void ProtocolSupport::parse(const QDomNamedNodeMap& map)
{
    // Maximum bytes of data in a packet.
    maxdatasize = ProtocolParser::getAttribute("maxSize", map, "0").toInt();

    // 64-bit support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportInt64", map)))
        int64 = false;

    // double support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportFloat64", map)))
        float64 = false;

    // special float support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportSpecialFloat", map)))
        specialFloat = false;

    // bitfield support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportBitfield", map)))
        bitfield = false;

    // long bitfield support can be turned on
    if(int64 && ProtocolParser::isFieldSet(ProtocolParser::getAttribute("supportLongBitfield", map)))
        longbitfield = true;

    // bitfield test support can be turned on
    if(ProtocolParser::isFieldSet(ProtocolParser::getAttribute("bitfieldTest", map)))
        bitfieldtest = true;

    // Global file names can be specified, but cannot have a "." in it
    globalFileName = ProtocolParser::getAttribute("file", map);
    globalFileName = globalFileName.left(globalFileName.indexOf("."));

    // Prefix is not required
    prefix = ProtocolParser::getAttribute("prefix", map);

    // Packet pointer type
    pointerType = ProtocolParser::getAttribute("pointer", map);

    // Packet name post fixes
    packetStructureSuffix = ProtocolParser::getAttribute("packetStructureSuffix", map, packetStructureSuffix);
    packetParameterSuffix = ProtocolParser::getAttribute("packetParameterSuffix", map, packetParameterSuffix);

    if(ProtocolParser::getAttribute("endian", map).contains("little", Qt::CaseInsensitive))
        bigendian = false;

}// ProtocolSupport::parse
<commit_msg>Added default pointer value<commit_after>#include "protocolsupport.h"
#include "protocolparser.h"

ProtocolSupport::ProtocolSupport() :
    maxdatasize(0),
    int64(true),
    float64(true),
    specialFloat(true),
    bitfield(true),
    longbitfield(false),
    bitfieldtest(false),
    disableunrecognized(false),
    bigendian(true),
    packetStructureSuffix("PacketStructure"),
    packetParameterSuffix("Packet")
{
}

//! Return the list of attributes understood by ProtocolSupport
QStringList ProtocolSupport::getAttriblist(void) const
{
    QStringList attribs;

    attribs << "maxSize"
            << "supportInt64"
            << "supportFloat64"
            << "supportSpecialFloat"
            << "supportBitfield"
            << "supportLongBitfield"
            << "bitfieldTest"
            << "file"
            << "prefix"
            << "packetStructureSuffix"
            << "packetParameterSuffix"
            << "endian"
            << "pointer";

    return attribs;
}

void ProtocolSupport::parse(const QDomNamedNodeMap& map)
{
    // Maximum bytes of data in a packet.
    maxdatasize = ProtocolParser::getAttribute("maxSize", map, "0").toInt();

    // 64-bit support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportInt64", map)))
        int64 = false;

    // double support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportFloat64", map)))
        float64 = false;

    // special float support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportSpecialFloat", map)))
        specialFloat = false;

    // bitfield support can be turned off
    if(ProtocolParser::isFieldClear(ProtocolParser::getAttribute("supportBitfield", map)))
        bitfield = false;

    // long bitfield support can be turned on
    if(int64 && ProtocolParser::isFieldSet(ProtocolParser::getAttribute("supportLongBitfield", map)))
        longbitfield = true;

    // bitfield test support can be turned on
    if(ProtocolParser::isFieldSet(ProtocolParser::getAttribute("bitfieldTest", map)))
        bitfieldtest = true;

    // Global file names can be specified, but cannot have a "." in it
    globalFileName = ProtocolParser::getAttribute("file", map);
    globalFileName = globalFileName.left(globalFileName.indexOf("."));

    // Prefix is not required
    prefix = ProtocolParser::getAttribute("prefix", map);

    // Packet pointer type (default is 'void')
    pointerType = ProtocolParser::getAttribute("pointer", map, "void");

    if(!pointerType.endsWith("*"))
    {
        pointerType += "*";
    }

    // Packet name post fixes
    packetStructureSuffix = ProtocolParser::getAttribute("packetStructureSuffix", map, packetStructureSuffix);
    packetParameterSuffix = ProtocolParser::getAttribute("packetParameterSuffix", map, packetParameterSuffix);

    if(ProtocolParser::getAttribute("endian", map).contains("little", Qt::CaseInsensitive))
        bigendian = false;

}// ProtocolSupport::parse
<|endoftext|>


<commit_before>#include "Halide.h"

// Include the machine-generated .stub.h header file.
#include "example.stub.h"

using Halide::Buffer;

const int kSize = 32;

void verify(const Buffer<int32_t> &img, float compiletime_factor, float runtime_factor, int channels) {
    for (int i = 0; i < kSize; i++) {
        for (int j = 0; j < kSize; j++) {
            for (int c = 0; c < channels; c++) {
                if (img(i, j, c) !=
                    (int32_t)(compiletime_factor * runtime_factor * c * (i > j ? i : j))) {
                    printf("img[%d, %d, %d] = %d\n", i, j, c, img(i, j, c));
                    exit(-1);
                }
            }
        }
    }
}

int main(int argc, char **argv) {
    Halide::JITGeneratorContext context(Halide::get_target_from_environment());

    {
        // Create a Generator and set its Inputs and GeneratorParams.
        // We could just use initializer-list syntax, but we'll explicitly
        // set the fields by name for clarity.
        example::Inputs inputs;
        inputs.runtime_factor = 1.f;

        // The fields of the GeneratorParams struct are initialized to the
        // default values specified in the Generator, so we can just omit
        // any we don't want to change
        example::GeneratorParams gp;
        gp.compiletime_factor = 2.392f;
        gp.enummy = Enum_enummy::foo;
        // gp.channels = 3;  -- this is the default; no need to set

        auto gen = example(context, inputs, gp);

        // We must call schedule() before calling realize()
        gen.schedule();

        Halide::Buffer<int32_t> img = gen.realize(kSize, kSize, 3);
        verify(img, 2.392f, 1, 3);
    }

    {
        // Here, we'll use an initializer list for inputs, and omit
        // the GeneratorParams entirely to use their default values.
        auto gen = example(context, /* inputs: */ { 1.f });

        // We'll set "vectorize=false" in the ScheduleParams, just to
        // show that we can:
        example::ScheduleParams sp;
        sp.vectorize = false;
        gen.schedule(sp);

        Halide::Buffer<int32_t> img = gen.realize(kSize, kSize, 3);
        verify(img, 1, 1, 3);
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Remove floating point rounding as a source of error<commit_after>#include "Halide.h"

// Include the machine-generated .stub.h header file.
#include "example.stub.h"

using Halide::Buffer;

const int kSize = 32;

void verify(const Buffer<int32_t> &img, float compiletime_factor, float runtime_factor, int channels) {
    for (int i = 0; i < kSize; i++) {
        for (int j = 0; j < kSize; j++) {
            for (int c = 0; c < channels; c++) {
                if (img(i, j, c) !=
                    (int32_t)(compiletime_factor * runtime_factor * c * (i > j ? i : j))) {
                    printf("img[%d, %d, %d] = %d\n", i, j, c, img(i, j, c));
                    exit(-1);
                }
            }
        }
    }
}

int main(int argc, char **argv) {
    Halide::JITGeneratorContext context(Halide::get_target_from_environment());

    {
        // Create a Generator and set its Inputs and GeneratorParams.
        // We could just use initializer-list syntax, but we'll explicitly
        // set the fields by name for clarity.
        example::Inputs inputs;
        inputs.runtime_factor = 1.f;

        // The fields of the GeneratorParams struct are initialized to the
        // default values specified in the Generator, so we can just omit
        // any we don't want to change
        example::GeneratorParams gp;
        gp.compiletime_factor = 2.5f;
        gp.enummy = Enum_enummy::foo;
        // gp.channels = 3;  -- this is the default; no need to set

        auto gen = example(context, inputs, gp);

        // We must call schedule() before calling realize()
        gen.schedule();

        Halide::Buffer<int32_t> img = gen.realize(kSize, kSize, 3);
        verify(img, 2.5f, 1, 3);
    }

    {
        // Here, we'll use an initializer list for inputs, and omit
        // the GeneratorParams entirely to use their default values.
        auto gen = example(context, /* inputs: */ { 1.f });

        // We'll set "vectorize=false" in the ScheduleParams, just to
        // show that we can:
        example::ScheduleParams sp;
        sp.vectorize = false;
        gen.schedule(sp);

        Halide::Buffer<int32_t> img = gen.realize(kSize, kSize, 3);
        verify(img, 1, 1, 3);
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. 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.
// 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.

#ifndef TUSLANGUAGE_REPLYBUILDER_HPP
#define TUSLANGUAGE_REPLYBUILDER_HPP

#include <Language/Interface/ICommand.hpp>
#include <boost/noncopyable.hpp>

namespace TUSLanguage
{

// TODO: Refactor me!

class ReplyBuilder
    : boost::noncopyable
{
public:
    /**
     * @brief Builds EchoReply.
     *
     * @param a_code The exit code.
     *
     * @return EchoReply.
     */
    ICommand::SingleHandle buildEchoReply(
        unsigned short int const a_code
    ) const;

    /**
     * @brief Builds ErrorReply.
     *
     * @param a_code The exit code.
     *
     * @return ErrorReply.
     */
    ICommand::SingleHandle buildErrorReply(
        unsigned short int const a_code
    ) const;

    /**
     * @brief Builds CreateLandReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateLandReply.
     */
    ICommand::SingleHandle buildCreateLandReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DeleteLandReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DeleteLandReply.
     */
    ICommand::SingleHandle buildDeleteLandReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetLandReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetLandReply.
     */
    ICommand::SingleHandle buildGetLandReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetLandsReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetLandsReply.
     */
    ICommand::SingleHandle buildGetLandsReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds CreateSettlementReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateSettlementReply.
     */
    ICommand::SingleHandle buildCreateSettlementReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DeleteSettlementReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DeleteSettlementReply.
     */
    ICommand::SingleHandle buildDeleteSettlementReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetSettlementReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetSettlementReply.
     */
    ICommand::SingleHandle buildGetSettlementReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetSettlementsReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetSettlementsReply.
     */
    ICommand::SingleHandle buildGetSettlementsReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds BuildBuildingReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return BuildBuildingReply.
     */
    ICommand::SingleHandle buildBuildBuildingReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DestroyBuildingReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DestroyBuildingReply.
     */
    ICommand::SingleHandle buildDestroyBuildingReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetBuildingReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetBuildingReply.
     */
    ICommand::SingleHandle buildGetBuildingReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetBuildingsReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetBuildingsReply.
     */
    ICommand::SingleHandle buildGetBuildingsReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds DismissHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DismissHumanReply.
     */
    ICommand::SingleHandle buildDismissHumanReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds EngageHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return EngageHumanReply.
     */
    ICommand::SingleHandle buildEngageHumanReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetHumanReply.
     */
    ICommand::SingleHandle buildGetHumanReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetHumansReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetHumansReply.
     */
    ICommand::SingleHandle buildGetHumansReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds GetResourceReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetResourceReply.
     */
    ICommand::SingleHandle buildGetResourceReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetResourcesReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetResourcesReply.
     */
    ICommand::SingleHandle buildGetResourcesReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds CreateUserReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateUserReply.
     */
    ICommand::SingleHandle buildCreateUserReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds CreateWorldReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateWorldReply.
     */
    ICommand::SingleHandle buildCreateWorldReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds CreateEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateEpochReply.
     */
    ICommand::SingleHandle buildCreateEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DeleteEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DeleteEpochReply.
     */
    ICommand::SingleHandle buildDeleteEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds ActivateEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return ActivateEpochReply.
     */
    ICommand::SingleHandle buildActivateEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DectivateEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DectivateEpochReply.
     */
    ICommand::SingleHandle buildDeactivateEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds FinishEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return FinishEpochReply.
     */
    ICommand::SingleHandle buildFinishEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds TickEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return TickEpochReply.
     */
    ICommand::SingleHandle buildTickEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds TransportHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return TransportHumanReply.
     */
    ICommand::SingleHandle buildTransportHumanReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds TransportResourceReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return TransportResourceReply.
     */
    ICommand::SingleHandle buildTransportResourceReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetEpochReply.
     */
    ICommand::SingleHandle buildGetEpochReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;
};

} // namespace TUSLanguage

#endif // TUSLANGUAGE_REPLYBUILDER_HPP
<commit_msg>A cosmetic change.<commit_after>// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. 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.
// 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.

#ifndef TUSLANGUAGE_REPLYBUILDER_HPP
#define TUSLANGUAGE_REPLYBUILDER_HPP

#include <Language/Interface/ICommand.hpp>
#include <boost/noncopyable.hpp>

namespace TUSLanguage
{

// TODO: Refactor me!

class ReplyBuilder
    : boost::noncopyable
{
public:
    /**
     * @brief Builds EchoReply.
     *
     * @param a_code The exit code.
     *
     * @return EchoReply.
     */
    ICommand::SingleHandle buildEchoReply(
        unsigned short int const a_code
    ) const;

    /**
     * @brief Builds ErrorReply.
     *
     * @param a_code The exit code.
     *
     * @return ErrorReply.
     */
    ICommand::SingleHandle buildErrorReply(
        unsigned short int const a_code
    ) const;

    /**
     * @brief Builds CreateLandReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateLandReply.
     */
    ICommand::SingleHandle buildCreateLandReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DeleteLandReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DeleteLandReply.
     */
    ICommand::SingleHandle buildDeleteLandReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetLandReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetLandReply.
     */
    ICommand::SingleHandle buildGetLandReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetLandsReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetLandsReply.
     */
    ICommand::SingleHandle buildGetLandsReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds CreateSettlementReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateSettlementReply.
     */
    ICommand::SingleHandle buildCreateSettlementReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DeleteSettlementReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DeleteSettlementReply.
     */
    ICommand::SingleHandle buildDeleteSettlementReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetSettlementReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetSettlementReply.
     */
    ICommand::SingleHandle buildGetSettlementReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetSettlementsReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetSettlementsReply.
     */
    ICommand::SingleHandle buildGetSettlementsReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds BuildBuildingReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return BuildBuildingReply.
     */
    ICommand::SingleHandle buildBuildBuildingReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DestroyBuildingReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DestroyBuildingReply.
     */
    ICommand::SingleHandle buildDestroyBuildingReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetBuildingReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetBuildingReply.
     */
    ICommand::SingleHandle buildGetBuildingReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetBuildingsReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetBuildingsReply.
     */
    ICommand::SingleHandle buildGetBuildingsReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds DismissHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DismissHumanReply.
     */
    ICommand::SingleHandle buildDismissHumanReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds EngageHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return EngageHumanReply.
     */
    ICommand::SingleHandle buildEngageHumanReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetHumanReply.
     */
    ICommand::SingleHandle buildGetHumanReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetHumansReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetHumansReply.
     */
    ICommand::SingleHandle buildGetHumansReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds GetResourceReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetResourceReply.
     */
    ICommand::SingleHandle buildGetResourceReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds GetResourcesReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_objects The objects.
     *
     * @return GetResourcesReply.
     */
    ICommand::SingleHandle buildGetResourcesReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Objects  const & a_objects
    ) const;

    /**
     * @brief Builds CreateUserReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateUserReply.
     */
    ICommand::SingleHandle buildCreateUserReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds CreateWorldReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateWorldReply.
     */
    ICommand::SingleHandle buildCreateWorldReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds CreateEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return CreateEpochReply.
     */
    ICommand::SingleHandle buildCreateEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DeleteEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DeleteEpochReply.
     */
    ICommand::SingleHandle buildDeleteEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds ActivateEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return ActivateEpochReply.
     */
    ICommand::SingleHandle buildActivateEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds DectivateEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return DectivateEpochReply.
     */
    ICommand::SingleHandle buildDeactivateEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds FinishEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return FinishEpochReply.
     */
    ICommand::SingleHandle buildFinishEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds TickEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return TickEpochReply.
     */
    ICommand::SingleHandle buildTickEpochReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds GetEpochReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     * @param a_object  The object.
     *
     * @return GetEpochReply.
     */
    ICommand::SingleHandle buildGetEpochReply(
        unsigned short int const   a_code,
        std::string        const   a_message,
        ICommand::Object   const & a_object
    ) const;

    /**
     * @brief Builds TransportHumanReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return TransportHumanReply.
     */
    ICommand::SingleHandle buildTransportHumanReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;

    /**
     * @brief Builds TransportResourceReply.
     *
     * @param a_code    The exit code.
     * @param a_message The status message.
     *
     * @return TransportResourceReply.
     */
    ICommand::SingleHandle buildTransportResourceReply(
        unsigned short int const a_code,
        std::string        const a_message
    ) const;
};

} // namespace TUSLanguage

#endif // TUSLANGUAGE_REPLYBUILDER_HPP
<|endoftext|>