<commit_before>#ifndef ORIGEN_HPP_INCLUDED
#define ORIGEN_HPP_INCLUDED

#define ORIGEN_VERSION "0.8.0"

#ifndef debugger
#define debugger __asm__("int $3");
#endif

#include "origen/utils.hpp"
#include "origen/helpers.hpp"
#include "origen/site.hpp"

namespace Origen {

extern vector<Site> Sites;
Utils::Version version();
Site& site();
Site& site(int site);

}
#endif
<commit_msg>Wrote new version in C++ code<commit_after>#ifndef ORIGEN_HPP_INCLUDED
#define ORIGEN_HPP_INCLUDED

#define ORIGEN_VERSION "0.8.1"

#ifndef debugger
#define debugger __asm__("int $3");
#endif

#include "origen/utils.hpp"
#include "origen/helpers.hpp"
#include "origen/site.hpp"

namespace Origen {

extern vector<Site> Sites;
Utils::Version version();
Site& site();
Site& site(int site);

}
#endif
<|endoftext|>


<commit_before>#include "cvolumeenumerator.h"
#include "assert/advanced_assert.h"
#include "container/algorithms.hpp"
#include "container/set_operations.hpp"
#include "utility/on_scope_exit.hpp"
#include "volumeinfohelper.hpp"

DISABLE_COMPILER_WARNINGS
#include <QDebug>
RESTORE_COMPILER_WARNINGS

#include <algorithm>

void CVolumeEnumerator::addObserver(IVolumeListObserver *observer)
{
	assert_r(std::find(_observers.begin(), _observers.end(), observer) == _observers.end());
	_observers.push_back(observer);
}

void CVolumeEnumerator::removeObserver(IVolumeListObserver *observer)
{
	ContainerAlgorithms::erase_all_occurrences(_observers, observer);
}

// Returns the drives found
std::deque<VolumeInfo> CVolumeEnumerator::drives() const
{
	std::lock_guard<typename decltype(_mutexForDrives)> lock(_mutexForDrives);

	return _drives;
}

void CVolumeEnumerator::updateSynchronously()
{
	enumerateVolumes(false);
}

CVolumeEnumerator::CVolumeEnumerator() : _enumeratorThread(_updateInterval, "CVolumeEnumerator thread")
{
	// Setting up the timer to fetch the notifications from the queue and execute them on this thread
	connect(&_timer, &QTimer::timeout, [this](){
		_notificationsQueue.exec();
	});
	_timer.start(_updateInterval / 3);

	// Starting the worker thread that actually enumerates the volumes
	_enumeratorThread.start([this](){
		enumerateVolumes(true);
	});
}

// Refresh the list of available volumes
void CVolumeEnumerator::enumerateVolumes(bool async)
{
	const auto newDrives = enumerateVolumesImpl();

	std::lock_guard<typename decltype(_mutexForDrives)> lock(_mutexForDrives);

	if (!async || newDrives != _drives)
	{
		_drives.resize(newDrives.size());
		std::copy(newDrives.cbegin(), newDrives.cend(), _drives.begin());

		notifyObservers(async);
	}
}

// Calls all the registered observers with the latest list of drives found
void CVolumeEnumerator::notifyObservers(bool async) const
{
	// This method is called from the worker thread
	// Queuing the code to be executed on the thread where CVolumeEnumerator was created

	_notificationsQueue.enqueue([this]() {
		for (auto& observer : _observers)
			observer->volumesChanged();
	}, 0); // Setting the tag to 0 will discard any previous queue items with the same tag that have not yet been processed

	if (!async)
		_notificationsQueue.exec();
}

///////////////////////////////////////////////
//      SYSTEM-SPECIFIC IMPLEMENTATION
///////////////////////////////////////////////

#if defined _WIN32

#include "windows/windowsutils.h"

#include <Windows.h>

inline QString parseVolumePathFromPathsList(WCHAR* paths)
{
	QString qstring;
	for (auto string = paths; string[0] != L'\0'; string += wcslen(string) + 1)
	{
		qstring = QString::fromWCharArray(string);
		if (qstring.contains(':'))
			return qstring;
	}

	return qstring;
}

inline VolumeInfo volumeInfoForDriveLetter(const QString& driveLetter)
{
	VolumeInfo info;

	WCHAR volumeName[256], filesystemName[256];
	const DWORD error = GetVolumeInformationW((WCHAR*)driveLetter.utf16(), volumeName, 256, nullptr, nullptr, nullptr, filesystemName, 256) != 0 ? 0 : GetLastError();

	if (error != 0 && error != ERROR_NOT_READY)
	{
		qInfo() << "GetVolumeInformationW() returned error:" << ErrorStringFromLastError();
		return info;
	}
	else
		info.isReady = error != ERROR_NOT_READY;

	info.rootObjectInfo = driveLetter;

	if (info.isReady)
	{
		ULARGE_INTEGER totalSpace, freeSpace;
		if (GetDiskFreeSpaceExW((WCHAR*)driveLetter.utf16(), &freeSpace, &totalSpace, nullptr) != 0)
		{
			info.volumeSize = totalSpace.QuadPart;
			info.freeSize = freeSpace.QuadPart;
		}
		else
			qInfo() << "GetDiskFreeSpaceExW() returned error:" << ErrorStringFromLastError();
	}

	info.volumeLabel = QString::fromWCharArray(volumeName);
	info.fileSystemName = QString::fromWCharArray(filesystemName);
	return info;
}

const std::deque<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
	std::deque<VolumeInfo> volumes;

	const auto oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
	EXEC_ON_SCOPE_EXIT([oldErrorMode]() {SetErrorMode(oldErrorMode);});

	DWORD drives = GetLogicalDrives();
	if (drives == 0)
	{
		qInfo() << "GetLogicalDrives() returned an error:" << ErrorStringFromLastError();
		return volumes;
	}

	for (char driveLetter = 'A'; drives != 0 && driveLetter <= 'Z'; ++driveLetter, drives >>= 1)
	{
		if ((drives & 0x1) == 0)
			continue;

		const auto volumeInfo = volumeInfoForDriveLetter(QString(driveLetter) + QStringLiteral(":\\"));
		if (!volumeInfo.isEmpty())
			volumes.push_back(volumeInfo);
	}

	return volumes;
}

#elif defined __APPLE__

const std::deque<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
	VolumeInfo info;
	info.rootObjectInfo = "/";
	info.volumeLabel = "root";
	info.isReady = true;

	const auto sys_info = volumeInfoForPath(info.rootObjectInfo.fullAbsolutePath());
	info.volumeSize = sys_info.f_bsize * sys_info.f_blocks;
	info.freeSize = sys_info.f_bsize * sys_info.f_bavail;

	return std::deque<VolumeInfo>(1, info);
}

#elif defined __linux__

const std::deque<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
	VolumeInfo info;
	info.rootObjectInfo = "/";
	info.volumeLabel = "root";
	info.isReady = true;

	const auto sys_info = volumeInfoForPath(info.rootObjectInfo.fullAbsolutePath());
	info.volumeSize = sys_info.f_bsize * sys_info.f_blocks;
	info.freeSize = sys_info.f_bsize * sys_info.f_bavail;

	return std::deque<VolumeInfo>(1, info);
}

#else

#error(Unknown OS)

#endif
<commit_msg>Linux / Mac compilation error fixed<commit_after>#include "cvolumeenumerator.h"
#include "assert/advanced_assert.h"
#include "container/algorithms.hpp"
#include "container/set_operations.hpp"
#include "utility/on_scope_exit.hpp"
#include "volumeinfohelper.hpp"

DISABLE_COMPILER_WARNINGS
#include <QDebug>
RESTORE_COMPILER_WARNINGS

#include <algorithm>

void CVolumeEnumerator::addObserver(IVolumeListObserver *observer)
{
	assert_r(std::find(_observers.begin(), _observers.end(), observer) == _observers.end());
	_observers.push_back(observer);
}

void CVolumeEnumerator::removeObserver(IVolumeListObserver *observer)
{
	ContainerAlgorithms::erase_all_occurrences(_observers, observer);
}

// Returns the drives found
std::deque<VolumeInfo> CVolumeEnumerator::drives() const
{
	std::lock_guard<decltype(_mutexForDrives)> lock(_mutexForDrives);

	return _drives;
}

void CVolumeEnumerator::updateSynchronously()
{
	enumerateVolumes(false);
}

CVolumeEnumerator::CVolumeEnumerator() : _enumeratorThread(_updateInterval, "CVolumeEnumerator thread")
{
	// Setting up the timer to fetch the notifications from the queue and execute them on this thread
	connect(&_timer, &QTimer::timeout, [this](){
		_notificationsQueue.exec();
	});
	_timer.start(_updateInterval / 3);

	// Starting the worker thread that actually enumerates the volumes
	_enumeratorThread.start([this](){
		enumerateVolumes(true);
	});
}

// Refresh the list of available volumes
void CVolumeEnumerator::enumerateVolumes(bool async)
{
	const auto newDrives = enumerateVolumesImpl();

	std::lock_guard<typename decltype(_mutexForDrives)> lock(_mutexForDrives);

	if (!async || newDrives != _drives)
	{
		_drives.resize(newDrives.size());
		std::copy(newDrives.cbegin(), newDrives.cend(), _drives.begin());

		notifyObservers(async);
	}
}

// Calls all the registered observers with the latest list of drives found
void CVolumeEnumerator::notifyObservers(bool async) const
{
	// This method is called from the worker thread
	// Queuing the code to be executed on the thread where CVolumeEnumerator was created

	_notificationsQueue.enqueue([this]() {
		for (auto& observer : _observers)
			observer->volumesChanged();
	}, 0); // Setting the tag to 0 will discard any previous queue items with the same tag that have not yet been processed

	if (!async)
		_notificationsQueue.exec();
}

///////////////////////////////////////////////
//      SYSTEM-SPECIFIC IMPLEMENTATION
///////////////////////////////////////////////

#if defined _WIN32

#include "windows/windowsutils.h"

#include <Windows.h>

inline QString parseVolumePathFromPathsList(WCHAR* paths)
{
	QString qstring;
	for (auto string = paths; string[0] != L'\0'; string += wcslen(string) + 1)
	{
		qstring = QString::fromWCharArray(string);
		if (qstring.contains(':'))
			return qstring;
	}

	return qstring;
}

inline VolumeInfo volumeInfoForDriveLetter(const QString& driveLetter)
{
	VolumeInfo info;

	WCHAR volumeName[256], filesystemName[256];
	const DWORD error = GetVolumeInformationW((WCHAR*)driveLetter.utf16(), volumeName, 256, nullptr, nullptr, nullptr, filesystemName, 256) != 0 ? 0 : GetLastError();

	if (error != 0 && error != ERROR_NOT_READY)
	{
		qInfo() << "GetVolumeInformationW() returned error:" << ErrorStringFromLastError();
		return info;
	}
	else
		info.isReady = error != ERROR_NOT_READY;

	info.rootObjectInfo = driveLetter;

	if (info.isReady)
	{
		ULARGE_INTEGER totalSpace, freeSpace;
		if (GetDiskFreeSpaceExW((WCHAR*)driveLetter.utf16(), &freeSpace, &totalSpace, nullptr) != 0)
		{
			info.volumeSize = totalSpace.QuadPart;
			info.freeSize = freeSpace.QuadPart;
		}
		else
			qInfo() << "GetDiskFreeSpaceExW() returned error:" << ErrorStringFromLastError();
	}

	info.volumeLabel = QString::fromWCharArray(volumeName);
	info.fileSystemName = QString::fromWCharArray(filesystemName);
	return info;
}

const std::deque<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
	std::deque<VolumeInfo> volumes;

	const auto oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
	EXEC_ON_SCOPE_EXIT([oldErrorMode]() {SetErrorMode(oldErrorMode);});

	DWORD drives = GetLogicalDrives();
	if (drives == 0)
	{
		qInfo() << "GetLogicalDrives() returned an error:" << ErrorStringFromLastError();
		return volumes;
	}

	for (char driveLetter = 'A'; drives != 0 && driveLetter <= 'Z'; ++driveLetter, drives >>= 1)
	{
		if ((drives & 0x1) == 0)
			continue;

		const auto volumeInfo = volumeInfoForDriveLetter(QString(driveLetter) + QStringLiteral(":\\"));
		if (!volumeInfo.isEmpty())
			volumes.push_back(volumeInfo);
	}

	return volumes;
}

#elif defined __APPLE__

const std::deque<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
	VolumeInfo info;
	info.rootObjectInfo = "/";
	info.volumeLabel = "root";
	info.isReady = true;

	const auto sys_info = volumeInfoForPath(info.rootObjectInfo.fullAbsolutePath());
	info.volumeSize = sys_info.f_bsize * sys_info.f_blocks;
	info.freeSize = sys_info.f_bsize * sys_info.f_bavail;

	return std::deque<VolumeInfo>(1, info);
}

#elif defined __linux__

const std::deque<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
	VolumeInfo info;
	info.rootObjectInfo = "/";
	info.volumeLabel = "root";
	info.isReady = true;

	const auto sys_info = volumeInfoForPath(info.rootObjectInfo.fullAbsolutePath());
	info.volumeSize = sys_info.f_bsize * sys_info.f_blocks;
	info.freeSize = sys_info.f_bsize * sys_info.f_bavail;

	return std::deque<VolumeInfo>(1, info);
}

#else

#error(Unknown OS)

#endif
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <qi/os.hpp>
#include <qi/path.hpp>
#include <qi/qi.hpp>

#include <errno.h>

#ifdef _WIN32
# include <windows.h>
# include <process.h>
# include <signal.h>
#else
# include <sys/wait.h>
#endif

/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */
// TODO2: Some tests to check the consume stack

static std::string binDir;
static std::string loopBinDir;

TEST(spawnvp, CmdWithNoArgs)
{
  char* args[] = {(char*)binDir.c_str(), NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnvp, CmdWithArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnvp, CmdWithMultiArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", (char*)"-1", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnvp, InvalidBin)
{
  char* args[] = {(char*)"test42", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(spawnlp, CmdWithNoArgs)
{
  std::string bin = binDir.c_str();

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnlp, CmdWithArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnlp, CmdWithMultiArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  std::string arg2 = "-1";

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg2.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnlp, Environment)
{
  // The check_env executable exits with rectode 1 if
  // the FOO environment var is not equal to BAR.
  std::string checkEnv = qi::path::findBin("check_env");
  int status = 0;
  qi::os::setenv("FOO", "BAR");
  int childPid = qi::os::spawnlp(checkEnv.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, status) << "waitpid failed with retcode:   " << error;
  EXPECT_EQ(0, status) << "check_env failed with rectode: " << status;
}

TEST(spawnlp, InvalidBin)
{
  std::string bin = "test42";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(kill, Terminate)
{
  int status = 0;
  int alive = -1;
  int killed = -1;
  int dead = 0;

  int childPid = qi::os::spawnlp(loopBinDir.c_str(), NULL);

  if (childPid != -1)
  {
    qi::os::sleep(1);

    // is it alive?
    alive = qi::os::kill(childPid, 0);

    // let's kill it
    killed = qi::os::kill(childPid, SIGTERM);
    qi::os::waitpid(childPid, &status);

    // is it dead?
    dead = qi::os::kill(childPid, 0);
  }

  EXPECT_EQ(0, alive) << "alive: " << alive;
  EXPECT_EQ(0, killed) << "killed: " << killed;
  EXPECT_EQ(-1, dead) << "dead: " << dead;
}

TEST(system, CmdWithNoArgs)
{
  std::string bin = binDir;

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(system, CmdWithArgs)
{
  std::string bin = binDir + " 23";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(system, CmdWithMultiArgs)
{
  std::string bin = binDir + " 23 -1";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(system, InvalidBin)
{
  std::string bin = "test42";

  int status = qi::os::system(bin.c_str());

 #ifdef _WIN32
  EXPECT_EQ(1, status) << "status: " << status;
 #else
  EXPECT_EQ(127, status) << "status: " << status;
 #endif
}

int main(int argc, char* argv[])
{
  qi::init(argc, (char**)argv);
  binDir = qi::path::findBin("testlaunch");
  loopBinDir = qi::path::findBin("testlaunchloop");

  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Stop the kill test if spawn fail.<commit_after>#include <gtest/gtest.h>
#include <qi/os.hpp>
#include <qi/path.hpp>
#include <qi/qi.hpp>

#include <errno.h>

#ifdef _WIN32
# include <windows.h>
# include <process.h>
# include <signal.h>
#else
# include <sys/wait.h>
#endif

/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */
// TODO2: Some tests to check the consume stack

static std::string binDir;
static std::string loopBinDir;

TEST(spawnvp, CmdWithNoArgs)
{
  char* args[] = {(char*)binDir.c_str(), NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnvp, CmdWithArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnvp, CmdWithMultiArgs)
{
  char* args[] = {(char*)binDir.c_str(), (char*)"23", (char*)"-1", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnvp, InvalidBin)
{
  char* args[] = {(char*)"test42", NULL};

  int status = 0;

  int childPid = qi::os::spawnvp(args);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(spawnlp, CmdWithNoArgs)
{
  std::string bin = binDir.c_str();

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(spawnlp, CmdWithArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(spawnlp, CmdWithMultiArgs)
{
  std::string bin = binDir.c_str();
  std::string arg1 = "23";
  std::string arg2 = "-1";

  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), arg2.c_str(), arg1.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(spawnlp, Environment)
{
  // The check_env executable exits with rectode 1 if
  // the FOO environment var is not equal to BAR.
  std::string checkEnv = qi::path::findBin("check_env");
  int status = 0;
  qi::os::setenv("FOO", "BAR");
  int childPid = qi::os::spawnlp(checkEnv.c_str(), NULL);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, status) << "waitpid failed with retcode:   " << error;
  EXPECT_EQ(0, status) << "check_env failed with rectode: " << status;
}

TEST(spawnlp, InvalidBin)
{
  std::string bin = "test42";
  int status = 0;

  int childPid = qi::os::spawnlp(bin.c_str(), NULL);
  EXPECT_EQ(-1, childPid);
  int error = qi::os::waitpid(childPid, &status);

  EXPECT_EQ(0, error) << "error: " << error;
  EXPECT_EQ(127, status) << "status: " << status;
}

TEST(kill, Terminate)
{
  int status = 0;
  int alive = -1;
  int killed = -1;
  int dead = 0;

  int childPid = qi::os::spawnlp(loopBinDir.c_str(), NULL);
  ASSERT_NE(-1, childPid);

  if (childPid != -1)
  {
    qi::os::sleep(1);

    // is it alive?
    alive = qi::os::kill(childPid, 0);

    // let's kill it
    killed = qi::os::kill(childPid, SIGTERM);
    qi::os::waitpid(childPid, &status);

    // is it dead?
    dead = qi::os::kill(childPid, 0);
  }

  EXPECT_EQ(0, alive) << "alive: " << alive;
  EXPECT_EQ(0, killed) << "killed: " << killed;
  EXPECT_EQ(-1, dead) << "dead: " << dead;
}

TEST(system, CmdWithNoArgs)
{
  std::string bin = binDir;

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(42, status) << "status: " << status;
}

TEST(system, CmdWithArgs)
{
  std::string bin = binDir + " 23";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(23, status) << "status: " << status;
}

TEST(system, CmdWithMultiArgs)
{
  std::string bin = binDir + " 23 -1";

  int status = qi::os::system(bin.c_str());

  EXPECT_EQ(22, status) << "status: " << status;
}

TEST(system, InvalidBin)
{
  std::string bin = "test42";

  int status = qi::os::system(bin.c_str());

 #ifdef _WIN32
  EXPECT_EQ(1, status) << "status: " << status;
 #else
  EXPECT_EQ(127, status) << "status: " << status;
 #endif
}

int main(int argc, char* argv[])
{
  qi::init(argc, (char**)argv);
  binDir = qi::path::findBin("testlaunch");
  loopBinDir = qi::path::findBin("testlaunchloop");

  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "PIDControl.h"

float pid_clip(float val, float min, float max) {
  float newval = val;
  newval = (newval > max) ? max : newval;
  newval = (newval < min) ? min : newval;
  return newval;
}

PID::PID(float Kc, float tauI, float tauD, float interval, float inMin, float inMax, float outMin, float outMax, float b) {
  setInputLimits(inMin, inMax);
  setOutputLimits(outMin, outMax);

  sampleTime_ = interval;

  setTunings(Kc, tauI, tauD);

  reset();

}

void PID::reset() {
  setPoint_ = 0.0;
  processVar_ = 0.0;
  integral_ = 0.0;
  errorPrior_ = 0;
  prevControllerOutput_ = 0.0;
}

void PID::setInputLimits(float inMin, float inMax) {

    //Make sure we haven't been given impossible values.
    if (inMin >= inMax) {
        return;
    }

    //Rescale the working variables to reflect the changes

    inMin_  = inMin;
    inMax_  = inMax;
}

void PID::setOutputLimits(float outMin, float outMax) {

    //Make sure we haven't been given impossible values.
    if (outMin >= outMax) {
        return;
    }

    //Rescale the working variables to reflect the changes.
    outMin_  = outMin;
    outMax_  = outMax;
}

void PID::setTunings(float Kc, float tauI, float tauD) {
  //Verify that the tunings make sense.
  if (Kc == 0.0 || tauI < 0.0 || tauD < 0.0) {
    return;
  }

  if ((Kc != Kc_) || (tauI != tauI_) || (tauD != tauD_)) {
    reset();
  }

  Kc_ = Kc;
  tauI_ = tauI;
  tauD_ = tauD;
}

void PID::setInterval(float interval) {
  sampleTime_ = interval;
}

void PID::setSetPoint(float sp) {
  setPoint_ = pid_clip(sp, inMin_, inMax_);
}

void PID::setProcessValue(float pv) {

  processVar_ = pid_clip(pv, inMin_, inMax_);

}

void PID::setBias(float b) {
  bias_ = b;
  reset();
}

float PID::compute() {
  float error = setPoint_ - processVar_;
  if (!(prevControllerOutput_ >= outMax_ && error > 0) && !(prevControllerOutput_ <= outMin_ && error < 0)) {
    integral_ += (error*sampleTime_);
  }
  float derivative = (error - errorPrior_) / sampleTime_;
  float output = (Kc_ * error) + (tauI_ * integral_) + (tauD_ * derivative) + bias_;
  errorPrior_ = error;

  prevControllerOutput_ = pid_clip(output, outMin_, outMax_);

  return prevControllerOutput_;
}
<commit_msg>working buoyancy test for pool<commit_after>#include "PIDControl.h"

float pid_clip(float val, float min, float max) {
  float newval = val;
  newval = (newval > max) ? max : newval;
  newval = (newval < min) ? min : newval;
  return newval;
}

PID::PID(float Kc, float tauI, float tauD, float interval, float inMin, float inMax, float outMin, float outMax, float b) {
  setInputLimits(inMin, inMax);
  setOutputLimits(outMin, outMax);

  sampleTime_ = interval;

  setTunings(Kc, tauI, tauD);

  reset();

}

void PID::reset() {
  setPoint_ = 0.0;
  processVar_ = 0.0;
  integral_ = 0.0;
  errorPrior_ = 0;
  prevControllerOutput_ = 0.0;
}

void PID::setInputLimits(float inMin, float inMax) {

    //Make sure we haven't been given impossible values.
    if (inMin >= inMax) {
        return;
    }

    //Rescale the working variables to reflect the changes

    inMin_  = inMin;
    inMax_  = inMax;
}

void PID::setOutputLimits(float outMin, float outMax) {

    //Make sure we haven't been given impossible values.
    if (outMin >= outMax) {
        return;
    }

    //Rescale the working variables to reflect the changes.
    outMin_  = outMin;
    outMax_  = outMax;
}

void PID::setTunings(float Kc, float tauI, float tauD) {
  //Verify that the tunings make sense.
  if (Kc == 0.0 || tauI < 0.0 || tauD < 0.0) {
    return;
  }

  if ((Kc != Kc_) || (tauI != tauI_) || (tauD != tauD_)) {
    reset();
  }

  Kc_ = Kc;
  tauI_ = tauI;
  tauD_ = tauD;
}

void PID::setInterval(float interval) {
  sampleTime_ = interval;
}

void PID::setSetPoint(float sp) {
  setPoint_ = pid_clip(sp, inMin_, inMax_);
}

void PID::setProcessValue(float pv) {

  processVar_ = pid_clip(pv, inMin_, inMax_);

}

void PID::setBias(float b) {
  bias_ = b;
  reset();
}

float PID::compute() {
  float error = setPoint_ - processVar_;
  // same anti-windup as in the old PID library, but rewritten to handle our bounds
  if (!(prevControllerOutput_ >= outMax_ && error > 0) && !(prevControllerOutput_ <= outMin_ && error < 0)) {
    integral_ += (error*sampleTime_);
  }
  float derivative = (error - errorPrior_) / sampleTime_;
  float output = (Kc_ * error) + (tauI_ * integral_) + (tauD_ * derivative) + bias_;
  errorPrior_ = error;

  prevControllerOutput_ = pid_clip(output, outMin_, outMax_);

  return prevControllerOutput_;
}
<|endoftext|>


<commit_before><commit_msg>GSvar: Fixed somatic CNV-QBIC-report<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010, John B. Rundle <rundle@cse.ucdavis.edu>,
// All rights reserved.
//
// Redistribution and use of this code or any derivative works are
// permitted provided that the following conditions are met:
//
// * Redistributions may not be sold, nor may they be used in a
// commercial product or activity.
//
// * Redistributions that are modified from the original source must
// include the complete source code, including the source code for all
// components used by a binary built from the modified
// sources. However, as a special exception, the source code
// distributed need not include anything that is normally distributed
// (in either source or binary form) with the major components
// (compiler, kernel, and so on) of the operating system on which the
// executable runs, unless that component itself accompanies the
// executable.
//
// * Redistributions 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "SimTimer.h"
#include "SimError.h"
#include "QuakeLibUtil.h"

#include <iomanip>
#include <math.h>
#include <stdexcept>
#include <valarray>

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

/*!
 Initializes a timer within this simulation framework. The timer consists of a name,
 whether it should have a global barrier before checking time, and whether
 it is preemptable by other times (e.g. communication timers).
 */
int SimTimer::initTimer(const std::string &timer_name, const bool &barrier, const bool &preemptable) {
	int		next_num;

	next_num = accumulated_times.size();
	timer_names.push_back(timer_name);
	accumulated_times.push_back(0.0);
	start_times.push_back(0.0);
	use_barrier.push_back(barrier);
	can_preempt.push_back(preemptable);
	num_timings.push_back(0);

	return next_num;
}

/*!
 Start a timer given the timer ID.
 */
void SimTimer::startTimer(const int &timer_id) {
	unsigned int		i;

	// Make sure the timer isn't already running
	assertThrow(!start_times[timer_id], "Timer already started.");

	// If any preemptable timers are running, suspend them
	for (i=0;i<accumulated_times.size();++i) {
		if (can_preempt[i] && start_times[i]) {
			paused_timers.push(i);
		}
	}
	// Record the start time of this timer
	start_times[timer_id] = curTime(use_barrier[timer_id]);
}

/*!
 Stop a timer given the timer ID.
 */
void SimTimer::stopTimer(const int &timer_id) {
	double accum_time;
	int paused_id;

	// Make sure the timer is running before we stop it
	assertThrow(start_times[timer_id], "Timer stopped without first being started.");

	accum_time = curTime(use_barrier[timer_id]) - start_times[timer_id];
	// For any paused timers, subtract this time interval from their running total
	while (!paused_timers.empty()) {
		paused_id = paused_timers.top();
		paused_timers.pop();
		start_times[paused_id] += accum_time;
	}
	// Add this time interval to the accumulated time
	accumulated_times[timer_id] += accum_time;
	start_times[timer_id] = 0;
	num_timings[timer_id]++;
}

/*!
 Check the current time using whatever function is
 appropriate to the environment.
 */
double SimTimer::curTime(const bool &use_barrier) {
#ifdef HAVE_MPI
	if (use_barrier) MPI_Barrier(MPI_COMM_WORLD);
	return MPI_Wtime();
#else
    struct timeval tv;
    gettimeofday(&tv, 0);
    return tv.tv_sec + (tv.tv_usec/1.e6);
#endif
}

/*!
 Gathers global timing statistics and prints the formatted values.
 */
void SimTimer::printAllTimers(std::ostream &out_stream, int world_size, int node_rank, int root_node_rank) {
	int		num_timers, i, max_name_len, ind_col_width, num_col_width, num_prec, num_times, *count_recv_buf, avg_counts;
	double	my_time, *time_recv_buf, max_time, min_time, sum_time, mean_time, stddev_time;

	num_timers = accumulated_times.size();

	// Calculate column widths for formatting
	for (max_name_len=0,i=0;i<num_timers;i++)
		max_name_len = (int)fmax((long unsigned int)max_name_len, (long unsigned int)timer_names[i].size()+5);
	ind_col_width = (int)(log(num_timers) + 1);
	num_prec = 3;
	num_col_width = (int)fmax(num_prec+2, 11);

	// Print the header line
	if (node_rank == root_node_rank) {
		out_stream.setf(std::ios::right);
		out_stream << std::setw(ind_col_width) << "#";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(max_name_len+1) << "Timer Name ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "AvgCounts ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "Min ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "Max ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "Mean ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "StdDev ";
		out_stream << std::endl;
		time_recv_buf = new double[world_size];
		count_recv_buf = new int[world_size];
	} else {
		time_recv_buf = NULL;
		count_recv_buf = NULL;
	}

	// For each timer, get statistics over all nodes in comm and print them to out_stream on node proc_num
	for (i=0;i<num_timers;++i) {
		my_time = accumulated_times[i];
		num_times = num_timings[i];
#ifdef HAVE_MPI
		MPI_Gather(&my_time, 1, MPI_DOUBLE, time_recv_buf, 1, MPI_DOUBLE, root_node_rank, MPI_COMM_WORLD);
		MPI_Gather(&num_times, 1, MPI_INT, count_recv_buf, 1, MPI_INT, root_node_rank, MPI_COMM_WORLD);
#else
		time_recv_buf[0] = my_time;
		count_recv_buf[0] = num_times;
#endif
		if (node_rank == root_node_rank) {
			std::valarray<double> all_times(time_recv_buf, world_size);
			std::valarray<int> all_counts(count_recv_buf, world_size);
			max_time = all_times.max();
			min_time = all_times.min();
			sum_time = all_times.sum();
			avg_counts = all_counts.sum()/world_size;
			mean_time = sum_time/world_size;
			all_times -= mean_time;
			all_times *= all_times;
			stddev_time = sqrt(all_times.sum()/world_size);

			out_stream.setf(std::ios::right);
			out_stream << std::setw(ind_col_width) << i;
			out_stream.setf(std::ios::right);
			out_stream << std::setw(max_name_len) << timer_names[i];
			out_stream.setf(std::ios::fixed);
			out_stream << std::setprecision(num_prec);
			out_stream << std::setw(num_col_width) << avg_counts;
			out_stream << std::setw(num_col_width) << min_time;
			out_stream << std::setw(num_col_width) << max_time;
			out_stream << std::setw(num_col_width) << mean_time;
			out_stream << std::setw(num_col_width) << stddev_time;
			out_stream << std::endl;
			out_stream.unsetf(std::ios::right);
			out_stream.unsetf(std::ios::fixed);
		}
	}
	if (time_recv_buf) delete time_recv_buf;
	if (count_recv_buf) delete count_recv_buf;
}
<commit_msg>fixed a bug with have_sys_time<commit_after>// Copyright (c) 2010, John B. Rundle <rundle@cse.ucdavis.edu>,
// All rights reserved.
//
// Redistribution and use of this code or any derivative works are
// permitted provided that the following conditions are met:
//
// * Redistributions may not be sold, nor may they be used in a
// commercial product or activity.
//
// * Redistributions that are modified from the original source must
// include the complete source code, including the source code for all
// components used by a binary built from the modified
// sources. However, as a special exception, the source code
// distributed need not include anything that is normally distributed
// (in either source or binary form) with the major components
// (compiler, kernel, and so on) of the operating system on which the
// executable runs, unless that component itself accompanies the
// executable.
//
// * Redistributions 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "SimTimer.h"
#include "SimError.h"
#include "QuakeLibUtil.h"

#include <iomanip>
#include <math.h>
#include <stdexcept>
#include <valarray>

#ifdef VC_HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

/*!
 Initializes a timer within this simulation framework. The timer consists of a name,
 whether it should have a global barrier before checking time, and whether
 it is preemptable by other times (e.g. communication timers).
 */
int SimTimer::initTimer(const std::string &timer_name, const bool &barrier, const bool &preemptable) {
	int		next_num;

	next_num = accumulated_times.size();
	timer_names.push_back(timer_name);
	accumulated_times.push_back(0.0);
	start_times.push_back(0.0);
	use_barrier.push_back(barrier);
	can_preempt.push_back(preemptable);
	num_timings.push_back(0);

	return next_num;
}

/*!
 Start a timer given the timer ID.
 */
void SimTimer::startTimer(const int &timer_id) {
	unsigned int		i;

	// Make sure the timer isn't already running
	assertThrow(!start_times[timer_id], "Timer already started.");

	// If any preemptable timers are running, suspend them
	for (i=0;i<accumulated_times.size();++i) {
		if (can_preempt[i] && start_times[i]) {
			paused_timers.push(i);
		}
	}
	// Record the start time of this timer
	start_times[timer_id] = curTime(use_barrier[timer_id]);
}

/*!
 Stop a timer given the timer ID.
 */
void SimTimer::stopTimer(const int &timer_id) {
	double accum_time;
	int paused_id;

	// Make sure the timer is running before we stop it
	assertThrow(start_times[timer_id], "Timer stopped without first being started.");

	accum_time = curTime(use_barrier[timer_id]) - start_times[timer_id];
	// For any paused timers, subtract this time interval from their running total
	while (!paused_timers.empty()) {
		paused_id = paused_timers.top();
		paused_timers.pop();
		start_times[paused_id] += accum_time;
	}
	// Add this time interval to the accumulated time
	accumulated_times[timer_id] += accum_time;
	start_times[timer_id] = 0;
	num_timings[timer_id]++;
}

/*!
 Check the current time using whatever function is
 appropriate to the environment.
 */
double SimTimer::curTime(const bool &use_barrier) {
#ifdef HAVE_MPI
	if (use_barrier) MPI_Barrier(MPI_COMM_WORLD);
	return MPI_Wtime();
#else
    struct timeval tv;
    gettimeofday(&tv, 0);
    return tv.tv_sec + (tv.tv_usec/1.e6);
#endif
}

/*!
 Gathers global timing statistics and prints the formatted values.
 */
void SimTimer::printAllTimers(std::ostream &out_stream, int world_size, int node_rank, int root_node_rank) {
	int		num_timers, i, max_name_len, ind_col_width, num_col_width, num_prec, num_times, *count_recv_buf, avg_counts;
	double	my_time, *time_recv_buf, max_time, min_time, sum_time, mean_time, stddev_time;

	num_timers = accumulated_times.size();

	// Calculate column widths for formatting
	for (max_name_len=0,i=0;i<num_timers;i++)
		max_name_len = (int)fmax((long unsigned int)max_name_len, (long unsigned int)timer_names[i].size()+5);
	ind_col_width = (int)(log(num_timers) + 1);
	num_prec = 3;
	num_col_width = (int)fmax(num_prec+2, 11);

	// Print the header line
	if (node_rank == root_node_rank) {
		out_stream.setf(std::ios::right);
		out_stream << std::setw(ind_col_width) << "#";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(max_name_len+1) << "Timer Name ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "AvgCounts ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "Min ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "Max ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "Mean ";
		out_stream.setf(std::ios::right);
		out_stream << std::setw(num_col_width) << "StdDev ";
		out_stream << std::endl;
		time_recv_buf = new double[world_size];
		count_recv_buf = new int[world_size];
	} else {
		time_recv_buf = NULL;
		count_recv_buf = NULL;
	}

	// For each timer, get statistics over all nodes in comm and print them to out_stream on node proc_num
	for (i=0;i<num_timers;++i) {
		my_time = accumulated_times[i];
		num_times = num_timings[i];
#ifdef HAVE_MPI
		MPI_Gather(&my_time, 1, MPI_DOUBLE, time_recv_buf, 1, MPI_DOUBLE, root_node_rank, MPI_COMM_WORLD);
		MPI_Gather(&num_times, 1, MPI_INT, count_recv_buf, 1, MPI_INT, root_node_rank, MPI_COMM_WORLD);
#else
		time_recv_buf[0] = my_time;
		count_recv_buf[0] = num_times;
#endif
		if (node_rank == root_node_rank) {
			std::valarray<double> all_times(time_recv_buf, world_size);
			std::valarray<int> all_counts(count_recv_buf, world_size);
			max_time = all_times.max();
			min_time = all_times.min();
			sum_time = all_times.sum();
			avg_counts = all_counts.sum()/world_size;
			mean_time = sum_time/world_size;
			all_times -= mean_time;
			all_times *= all_times;
			stddev_time = sqrt(all_times.sum()/world_size);

			out_stream.setf(std::ios::right);
			out_stream << std::setw(ind_col_width) << i;
			out_stream.setf(std::ios::right);
			out_stream << std::setw(max_name_len) << timer_names[i];
			out_stream.setf(std::ios::fixed);
			out_stream << std::setprecision(num_prec);
			out_stream << std::setw(num_col_width) << avg_counts;
			out_stream << std::setw(num_col_width) << min_time;
			out_stream << std::setw(num_col_width) << max_time;
			out_stream << std::setw(num_col_width) << mean_time;
			out_stream << std::setw(num_col_width) << stddev_time;
			out_stream << std::endl;
			out_stream.unsetf(std::ios::right);
			out_stream.unsetf(std::ios::fixed);
		}
	}
	if (time_recv_buf) delete time_recv_buf;
	if (count_recv_buf) delete count_recv_buf;
}
<|endoftext|>


<commit_before>#include <cctype>
#include <cmath>
#include <cstdlib>
#include <array>
#include <iostream>
#include <fstream>
#include <list>
#include <map>
#include <queue>
#include <string>
#include <sstream>
#include <vector>

#include <yaml-cpp/yaml.h>
#include <SFML/Graphics.hpp>

static const unsigned int PPB = 48;
static const sf::Vector2i X(1, 0);
static const sf::Vector2i Y(0, 1);
static const sf::Vector2i XY(1, 1);

extern sf::Font font;
extern sf::RenderTexture tile_texture[26];
extern std::map<std::string, std::string> dictionary;

// TODO better place for this?
// for classes that handle sf::Events
class InputReader
{
protected:
	bool finished;
public:
	InputReader() { finished = false; }
	virtual ~InputReader() {}

	inline bool is_finished() const
	{
		return finished;
	}

	virtual bool process_event(sf::Event& event)
	{
		return true;
	}
};

#include "menu.hpp"
#include "control.hpp"
#include "message.hpp"
#include "cursor.hpp"
#include "tile.hpp"
#include "grid.hpp"
#include "hand.hpp"
#include "buffer.hpp"
<commit_msg>Ignore unused paramter warning for InputReader<commit_after>#include <cctype>
#include <cmath>
#include <cstdlib>
#include <array>
#include <iostream>
#include <fstream>
#include <list>
#include <map>
#include <queue>
#include <string>
#include <sstream>
#include <vector>

#include <yaml-cpp/yaml.h>
#include <SFML/Graphics.hpp>

static const unsigned int PPB = 48;
static const sf::Vector2i X(1, 0);
static const sf::Vector2i Y(0, 1);
static const sf::Vector2i XY(1, 1);

extern sf::Font font;
extern sf::RenderTexture tile_texture[26];
extern std::map<std::string, std::string> dictionary;

// TODO better place for this?
// for classes that handle sf::Events
class InputReader
{
protected:
	bool finished;
public:
	InputReader() { finished = false; }
	virtual ~InputReader() {}

	inline bool is_finished() const
	{
		return finished;
	}

#pragma GCC diagnostic ignored "-Wunused-parameter"
	virtual bool process_event(sf::Event& event)
	{
		return true;
	}
#pragma GCC diagnostic pop
};

#include "menu.hpp"
#include "control.hpp"
#include "message.hpp"
#include "cursor.hpp"
#include "tile.hpp"
#include "grid.hpp"
#include "hand.hpp"
#include "buffer.hpp"
<|endoftext|>


<commit_before>#include "helper.h"
#include "../lib/triangle.h"
#include "../lib/xorshift.h"

#include <catch.hpp>

TEST_CASE("Test Triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = random_triangle();

        Vec normal = triangle.normal;

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));

        // Verify normal is perpendicular to edges of triangle.
        float cos_u = normal * triangle.u.Normalize();
        float cos_v = normal * triangle.v.Normalize();
        REQUIRE(cos_u == Approx(0.f));
        REQUIRE(cos_v == Approx(0.f));
    }
}

TEST_CASE("Test interpolate triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;
    static xorshift64star<float> uniform{4};

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = test_triangle( random_vec(), random_vec(),
            random_vec(), random_vec().Normalize(), random_vec().Normalize(),
            random_vec().Normalize());

        float r = uniform();
        float s = uniform();
        float t = uniform();
        while( r+s+t > 1.0f) {
          r = uniform();
          s = uniform();
          t = uniform();
        }
        Vec normal = triangle.interpolate_normal(r, s, t);

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));
    }
}
<commit_msg>Test trival triangle normal interpolation.<commit_after>#include "helper.h"
#include "../lib/triangle.h"
#include "../lib/xorshift.h"

#include <catch.hpp>

TEST_CASE("Test Triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = random_triangle();

        Vec normal = triangle.normal;

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));

        // Verify normal is perpendicular to edges of triangle.
        float cos_u = normal * triangle.u.Normalize();
        float cos_v = normal * triangle.v.Normalize();
        REQUIRE(cos_u == Approx(0.f));
        REQUIRE(cos_v == Approx(0.f));
    }
}

TEST_CASE("Test interpolate triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;
    static xorshift64star<float> uniform{4};

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = test_triangle( random_vec(), random_vec(),
            random_vec(), random_vec().Normalize(), random_vec().Normalize(),
            random_vec().Normalize());

        float r = uniform();
        float s = uniform();
        float t = uniform();
        while( r+s+t > 1.0f) {
          r = uniform();
          s = uniform();
          t = uniform();
        }
        Vec normal = triangle.interpolate_normal(r, s, t);

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));
    }
}

TEST_CASE("Test interpolate triangle normal with trivial case", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;
    static xorshift64star<float> uniform{4};

    auto normal = random_vec().Normalize();
    Triangle triangle = test_triangle( random_vec(), random_vec(),
        random_vec(), normal, normal, normal);
    for (int j = 0; j < NUM_SAMPLES; ++j) {

        float r = uniform();
        float s = uniform();
        float t = uniform();
        while( r+s+t > 1.0f) {
          r = uniform();
          s = uniform();
          t = uniform();
        }
        Vec interpolated_normal = triangle.interpolate_normal(r, s, t);

        // Verify unit length of normal.
        float length = interpolated_normal.Length();
        REQUIRE(length == Approx(1.f));

        // Verify that interpolated normal is equal to actual normal
        REQUIRE(interpolated_normal.x == Approx(normal.x));
        REQUIRE(interpolated_normal.y == Approx(normal.y));
        REQUIRE(interpolated_normal.z == Approx(normal.z));
    }
}
<|endoftext|>


<commit_before><commit_msg>GSvar: fixed transcript formatting in HTML report.<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <generic/gensys.h>

#include <vcl/msgbox.hxx>
#include <vcl/button.hxx>

#include <svdata.hxx>

#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <osl/process.h>
#include <osl/thread.h>

#include "vcl/unohelp.hxx"
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

using namespace com::sun::star;

namespace {

OUString GetNativeMessageBoxButtonText( int nButtonId, bool bUseResources )
{
    OUString aText;
    if( bUseResources )
    {
        aText = Button::GetStandardText( nButtonId );
    }
    if( aText.isEmpty() )
    {
        switch( nButtonId )
        {
        case BUTTON_OK:
            aText = "OK";
            break;
        case BUTTON_CANCEL:
            aText = "Cancel";
            break;
        case BUTTON_ABORT:
            aText = "Abort";
            break;
        case BUTTON_RETRY:
            aText = "Retry";
            break;
        case BUTTON_IGNORE:
            aText = "Ignore";
            break;
        case BUTTON_YES:
            aText = "Yes";
            break;
        case BUTTON_NO:
            aText = "No";
            break;
        }
    }
    return aText;
}

}

SalGenericSystem::SalGenericSystem()
{
}

SalGenericSystem::~SalGenericSystem()
{
}

int SalGenericSystem::ShowNativeMessageBox( const OUString& rTitle, const OUString& rMessage,
                                            int nButtonCombination, int nDefaultButton,
                                            bool bUseResources )
{
    int nDefButton = 0;
    std::list< OUString > aButtons;
    int nButtonIds[5], nBut = 0;

    ImplHideSplash();

    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
    {
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_OK, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
    }
    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
    {
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_YES, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_NO, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
        if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
            nDefButton = 1;
    }
    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
    {
        if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
        {
            aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_RETRY, bUseResources ) );
            nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
        }
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_CANCEL, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
        if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
            nDefButton = aButtons.size()-1;
    }
    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
    {
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_ABORT, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_RETRY, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_IGNORE, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
        switch( nDefaultButton )
        {
            case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
            case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
        }
    }

    int nResult = ShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );

    return nResult != -1 ? nButtonIds[ nResult ] : 0;
}

#if !defined(ANDROID) && !defined(IOS)

// X11-specific

const char* SalGenericSystem::getFrameResName()
{
    /*  according to ICCCM:
     *  first search command line for -name parameter
     *  then try RESOURCE_NAME environment variable
     *  then use argv[0] stripped by directories
     */
    static OStringBuffer aResName;
    if( !aResName.getLength() )
    {
        int nArgs = osl_getCommandArgCount();
        for( int n = 0; n < nArgs-1; n++ )
        {
            OUString aArg;
            if( ! osl_getCommandArg( n, &aArg.pData ) &&
                aArg.equalsIgnoreAsciiCase("-name") &&
                ! osl_getCommandArg( n+1, &aArg.pData ) )
            {
                aResName.append( OUStringToOString( aArg, osl_getThreadTextEncoding() ) );
                break;
            }
        }
        if( !aResName.getLength() )
        {
            const char* pEnv = getenv( "RESOURCE_NAME" );
            if( pEnv && *pEnv )
                aResName.append( pEnv );
        }
        if( !aResName.getLength() )
            aResName.append( "VCLSalFrame" );
    }
    return aResName.getStr();
}

const char* SalGenericSystem::getFrameClassName()
{
    static OStringBuffer aClassName;
    if( !aClassName.getLength() )
    {
        OUString aIni, aProduct;
        rtl::Bootstrap::get( "BRAND_BASE_DIR", aIni );
        aIni += "/program/" + SAL_CONFIGFILE( "bootstrap" );
        rtl::Bootstrap aBootstrap( aIni );
        aBootstrap.getFrom( "ProductKey", aProduct );

        if( !aProduct.isEmpty() )
            aClassName.append( OUStringToOString( aProduct, osl_getThreadTextEncoding() ) );
        else
            aClassName.append( "VCLSalFrame" );
    }
    return aClassName.getStr();
}

OString SalGenericSystem::getFrameResName( SalExtStyle nStyle )
{
    OStringBuffer aBuf( 64 );
    aBuf.append( getFrameResName() );
    if( (nStyle & SAL_FRAME_EXT_STYLE_DOCUMENT) )
        aBuf.append( ".DocumentWindow" );

    return aBuf.makeStringAndClear();
}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix previous fix<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <generic/gensys.h>

#include <vcl/msgbox.hxx>
#include <vcl/button.hxx>

#include <svdata.hxx>

#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <osl/process.h>
#include <osl/thread.h>

#include "vcl/unohelp.hxx"
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

using namespace com::sun::star;

namespace {

OUString GetNativeMessageBoxButtonText( int nButtonId, bool bUseResources )
{
    OUString aText;
    if( bUseResources )
    {
        aText = Button::GetStandardText( nButtonId );
    }
    if( aText.isEmpty() )
    {
        switch( nButtonId )
        {
        case BUTTON_OK:
            aText = "OK";
            break;
        case BUTTON_CANCEL:
            aText = "Cancel";
            break;
        case BUTTON_ABORT:
            aText = "Abort";
            break;
        case BUTTON_RETRY:
            aText = "Retry";
            break;
        case BUTTON_IGNORE:
            aText = "Ignore";
            break;
        case BUTTON_YES:
            aText = "Yes";
            break;
        case BUTTON_NO:
            aText = "No";
            break;
        }
    }
    return aText;
}

}

SalGenericSystem::SalGenericSystem()
{
}

SalGenericSystem::~SalGenericSystem()
{
}

int SalGenericSystem::ShowNativeMessageBox( const OUString& rTitle, const OUString& rMessage,
                                            int nButtonCombination, int nDefaultButton,
                                            bool bUseResources )
{
    int nDefButton = 0;
    std::list< OUString > aButtons;
    int nButtonIds[5], nBut = 0;

    ImplHideSplash();

    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
    {
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_OK, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
    }
    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
    {
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_YES, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_NO, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
        if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
            nDefButton = 1;
    }
    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
        nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
    {
        if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
        {
            aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_RETRY, bUseResources ) );
            nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
        }
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_CANCEL, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
        if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
            nDefButton = aButtons.size()-1;
    }
    if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
    {
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_ABORT, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_RETRY, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
        aButtons.push_back( GetNativeMessageBoxButtonText( BUTTON_IGNORE, bUseResources ) );
        nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
        switch( nDefaultButton )
        {
            case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
            case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
        }
    }

    int nResult = ShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );

    return nResult != -1 ? nButtonIds[ nResult ] : 0;
}

#if !defined(ANDROID) && !defined(IOS)

// X11-specific

const char* SalGenericSystem::getFrameResName()
{
    /*  according to ICCCM:
     *  first search command line for -name parameter
     *  then try RESOURCE_NAME environment variable
     *  then use argv[0] stripped by directories
     */
    static OStringBuffer aResName;
    if( !aResName.getLength() )
    {
        int nArgs = osl_getCommandArgCount();
        for( int n = 0; n < nArgs-1; n++ )
        {
            OUString aArg;
            if( ! osl_getCommandArg( n, &aArg.pData ) &&
                aArg.equalsIgnoreAsciiCase("-name") &&
                ! osl_getCommandArg( n+1, &aArg.pData ) )
            {
                aResName.append( OUStringToOString( aArg, osl_getThreadTextEncoding() ) );
                break;
            }
        }
        if( !aResName.getLength() )
        {
            const char* pEnv = getenv( "RESOURCE_NAME" );
            if( pEnv && *pEnv )
                aResName.append( pEnv );
        }
        if( !aResName.getLength() )
            aResName.append( "VCLSalFrame" );
    }
    return aResName.getStr();
}

const char* SalGenericSystem::getFrameClassName()
{
    static OStringBuffer aClassName;
    if( !aClassName.getLength() )
    {
        OUString aIni, aProduct;
        rtl::Bootstrap::get( "BRAND_BASE_DIR", aIni );
        aIni += "/program/" SAL_CONFIGFILE( "bootstrap" );
        rtl::Bootstrap aBootstrap( aIni );
        aBootstrap.getFrom( "ProductKey", aProduct );

        if( !aProduct.isEmpty() )
            aClassName.append( OUStringToOString( aProduct, osl_getThreadTextEncoding() ) );
        else
            aClassName.append( "VCLSalFrame" );
    }
    return aClassName.getStr();
}

OString SalGenericSystem::getFrameResName( SalExtStyle nStyle )
{
    OStringBuffer aBuf( 64 );
    aBuf.append( getFrameResName() );
    if( (nStyle & SAL_FRAME_EXT_STYLE_DOCUMENT) )
        aBuf.append( ".DocumentWindow" );

    return aBuf.makeStringAndClear();
}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <dropwhile.hpp>
#include <range.hpp>

#include <vector>
#include <iostream>

using iter::dropwhile;
using iter::range;

int main() {
    std::vector<int> ivec{1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4};
    for (auto i : dropwhile([] (int i) {return i < 5;}, ivec)) {
        std::cout << i << '\n';
    }

    for (auto i : dropwhile([] (int i) {return i < 5;}, range(10))) {
        std::cout << i << '\n';
    }

    for (auto i : dropwhile([] (int i) {return i < 5;},
                {1, 2, 3, 4, 5, 6, 7, 8, 9})) {
        std::cout << i << '\n';
    }

    return 0;
}
<commit_msg>Adds dropwhile temporary test and asserts<commit_after>#include <dropwhile.hpp>
#include <range.hpp>

#include <vector>
#include <iostream>
#include <cassert>

using iter::dropwhile;
using iter::range;

int main() {
    std::vector<int> ivec{1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4};
    for (auto& i : dropwhile([] (int i) {return i < 5;}, ivec)) {
        std::cout << i << '\n';
        i = 69;
    }
    assert(ivec.at(0) == 1);
    assert(ivec.at(4) == 69);

    for (auto i : dropwhile([] (int i) {return i < 5;}, range(10))) {
        std::cout << i << '\n';
    }

    for (auto i : dropwhile([] (int i) {return i < 5;},
                {1, 2, 3, 4, 5, 6, 7, 8, 9})) {
        std::cout << i << '\n';
    }

    for (auto i : dropwhile([] (int i) {return i < 5;},
                std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9})) {
        std::cout << i << '\n';
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2017 ScyllaDB Ltd.
 */

#pragma once

#include <boost/range/numeric.hpp>

#include <seastar/testing/seastar_test.hh>
#include <seastar/core/file.hh>

namespace seastar {

class mock_read_only_file final : public file_impl {
    bool _closed = false;
    uint64_t _total_file_size;
    size_t _allowed_read_requests = 0;
    std::function<void(size_t)> _verify_length;
private:
    size_t verify_read(uint64_t position, size_t length) {
        BOOST_CHECK(!_closed);
        BOOST_CHECK_LE(position, _total_file_size);
        BOOST_CHECK_LE(position + length, _total_file_size);
        if (position + length != _total_file_size) {
            _verify_length(length);
        }
        BOOST_CHECK(_allowed_read_requests);
        assert(_allowed_read_requests);
        _allowed_read_requests--;
        return length;
    }
public:
    explicit mock_read_only_file(uint64_t file_size) noexcept
        : _total_file_size(file_size)
        , _verify_length([] (auto) { })
    { }

    void set_read_size_verifier(std::function<void(size_t)> fn) {
        _verify_length = fn;
    }
    void set_expected_read_size(size_t expected) {
        _verify_length = [expected] (auto length) {
            BOOST_CHECK_EQUAL(length, expected);
        };
    }
    void set_allowed_read_requests(size_t requests) {
        _allowed_read_requests = requests;
    }

    virtual future<size_t> write_dma(uint64_t, const void*, size_t, const io_priority_class&) override {
        throw std::bad_function_call();
    }
    virtual future<size_t> write_dma(uint64_t, std::vector<iovec>, const io_priority_class&) override {
        throw std::bad_function_call();
    }
    virtual future<size_t> read_dma(uint64_t pos, void*, size_t len, const io_priority_class&) override {
        return make_ready_future<size_t>(verify_read(pos, len));
    }
    virtual future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class&) override {
        auto length = boost::accumulate(iov | boost::adaptors::transformed([] (auto&& iov) { return iov.iov_len; }),
                                        size_t(0), std::plus<size_t>());
        return make_ready_future<size_t>(verify_read(pos, length));
    }
    virtual future<> flush() override {
        return make_ready_future<>();
    }
    virtual future<struct stat> stat() override {
        throw std::bad_function_call();
    }
    virtual future<> truncate(uint64_t) {
        throw std::bad_function_call();
    }
    virtual future<> discard(uint64_t offset, uint64_t length) override {
        throw std::bad_function_call();
    }
    virtual future<> allocate(uint64_t position, uint64_t length) override {
        throw std::bad_function_call();
    }
    virtual future<uint64_t> size() override {
        return make_ready_future<uint64_t>(_total_file_size);
    }
    virtual future<> close() override {
        BOOST_CHECK(!_closed);
        _closed = true;
        return make_ready_future<>();
    }
    virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)>) override {
        throw std::bad_function_call();
    }
    virtual future<temporary_buffer<uint8_t>> dma_read_bulk(uint64_t offset, size_t range_size, const io_priority_class&) override {
        auto length = verify_read(offset, range_size);
        return make_ready_future<temporary_buffer<uint8_t>>(temporary_buffer<uint8_t>(length));
    }
};

}
<commit_msg>tests/mock_file: add missing override<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2017 ScyllaDB Ltd.
 */

#pragma once

#include <boost/range/numeric.hpp>

#include <seastar/testing/seastar_test.hh>
#include <seastar/core/file.hh>

namespace seastar {

class mock_read_only_file final : public file_impl {
    bool _closed = false;
    uint64_t _total_file_size;
    size_t _allowed_read_requests = 0;
    std::function<void(size_t)> _verify_length;
private:
    size_t verify_read(uint64_t position, size_t length) {
        BOOST_CHECK(!_closed);
        BOOST_CHECK_LE(position, _total_file_size);
        BOOST_CHECK_LE(position + length, _total_file_size);
        if (position + length != _total_file_size) {
            _verify_length(length);
        }
        BOOST_CHECK(_allowed_read_requests);
        assert(_allowed_read_requests);
        _allowed_read_requests--;
        return length;
    }
public:
    explicit mock_read_only_file(uint64_t file_size) noexcept
        : _total_file_size(file_size)
        , _verify_length([] (auto) { })
    { }

    void set_read_size_verifier(std::function<void(size_t)> fn) {
        _verify_length = fn;
    }
    void set_expected_read_size(size_t expected) {
        _verify_length = [expected] (auto length) {
            BOOST_CHECK_EQUAL(length, expected);
        };
    }
    void set_allowed_read_requests(size_t requests) {
        _allowed_read_requests = requests;
    }

    virtual future<size_t> write_dma(uint64_t, const void*, size_t, const io_priority_class&) override {
        throw std::bad_function_call();
    }
    virtual future<size_t> write_dma(uint64_t, std::vector<iovec>, const io_priority_class&) override {
        throw std::bad_function_call();
    }
    virtual future<size_t> read_dma(uint64_t pos, void*, size_t len, const io_priority_class&) override {
        return make_ready_future<size_t>(verify_read(pos, len));
    }
    virtual future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class&) override {
        auto length = boost::accumulate(iov | boost::adaptors::transformed([] (auto&& iov) { return iov.iov_len; }),
                                        size_t(0), std::plus<size_t>());
        return make_ready_future<size_t>(verify_read(pos, length));
    }
    virtual future<> flush() override {
        return make_ready_future<>();
    }
    virtual future<struct stat> stat() override {
        throw std::bad_function_call();
    }
    virtual future<> truncate(uint64_t) override {
        throw std::bad_function_call();
    }
    virtual future<> discard(uint64_t offset, uint64_t length) override {
        throw std::bad_function_call();
    }
    virtual future<> allocate(uint64_t position, uint64_t length) override {
        throw std::bad_function_call();
    }
    virtual future<uint64_t> size() override {
        return make_ready_future<uint64_t>(_total_file_size);
    }
    virtual future<> close() override {
        BOOST_CHECK(!_closed);
        _closed = true;
        return make_ready_future<>();
    }
    virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)>) override {
        throw std::bad_function_call();
    }
    virtual future<temporary_buffer<uint8_t>> dma_read_bulk(uint64_t offset, size_t range_size, const io_priority_class&) override {
        auto length = verify_read(offset, range_size);
        return make_ready_future<temporary_buffer<uint8_t>>(temporary_buffer<uint8_t>(length));
    }
};

}
<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

// MOOSE includes
#include "VectorPostprocessor.h"
#include "SubProblem.h"
#include "Conversion.h"
#include "UserObject.h"
#include "FEProblem.h"

InputParameters
VectorPostprocessor::validParams()
{
  InputParameters params = UserObject::validParams();
  params += OutputInterface::validParams();
  params.addParam<bool>("contains_complete_history",
                        false,
                        "Set this flag to indicate that the values in all vectors declared by this "
                        "VPP represent a time history (e.g. with each invocation, new values are "
                        "added and old values are never removed). This changes the output so that "
                        "only a single file is output and updated with each invocation");

  // VPPs can set this to true if their resulting vectors are naturally replicated in parallel
  // setting this to false will keep MOOSE from unnecessarily broadcasting those vectors
  params.addPrivateParam<bool>("_auto_broadcast", true);

  // VPPs can operate in "distributed" mode, which disables the automatic broadcasting
  // and results in an individual file per processor if CSV output is enabled
  MooseEnum parallel_type("DISTRIBUTED REPLICATED", "REPLICATED");
  params.addParam<MooseEnum>(
      "parallel_type",
      parallel_type,
      "Set how the data is represented within the VectorPostprocessor (VPP); 'distributed' "
      "indicates that data within the VPP is distributed and no auto communication is preformed, "
      "this setting will result in parallel output within the CSV output; 'replicated' indicates "
      "that the data within the VPP is correct on processor 0, the data will automatically be "
      "broadcast to all processors unless the '_auto_broadcast' param is set to false within the "
      "validParams function.");

  params.addParamNamesToGroup("outputs", "Advanced");
  params.registerBase("VectorPostprocessor");
  return params;
}

VectorPostprocessor::VectorPostprocessor(const MooseObject * moose_object)
  : OutputInterface(moose_object->parameters()),
    _vpp_name(MooseUtils::shortName(moose_object->parameters().get<std::string>("_object_name"))),
    _vpp_fe_problem(
        *moose_object->parameters().getCheckedPointerParam<FEProblemBase *>("_fe_problem_base")),
    _parallel_type(moose_object->parameters().get<MooseEnum>("parallel_type")),
    _vpp_moose_object(*moose_object),
    _vpp_tid(moose_object->parameters().isParamValid("_tid")
                 ? moose_object->parameters().get<THREAD_ID>("_tid")
                 : 0),
    _contains_complete_history(moose_object->parameters().get<bool>("contains_complete_history")),
    _is_distributed(_parallel_type == "DISTRIBUTED"),
    _is_broadcast(_is_distributed || !moose_object->parameters().get<bool>("_auto_broadcast"))
{
}

VectorPostprocessorValue &
VectorPostprocessor::declareVector(const std::string & vector_name)
{
  _vector_names.insert(vector_name);

  if (_vpp_tid)
    return _thread_local_vectors.emplace(vector_name, VectorPostprocessorValue()).first->second;

  // _is_broadcast = true (_auto_broadcast = false) then data is produced in a replicated manner
  ReporterMode mode = REPORTER_MODE_ROOT;
  if (_is_broadcast)
    mode = REPORTER_MODE_REPLICATED;
  if (_is_distributed)
    mode = REPORTER_MODE_DISTRIBUTED;

  return _vpp_fe_problem.getReporterData(ReporterData::WriteKey())
      .declareReporterValue<VectorPostprocessorValue,
                            VectorPostprocessorContext<VectorPostprocessorValue>>(
          VectorPostprocessorReporterName(_vpp_name, vector_name), mode, _vpp_moose_object);
}

const std::set<std::string> &
VectorPostprocessor::getVectorNames() const
{
  return _vector_names;
}

// Explicit instantiation
template class VectorPostprocessorContext<VectorPostprocessorValue>;
const ReporterMode REPORTER_MODE_VPP_SCATTER("VPP_SCATTER");

template <typename T>
VectorPostprocessorContext<T>::VectorPostprocessorContext(const libMesh::ParallelObject & other,
                                                          const MooseObject & producer,
                                                          ReporterState<T> & state)
  : ReporterGeneralContext<T>(other, producer, state)
{
}

template <typename T>
void
VectorPostprocessorContext<T>::finalize()
{
  ReporterGeneralContext<T>::finalize();

  const auto & consumer_modes = this->state().getConsumers();
  auto func = [](const std::pair<ReporterMode, const MooseObject *> & mode_pair)
  { return mode_pair.first == REPORTER_MODE_VPP_SCATTER; };
  if (std::find_if(consumer_modes.begin(), consumer_modes.end(), func) != consumer_modes.end())
  {
    const T & value = this->state().value();
    if (this->processor_id() == 0 && value.size() != this->n_processors())
      mooseError("The VectorPostprocessor value to be scatter has a length of ",
                 value.size(),
                 "; it must be the same length as the number of processors (",
                 this->n_processors(),
                 ").");

    this->comm().scatter(value, _scatter_value);
  }
}

template <typename T>
void
VectorPostprocessorContext<T>::copyValuesBack()
{
  ReporterGeneralContext<T>::copyValuesBack();
  _scatter_value_old = _scatter_value;
}

template <typename T>
const ScatterVectorPostprocessorValue &
VectorPostprocessorContext<T>::getScatterValue() const
{
  return _scatter_value;
}

template <typename T>
const ScatterVectorPostprocessorValue &
VectorPostprocessorContext<T>::getScatterValueOld() const
{
  return _scatter_value_old;
}
<commit_msg>Move templated member definitions before explicit instantiation. (#21873)<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

// MOOSE includes
#include "VectorPostprocessor.h"
#include "SubProblem.h"
#include "Conversion.h"
#include "UserObject.h"
#include "FEProblem.h"

InputParameters
VectorPostprocessor::validParams()
{
  InputParameters params = UserObject::validParams();
  params += OutputInterface::validParams();
  params.addParam<bool>("contains_complete_history",
                        false,
                        "Set this flag to indicate that the values in all vectors declared by this "
                        "VPP represent a time history (e.g. with each invocation, new values are "
                        "added and old values are never removed). This changes the output so that "
                        "only a single file is output and updated with each invocation");

  // VPPs can set this to true if their resulting vectors are naturally replicated in parallel
  // setting this to false will keep MOOSE from unnecessarily broadcasting those vectors
  params.addPrivateParam<bool>("_auto_broadcast", true);

  // VPPs can operate in "distributed" mode, which disables the automatic broadcasting
  // and results in an individual file per processor if CSV output is enabled
  MooseEnum parallel_type("DISTRIBUTED REPLICATED", "REPLICATED");
  params.addParam<MooseEnum>(
      "parallel_type",
      parallel_type,
      "Set how the data is represented within the VectorPostprocessor (VPP); 'distributed' "
      "indicates that data within the VPP is distributed and no auto communication is preformed, "
      "this setting will result in parallel output within the CSV output; 'replicated' indicates "
      "that the data within the VPP is correct on processor 0, the data will automatically be "
      "broadcast to all processors unless the '_auto_broadcast' param is set to false within the "
      "validParams function.");

  params.addParamNamesToGroup("outputs", "Advanced");
  params.registerBase("VectorPostprocessor");
  return params;
}

VectorPostprocessor::VectorPostprocessor(const MooseObject * moose_object)
  : OutputInterface(moose_object->parameters()),
    _vpp_name(MooseUtils::shortName(moose_object->parameters().get<std::string>("_object_name"))),
    _vpp_fe_problem(
        *moose_object->parameters().getCheckedPointerParam<FEProblemBase *>("_fe_problem_base")),
    _parallel_type(moose_object->parameters().get<MooseEnum>("parallel_type")),
    _vpp_moose_object(*moose_object),
    _vpp_tid(moose_object->parameters().isParamValid("_tid")
                 ? moose_object->parameters().get<THREAD_ID>("_tid")
                 : 0),
    _contains_complete_history(moose_object->parameters().get<bool>("contains_complete_history")),
    _is_distributed(_parallel_type == "DISTRIBUTED"),
    _is_broadcast(_is_distributed || !moose_object->parameters().get<bool>("_auto_broadcast"))
{
}

VectorPostprocessorValue &
VectorPostprocessor::declareVector(const std::string & vector_name)
{
  _vector_names.insert(vector_name);

  if (_vpp_tid)
    return _thread_local_vectors.emplace(vector_name, VectorPostprocessorValue()).first->second;

  // _is_broadcast = true (_auto_broadcast = false) then data is produced in a replicated manner
  ReporterMode mode = REPORTER_MODE_ROOT;
  if (_is_broadcast)
    mode = REPORTER_MODE_REPLICATED;
  if (_is_distributed)
    mode = REPORTER_MODE_DISTRIBUTED;

  return _vpp_fe_problem.getReporterData(ReporterData::WriteKey())
      .declareReporterValue<VectorPostprocessorValue,
                            VectorPostprocessorContext<VectorPostprocessorValue>>(
          VectorPostprocessorReporterName(_vpp_name, vector_name), mode, _vpp_moose_object);
}

const std::set<std::string> &
VectorPostprocessor::getVectorNames() const
{
  return _vector_names;
}

const ReporterMode REPORTER_MODE_VPP_SCATTER("VPP_SCATTER");

template <typename T>
VectorPostprocessorContext<T>::VectorPostprocessorContext(const libMesh::ParallelObject & other,
                                                          const MooseObject & producer,
                                                          ReporterState<T> & state)
  : ReporterGeneralContext<T>(other, producer, state)
{
}

template <typename T>
void
VectorPostprocessorContext<T>::finalize()
{
  ReporterGeneralContext<T>::finalize();

  const auto & consumer_modes = this->state().getConsumers();
  auto func = [](const std::pair<ReporterMode, const MooseObject *> & mode_pair)
  { return mode_pair.first == REPORTER_MODE_VPP_SCATTER; };
  if (std::find_if(consumer_modes.begin(), consumer_modes.end(), func) != consumer_modes.end())
  {
    const T & value = this->state().value();
    if (this->processor_id() == 0 && value.size() != this->n_processors())
      mooseError("The VectorPostprocessor value to be scatter has a length of ",
                 value.size(),
                 "; it must be the same length as the number of processors (",
                 this->n_processors(),
                 ").");

    this->comm().scatter(value, _scatter_value);
  }
}

template <typename T>
void
VectorPostprocessorContext<T>::copyValuesBack()
{
  ReporterGeneralContext<T>::copyValuesBack();
  _scatter_value_old = _scatter_value;
}

template <typename T>
const ScatterVectorPostprocessorValue &
VectorPostprocessorContext<T>::getScatterValue() const
{
  return _scatter_value;
}

template <typename T>
const ScatterVectorPostprocessorValue &
VectorPostprocessorContext<T>::getScatterValueOld() const
{
  return _scatter_value_old;
}

// Explicit instantiation
template class VectorPostprocessorContext<VectorPostprocessorValue>;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Sacha Refshauge
 *
 */
// Qt implementation of the framework.
// Currently supports: Symbian, Blackberry, Linux

#include <QtGui/QApplication>
#include <QUrl>
#include <QDesktopWidget>
#include <QDesktopServices>

#ifdef __SYMBIAN32__
#include <AknAppUi.h>
#endif
#include "QtMain.h"

void LaunchBrowser(const char *url)
{
	QDesktopServices::openUrl(QUrl(url));
}

void SimulateGamepad(InputState *input) {
	input->pad_lstick_x = 0;
	input->pad_lstick_y = 0;
	input->pad_rstick_x = 0;
	input->pad_rstick_y = 0;

	if (input->pad_buttons & PAD_BUTTON_JOY_UP)
		input->pad_lstick_y=1;
	else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN)
		input->pad_lstick_y=-1;
	if (input->pad_buttons & PAD_BUTTON_JOY_LEFT)
		input->pad_lstick_x=-1;
	else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT)
		input->pad_lstick_x=1;
}

float CalculateDPIScale()
{
	// Sane default for Symbian, Blackberry and Meego
#ifdef __SYMBIAN32__
	return 1.3f;
#else
	return 1.2f;
#endif
}

int main(int argc, char *argv[])
{
#ifdef Q_WS_X11
	QApplication::setAttribute(Qt::AA_X11InitThreads, true);
#endif
	QApplication a(argc, argv);
	// Lock orientation to landscape on Symbian
#ifdef __SYMBIAN32__
	QT_TRAP_THROWING(dynamic_cast<CAknAppUi*>(CEikonEnv::Static()->AppUi())->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape));
#endif
	QSize res = QApplication::desktop()->screenGeometry().size();
	if (res.width() < res.height())
		res.transpose();
	pixel_xres = res.width();
	pixel_yres = res.height();

	float dpi_scale = CalculateDPIScale();
	dp_xres = (int)(pixel_xres * dpi_scale); dp_yres = (int)(pixel_yres * dpi_scale);
	net::Init();
#ifdef __SYMBIAN32__
	NativeInit(argc, (const char **)argv, "E:/PPSSPP/", "E:", "BADCOFFEE");
#elif defined(BLACKBERRY)
	NativeInit(argc, (const char **)argv, "data/", QDir::tempPath().toStdString().c_str(), "BADCOFFEE");
#else
	NativeInit(argc, (const char **)argv, "./", QDir::tempPath().toStdString().c_str(), "BADCOFFEE");
#endif

#if defined(USING_GLES2)
	MainUI w(dpi_scale);
	w.resize(pixel_xres, pixel_yres);
	w.showFullScreen();
#endif

	MainAudio *audio = new MainAudio();

	int ret = a.exec();
	delete audio;
	NativeShutdown();
	net::Shutdown();
	return ret;
}
<commit_msg>Quick fix for missing QDir<commit_after>/*
 * Copyright (c) 2012 Sacha Refshauge
 *
 */
// Qt implementation of the framework.
// Currently supports: Symbian, Blackberry, Linux

#include <QtGui/QApplication>
#include <QUrl>
#include <QDir>
#include <QDesktopWidget>
#include <QDesktopServices>

#ifdef __SYMBIAN32__
#include <AknAppUi.h>
#endif
#include "QtMain.h"

void LaunchBrowser(const char *url)
{
	QDesktopServices::openUrl(QUrl(url));
}

void SimulateGamepad(InputState *input) {
	input->pad_lstick_x = 0;
	input->pad_lstick_y = 0;
	input->pad_rstick_x = 0;
	input->pad_rstick_y = 0;

	if (input->pad_buttons & PAD_BUTTON_JOY_UP)
		input->pad_lstick_y=1;
	else if (input->pad_buttons & PAD_BUTTON_JOY_DOWN)
		input->pad_lstick_y=-1;
	if (input->pad_buttons & PAD_BUTTON_JOY_LEFT)
		input->pad_lstick_x=-1;
	else if (input->pad_buttons & PAD_BUTTON_JOY_RIGHT)
		input->pad_lstick_x=1;
}

float CalculateDPIScale()
{
	// Sane default for Symbian, Blackberry and Meego
#ifdef __SYMBIAN32__
	return 1.3f;
#else
	return 1.2f;
#endif
}

int main(int argc, char *argv[])
{
#ifdef Q_WS_X11
	QApplication::setAttribute(Qt::AA_X11InitThreads, true);
#endif
	QApplication a(argc, argv);
	// Lock orientation to landscape on Symbian
#ifdef __SYMBIAN32__
	QT_TRAP_THROWING(dynamic_cast<CAknAppUi*>(CEikonEnv::Static()->AppUi())->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape));
#endif
	QSize res = QApplication::desktop()->screenGeometry().size();
	if (res.width() < res.height())
		res.transpose();
	pixel_xres = res.width();
	pixel_yres = res.height();

	float dpi_scale = CalculateDPIScale();
	dp_xres = (int)(pixel_xres * dpi_scale); dp_yres = (int)(pixel_yres * dpi_scale);
	net::Init();
#ifdef __SYMBIAN32__
	NativeInit(argc, (const char **)argv, "E:/PPSSPP/", "E:", "BADCOFFEE");
#elif defined(BLACKBERRY)
	NativeInit(argc, (const char **)argv, "data/", QDir::tempPath().toStdString().c_str(), "BADCOFFEE");
#else
	NativeInit(argc, (const char **)argv, "./", QDir::tempPath().toStdString().c_str(), "BADCOFFEE");
#endif

#if defined(USING_GLES2)
	MainUI w(dpi_scale);
	w.resize(pixel_xres, pixel_yres);
	w.showFullScreen();
#endif

	MainAudio *audio = new MainAudio();

	int ret = a.exec();
	delete audio;
	NativeShutdown();
	net::Shutdown();
	return ret;
}
<|endoftext|>