<commit_before>#include <node.h>
#include <v8.h>
#include <string>
#include <iostream>
#include "steamworks-sdk/public/steam/steam_api.h"
#include "steamworks-sdk/public/steam/steam_gameserver.h"
#include "steamworks-sdk/public/steam/isteamremotestorage.h"

using namespace v8;
using namespace std;

struct FileIOAsync {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sFilename;
	string sContent;
	string sError;
	bool bSuccess;
};

struct CloudQuota {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	int nTotalBytes;
	int nAvailableBytes;
	bool bSuccess;
};

struct Achievement {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sAchievementId;
	bool bSuccess;
};

class Greenworks : node::ObjectWrap {
	private:

		static void steamWriteToFile(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Checking quota (in the future we may need it)
			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				writeData->sError = "Error getting Cloud quota";
				writeData->bSuccess = false;
				return;
			}

			writeData->bSuccess = pSteamRemoteStorage->FileWrite(writeData->sFilename.c_str(), writeData->sContent.c_str(), (int)strlen(writeData->sContent.c_str()));
			if (!writeData->bSuccess)
				writeData->sError = "Error writing to file. ";

			return;
		}

		static void steamReadFromFile(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Check if file exists
			if (!pSteamRemoteStorage->FileExists(readData->sFilename.c_str())) {
				readData->bSuccess = false;
				readData->sError = "File doesn't exist";
				return;
			}

			int32 nFileSize = pSteamRemoteStorage->GetFileSize(readData->sFilename.c_str());

			char *sFileContents = new char[nFileSize+1];
			int32 cubRead = pSteamRemoteStorage->FileRead( readData->sFilename.c_str(), sFileContents, nFileSize );
			sFileContents[cubRead] = 0; // null-terminate

			if (cubRead == 0 && nFileSize > 0) {
				readData->bSuccess = false;
				readData->sError = "Error loading file";
			}
			else {
				readData->bSuccess = true;
				readData->sContent = sFileContents;
			}

			delete sFileContents;
			return;
		}

		static void steamGetCloudQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				quotaData->bSuccess = false;
				return;
			}

			quotaData->bSuccess = true;
			quotaData->nTotalBytes = nTotal;
			quotaData->nAvailableBytes = nAvailable;

			return;
		}

		static void steamSetAchievement(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;
			ISteamUserStats *pSteamUserStats = SteamUserStats();

			pSteamUserStats->SetAchievement(achievementData->sAchievementId.c_str());
			achievementData->bSuccess = pSteamUserStats->StoreStats();

			return;
		}

		static void fileWrote(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (writeData->bSuccess) {
				callbackResultArgs[0] = Undefined();
				writeData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(writeData->sError.c_str());
				writeData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}

			return;
		}

		static void fileLoaded(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (readData->bSuccess) {
				callbackResultArgs[0] = String::New(readData->sContent.c_str());
				readData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(readData->sError.c_str());
				readData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void gotQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;

			Handle<Value> callbackResultArgs[2];

			if (quotaData->bSuccess) {
				callbackResultArgs[0] = Integer::New(quotaData->nTotalBytes);
				callbackResultArgs[1] = Integer::New(quotaData->nAvailableBytes);
				quotaData->successCallback->Call(Context::GetCurrent()->Global(), 2, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = Undefined();
				quotaData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void achievementStored(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;

			Handle<Value> callbackResultArgs[1];
			callbackResultArgs[0] = Undefined();

			if (achievementData->bSuccess) {
				achievementData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				achievementData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

	public:
		GreenheartGames()  {}
		~GreenheartGames() {}

		static Handle<Value> initAPI(const Arguments& args) {
			HandleScope scope;

			// Initializing Steam API
			bool bSuccess = SteamAPI_Init();

			if (bSuccess) {
				ISteamUserStats *pSteamUserStats = SteamUserStats();
				pSteamUserStats->RequestCurrentStats();
			}

			return scope.Close(Boolean::New(bSuccess));
		}

		static Handle<Value> getCloudQuota(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			Local<Function>successCallback = Local<Function>::Cast(args[0]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[1]);

			CloudQuota *quotaData = new CloudQuota;
			quotaData->successCallback  = Persistent<Function>::New(successCallback);
			quotaData->errorCallback    = Persistent<Function>::New(errorCallback);

			uv_work_t *req = new uv_work_t;
			req->data = quotaData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamGetCloudQuota, (uv_after_work_cb)gotQuota);

			return scope.Close(Undefined());
		}

		static Handle<Value> saveTextToFile(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			string sContent(*String::Utf8Value(args[1]));
			Local<Function>successCallback = Local<Function>::Cast(args[2]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[3]);

			FileIOAsync *writeData = new FileIOAsync;
			writeData->successCallback  = Persistent<Function>::New(successCallback);
			writeData->errorCallback    = Persistent<Function>::New(errorCallback);
			writeData->sFilename = sFilename;
			writeData->sContent  = sContent;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = writeData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamWriteToFile, (uv_after_work_cb)fileWrote);

			return scope.Close(Undefined());
		}

		static Handle<Value> readTextFromFile(const Arguments& args) {
			HandleScope scope;

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
			FileIOAsync *readData = new FileIOAsync;
			readData->successCallback  = Persistent<Function>::New(successCallback);
			readData->errorCallback    = Persistent<Function>::New(errorCallback);
			readData->sFilename = sFilename;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = readData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamReadFromFile, (uv_after_work_cb)fileLoaded);

			return scope.Close(Undefined());
		}

		static Handle<Value> activateAchievement(const Arguments& args) {
			HandleScope scope;

			string sAchievementId(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			Achievement *achievementData = new Achievement;
			achievementData->successCallback = Persistent<Function>::New(successCallback);
			achievementData->errorCallback   = Persistent<Function>::New(errorCallback);
			achievementData->sAchievementId  = sAchievementId;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = achievementData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamSetAchievement, (uv_after_work_cb)achievementStored);

			return scope.Close(Undefined());
		}
};

void init(Handle<Object> exports) {
	exports->Set(String::NewSymbol("initAPI"), FunctionTemplate::New(GreenheartGames::initAPI)->GetFunction());
	exports->Set(String::NewSymbol("getCloudQuota"), FunctionTemplate::New(GreenheartGames::getCloudQuota)->GetFunction());
	exports->Set(String::NewSymbol("saveTextToFile"), FunctionTemplate::New(GreenheartGames::saveTextToFile)->GetFunction());
	exports->Set(String::NewSymbol("readTextFromFile"), FunctionTemplate::New(GreenheartGames::readTextFromFile)->GetFunction());
	exports->Set(String::NewSymbol("activateAchievement"), FunctionTemplate::New(GreenheartGames::activateAchievement)->GetFunction());
}

#ifdef _WIN32
	NODE_MODULE(greenworks_win, init)
#elif __APPLE__
	NODE_MODULE(greenworks_osx, init)
#elif __linux__
	NODE_MODULE(greenworks_linux, init)
#endif
<commit_msg>corrected constructors/destructors and references<commit_after>#include <node.h>
#include <v8.h>
#include <string>
#include <iostream>
#include "steamworks-sdk/public/steam/steam_api.h"
#include "steamworks-sdk/public/steam/steam_gameserver.h"
#include "steamworks-sdk/public/steam/isteamremotestorage.h"

using namespace v8;
using namespace std;

struct FileIOAsync {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sFilename;
	string sContent;
	string sError;
	bool bSuccess;
};

struct CloudQuota {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	int nTotalBytes;
	int nAvailableBytes;
	bool bSuccess;
};

struct Achievement {
	Persistent<Function> errorCallback;
	Persistent<Function> successCallback;
	string sAchievementId;
	bool bSuccess;
};

class Greenworks : node::ObjectWrap {
	private:

		static void steamWriteToFile(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Checking quota (in the future we may need it)
			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				writeData->sError = "Error getting Cloud quota";
				writeData->bSuccess = false;
				return;
			}

			writeData->bSuccess = pSteamRemoteStorage->FileWrite(writeData->sFilename.c_str(), writeData->sContent.c_str(), (int)strlen(writeData->sContent.c_str()));
			if (!writeData->bSuccess)
				writeData->sError = "Error writing to file. ";

			return;
		}

		static void steamReadFromFile(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Check if file exists
			if (!pSteamRemoteStorage->FileExists(readData->sFilename.c_str())) {
				readData->bSuccess = false;
				readData->sError = "File doesn't exist";
				return;
			}

			int32 nFileSize = pSteamRemoteStorage->GetFileSize(readData->sFilename.c_str());

			char *sFileContents = new char[nFileSize+1];
			int32 cubRead = pSteamRemoteStorage->FileRead( readData->sFilename.c_str(), sFileContents, nFileSize );
			sFileContents[cubRead] = 0; // null-terminate

			if (cubRead == 0 && nFileSize > 0) {
				readData->bSuccess = false;
				readData->sError = "Error loading file";
			}
			else {
				readData->bSuccess = true;
				readData->sContent = sFileContents;
			}

			delete sFileContents;
			return;
		}

		static void steamGetCloudQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			int nTotal = -1, nAvailable = -1;

			if (!pSteamRemoteStorage->GetQuota(&nTotal, &nAvailable)) {
				quotaData->bSuccess = false;
				return;
			}

			quotaData->bSuccess = true;
			quotaData->nTotalBytes = nTotal;
			quotaData->nAvailableBytes = nAvailable;

			return;
		}

		static void steamSetAchievement(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;
			ISteamUserStats *pSteamUserStats = SteamUserStats();

			pSteamUserStats->SetAchievement(achievementData->sAchievementId.c_str());
			achievementData->bSuccess = pSteamUserStats->StoreStats();

			return;
		}

		static void fileWrote(uv_work_t *req) {
			FileIOAsync *writeData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (writeData->bSuccess) {
				callbackResultArgs[0] = Undefined();
				writeData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(writeData->sError.c_str());
				writeData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}

			return;
		}

		static void fileLoaded(uv_work_t *req) {
			FileIOAsync *readData = (FileIOAsync*)req->data;

			// Calling callback here
			Handle<Value> callbackResultArgs[1];

			if (readData->bSuccess) {
				callbackResultArgs[0] = String::New(readData->sContent.c_str());
				readData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = String::New(readData->sError.c_str());
				readData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void gotQuota(uv_work_t *req) {
			CloudQuota *quotaData = (CloudQuota*)req->data;

			Handle<Value> callbackResultArgs[2];

			if (quotaData->bSuccess) {
				callbackResultArgs[0] = Integer::New(quotaData->nTotalBytes);
				callbackResultArgs[1] = Integer::New(quotaData->nAvailableBytes);
				quotaData->successCallback->Call(Context::GetCurrent()->Global(), 2, callbackResultArgs);
			}
			else {
				callbackResultArgs[0] = Undefined();
				quotaData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

		static void achievementStored(uv_work_t *req) {
			Achievement *achievementData = (Achievement*)req->data;

			Handle<Value> callbackResultArgs[1];
			callbackResultArgs[0] = Undefined();

			if (achievementData->bSuccess) {
				achievementData->successCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
			else {
				achievementData->errorCallback->Call(Context::GetCurrent()->Global(), 1, callbackResultArgs);
			}
		}

	public:
		Greenworks()  {}
		~Greenworks() {}

		static Handle<Value> initAPI(const Arguments& args) {
			HandleScope scope;

			// Initializing Steam API
			bool bSuccess = SteamAPI_Init();

			if (bSuccess) {
				ISteamUserStats *pSteamUserStats = SteamUserStats();
				pSteamUserStats->RequestCurrentStats();
			}

			return scope.Close(Boolean::New(bSuccess));
		}

		static Handle<Value> getCloudQuota(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			Local<Function>successCallback = Local<Function>::Cast(args[0]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[1]);

			CloudQuota *quotaData = new CloudQuota;
			quotaData->successCallback  = Persistent<Function>::New(successCallback);
			quotaData->errorCallback    = Persistent<Function>::New(errorCallback);

			uv_work_t *req = new uv_work_t;
			req->data = quotaData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamGetCloudQuota, (uv_after_work_cb)gotQuota);

			return scope.Close(Undefined());
		}

		static Handle<Value> saveTextToFile(const Arguments& args) {
			HandleScope scope;
			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			string sContent(*String::Utf8Value(args[1]));
			Local<Function>successCallback = Local<Function>::Cast(args[2]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[3]);

			FileIOAsync *writeData = new FileIOAsync;
			writeData->successCallback  = Persistent<Function>::New(successCallback);
			writeData->errorCallback    = Persistent<Function>::New(errorCallback);
			writeData->sFilename = sFilename;
			writeData->sContent  = sContent;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = writeData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamWriteToFile, (uv_after_work_cb)fileWrote);

			return scope.Close(Undefined());
		}

		static Handle<Value> readTextFromFile(const Arguments& args) {
			HandleScope scope;

			// Convert passed string arguments directly to std::string
			string sFilename(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			ISteamRemoteStorage *pSteamRemoteStorage = SteamRemoteStorage();
			FileIOAsync *readData = new FileIOAsync;
			readData->successCallback  = Persistent<Function>::New(successCallback);
			readData->errorCallback    = Persistent<Function>::New(errorCallback);
			readData->sFilename = sFilename;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = readData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamReadFromFile, (uv_after_work_cb)fileLoaded);

			return scope.Close(Undefined());
		}

		static Handle<Value> activateAchievement(const Arguments& args) {
			HandleScope scope;

			string sAchievementId(*String::Utf8Value(args[0]));
			Local<Function>successCallback = Local<Function>::Cast(args[1]);
			Local<Function>errorCallback   = Local<Function>::Cast(args[2]);

			Achievement *achievementData = new Achievement;
			achievementData->successCallback = Persistent<Function>::New(successCallback);
			achievementData->errorCallback   = Persistent<Function>::New(errorCallback);
			achievementData->sAchievementId  = sAchievementId;

			// Preparing separate thread work call
			uv_work_t *req = new uv_work_t;
			req->data = achievementData;

			// Call separate thread work
			uv_queue_work(uv_default_loop(), req, steamSetAchievement, (uv_after_work_cb)achievementStored);

			return scope.Close(Undefined());
		}
};

void init(Handle<Object> exports) {
	exports->Set(String::NewSymbol("initAPI"), FunctionTemplate::New(Greenworks::initAPI)->GetFunction());
	exports->Set(String::NewSymbol("getCloudQuota"), FunctionTemplate::New(Greenworks::getCloudQuota)->GetFunction());
	exports->Set(String::NewSymbol("saveTextToFile"), FunctionTemplate::New(Greenworks::saveTextToFile)->GetFunction());
	exports->Set(String::NewSymbol("readTextFromFile"), FunctionTemplate::New(Greenworks::readTextFromFile)->GetFunction());
	exports->Set(String::NewSymbol("activateAchievement"), FunctionTemplate::New(Greenworks::activateAchievement)->GetFunction());
}

#ifdef _WIN32
	NODE_MODULE(greenworks_win, init)
#elif __APPLE__
	NODE_MODULE(greenworks_osx, init)
#elif __linux__
	NODE_MODULE(greenworks_linux, init)
#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/test/unit_test.hpp>

#include "tests/test-utils.hh"
#include "sstable_test.hh"

using namespace sstables;

static future<> broken_sst(sstring dir, unsigned long generation) {
    // Using an empty schema for this function, which is only about loading
    // a malformed component and checking that it fails.
    auto s = make_lw_shared(schema({}, "ks", "cf", {}, {}, {}, {}, utf8_type));
    auto sst = std::make_unique<sstable>(s, dir, generation, la, big);
    auto fut = sst->load();
    return std::move(fut).then_wrapped([sst = std::move(sst)] (future<> f) mutable {
        try {
            f.get();
            BOOST_FAIL("expecting exception");
        } catch (malformed_sstable_exception& e) {
            // ok
        }
        return make_ready_future<>();
    });
}

SEASTAR_TEST_CASE(empty_toc) {
    return broken_sst("tests/sstables/badtoc", 1);
}

SEASTAR_TEST_CASE(alien_toc) {
    return broken_sst("tests/sstables/badtoc", 2);
}

SEASTAR_TEST_CASE(truncated_toc) {
    return broken_sst("tests/sstables/badtoc", 3);
}

SEASTAR_TEST_CASE(wrong_format_toc) {
    return broken_sst("tests/sstables/badtoc", 4);
}

SEASTAR_TEST_CASE(compression_truncated) {
    return broken_sst("tests/sstables/badcompression", 1);
}

SEASTAR_TEST_CASE(compression_bytes_flipped) {
    return broken_sst("tests/sstables/badcompression", 2);
}
<commit_msg>Check the exception message.<commit_after>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/test/unit_test.hpp>

#include "tests/test-utils.hh"
#include "sstable_test.hh"

using namespace sstables;

static future<> broken_sst(sstring dir, unsigned long generation, sstring msg) {
    // Using an empty schema for this function, which is only about loading
    // a malformed component and checking that it fails.
    auto s = make_lw_shared(schema({}, "ks", "cf", {}, {}, {}, {}, utf8_type));
    auto sst = std::make_unique<sstable>(s, dir, generation, la, big);
    auto fut = sst->load();
    return std::move(fut).then_wrapped([sst = std::move(sst), msg = std::move(msg)] (future<> f) mutable {
        try {
            f.get();
            BOOST_FAIL("expecting exception");
        } catch (malformed_sstable_exception& e) {
            BOOST_REQUIRE_EQUAL(sstring(e.what()), msg);
        }
        return make_ready_future<>();
    });
}

SEASTAR_TEST_CASE(empty_toc) {
    return broken_sst("tests/sstables/badtoc", 1,
                      "Empty TOC in sstable tests/sstables/badtoc/la-1-big-TOC.txt");
}

SEASTAR_TEST_CASE(alien_toc) {
    return broken_sst("tests/sstables/badtoc", 2,
                      "tests/sstables/badtoc/la-2-big-Statistics.db: file not found");
}

SEASTAR_TEST_CASE(truncated_toc) {
    return broken_sst("tests/sstables/badtoc", 3,
                      "tests/sstables/badtoc/la-3-big-Statistics.db: file not found");
}

SEASTAR_TEST_CASE(wrong_format_toc) {
    return broken_sst("tests/sstables/badtoc", 4,
                      "tests/sstables/badtoc/la-4-big-TOC.txt: file not found");
}

SEASTAR_TEST_CASE(compression_truncated) {
    return broken_sst("tests/sstables/badcompression", 1,
                      "tests/sstables/badcompression/la-1-big-Statistics.db: file not found");
}

SEASTAR_TEST_CASE(compression_bytes_flipped) {
    return broken_sst("tests/sstables/badcompression", 2,
                      "tests/sstables/badcompression/la-2-big-Statistics.db: file not found");
}
<|endoftext|>


<commit_before>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h"
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
#include "Adafruit_MAX31856.h"

#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288

#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10

#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space

#ifdef SERIAL_EN
#define DEBUG(input)   {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif

ISR(WDT_vect) { Sleepy::watchdogEvent(); }

/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 100;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Adafruit_MAX31856 tc1 = Adafruit_MAX31856(TC1_CS);
Adafruit_MAX31856 tc2 = Adafruit_MAX31856(TC2_CS);
Adafruit_MAX31856 tc3 = Adafruit_MAX31856(TC3_CS);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 30000;
const uint16_t REC_INTERVAL = (30000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
	uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this

//Data structure for storing data locally (12 bytes)
struct Data {
	uint16_t count;
	int16_t tc1;
	int16_t tc2;
	int16_t tc3;
	int16_t brd_tmp;
	int16_t bat_v;
};

//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
	uint32_t timestamp;
	uint16_t count;
	int16_t tc1;
	int16_t tc2;
	int16_t tc3;
	int16_t brd_tmp;
	int16_t bat_v;
};
Payload thePayload;

struct Measurement {
	uint32_t time;
	int16_t tc1;
	int16_t tc2;
	int16_t tc3;
};

uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
uint32_t saved_time = 0;
uint16_t interval = 1000;

struct Mem {
	long one;
	long two;
	long three;
	long four;
	long five;
};
Mem thisMem;

void setup()
{
	#ifdef SERIAL_EN
		Serial.begin(SERIAL_BAUD);
	#endif
	randomSeed(analogRead(A4)); //set random seed
	NETWORKID += setAddress();
	radio.initialize(FREQUENCY,NODEID,NETWORKID);
	radio.setHighPower();
	radio.encrypt(null);
	radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
	DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
	pinMode(LED, OUTPUT);
	// Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
	digitalWrite(LED, HIGH); //write LED high to signal attempting connection
	while(!getTime()) { //this saves time to the struct which holds the time globally
		radio.sleep();
		DEBUGFlush();
		delay(10000);
	}
	digitalWrite(LED, LOW); //write low to signal success
	DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");

  tc1.begin(); tc2.begin(); tc3.begin();
  tc1.setThermocoupleType(MAX31856_TCTYPE_E);
  tc2.setThermocoupleType(MAX31856_TCTYPE_E);
  tc3.setThermocoupleType(MAX31856_TCTYPE_E);
	DEBUGln("--Thermocouples are engaged");

	DEBUG("--Flash Mem: ");
	flash.begin();
	uint16_t _name = flash.getChipName();
	uint32_t capacity = flash.getCapacity();
	DEBUG("W25X"); DEBUG(_name); DEBUG("**  ");
	DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
	DEBUGln("Erasing Chip!"); flash.eraseChip();
}

void loop()
{
	current_time = millis();
	if(saved_time + interval < current_time) {
		thisMem.one = random(0, 1000);
		thisMem.two = random(0, 1000);
		thisMem.three = random(0, 1000);
		thisMem.four = random(0, 1000);
		thisMem.five = random(0, 1000);
		flash.writeAnything(FLASH_ADDR, thisMem);
		Mem newMem;
		if(flash.readAnything(FLASH_ADDR, newMem)) {
			DEBUGln(newMem.one);
			DEBUGln(newMem.two);
			DEBUGln(newMem.three);
			DEBUGln(newMem.four);
			DEBUGln(newMem.five);
			DEBUGln();
			FLASH_ADDR += sizeof(thisMem);
		}
		saved_time = current_time;
	}
}

/**
 * [getTime description]
 * @return [description]
 */
bool getTime()
{
	LED_STATE = true;
	digitalWrite(LED, LED_STATE);
	//Get the current timestamp from the datalogger
	bool TIME_RECIEVED = false;
	if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
		DEBUG("time - ");
		if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
			DEBUG("snd . . ");
			HANDSHAKE_SENT = true;
		}
		else {
			DEBUGln("failed . . . no ack");
			return false; //if there is no response, returns false and exits function
		}
	}
	while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
		if (radio.receiveDone()) {
			if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
				theTimeStamp = *(TimeStamp*)radio.DATA; //save data
				DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
				DEBUG(theTimeStamp.timestamp);
				DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
				DEBUGln();
				TIME_RECIEVED = true;
				LED_STATE = false;
				digitalWrite(LED, LED_STATE);
			}
			if (radio.ACKRequested()) radio.sendACK();
		}
	}
	HANDSHAKE_SENT = false;
	return true;
}

/**
 * [Blink description]
 * @param t [description]
 */
void Blink(uint8_t t) {
	LED_STATE = !LED_STATE;
	digitalWrite(LED, LED_STATE);
	delay(t);
	LED_STATE = !LED_STATE;
	digitalWrite(LED, LED_STATE);
	delay(t);
}
/**
 * [setAddress description]
 * @return [description]
 */
uint8_t setAddress() {
	//sets network address based on which solder jumpers are closed
	uint8_t addr01, addr02, addr03;
	pinMode(N_SEL_1, INPUT_PULLUP);
	pinMode(N_SEL_2, INPUT_PULLUP);
	pinMode(N_SEL_4, INPUT_PULLUP);
	addr01 = !digitalRead(N_SEL_1);
	addr02 = !digitalRead(N_SEL_2) * 2;
	addr03 = !digitalRead(N_SEL_4) * 4;
	pinMode(N_SEL_1, OUTPUT);
	pinMode(N_SEL_2, OUTPUT);
	pinMode(N_SEL_4, OUTPUT);
	digitalWrite(N_SEL_1, HIGH);
	digitalWrite(N_SEL_2, HIGH);
	digitalWrite(N_SEL_4, HIGH);
	uint8_t addr = addr01 | addr02 | addr03;
	return addr;
}
<commit_msg>not fucked yet<commit_after>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h"
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
#include "Adafruit_MAX31856.h"

#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288

#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10

#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space

#ifdef SERIAL_EN
#define DEBUG(input)   {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif

ISR(WDT_vect) { Sleepy::watchdogEvent(); }

/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 100;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Adafruit_MAX31856 tc1 = Adafruit_MAX31856(TC1_CS);
Adafruit_MAX31856 tc2 = Adafruit_MAX31856(TC2_CS);
Adafruit_MAX31856 tc3 = Adafruit_MAX31856(TC3_CS);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 30000;
const uint16_t REC_INTERVAL = (30000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
	uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this

//Data structure for storing data locally (12 bytes)
struct Data {
	uint16_t count;
	int16_t tc1;
	int16_t tc2;
	int16_t tc3;
	int16_t brd_tmp;
	int16_t bat_v;
};

//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
	uint32_t timestamp;
	uint16_t count;
	int16_t tc1;
	int16_t tc2;
	int16_t tc3;
	int16_t brd_tmp;
	int16_t bat_v;
};
Payload thePayload;

uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
uint32_t saved_time = 0;
uint16_t interval = 1000;

void setup()
{
	#ifdef SERIAL_EN
		Serial.begin(SERIAL_BAUD);
	#endif
	randomSeed(analogRead(A4)); //set random seed
	NETWORKID += setAddress();
	radio.initialize(FREQUENCY,NODEID,NETWORKID);
	radio.setHighPower();
	radio.encrypt(null);
	radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
	DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
	pinMode(LED, OUTPUT);
	// Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
	digitalWrite(LED, HIGH); //write LED high to signal attempting connection
	while(!getTime()) { //this saves time to the struct which holds the time globally
		radio.sleep();
		DEBUGFlush();
		delay(10000);
	}
	digitalWrite(LED, LOW); //write low to signal success
	DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");

  tc1.begin(); tc2.begin(); tc3.begin();
  tc1.setThermocoupleType(MAX31856_TCTYPE_E);
  tc2.setThermocoupleType(MAX31856_TCTYPE_E);
  tc3.setThermocoupleType(MAX31856_TCTYPE_E);
	DEBUGln("--Thermocouples are engaged");

	DEBUG("--Flash Mem: ");
	flash.begin();
	uint16_t _name = flash.getChipName();
	uint32_t capacity = flash.getCapacity();
	DEBUG("W25X"); DEBUG(_name); DEBUG("**  ");
	DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
	DEBUGln("Erasing Chip!"); flash.eraseChip();
}

void loop()
{

}

/**
 * [getTime description]
 * @return [description]
 */
bool getTime()
{
	LED_STATE = true;
	digitalWrite(LED, LED_STATE);
	//Get the current timestamp from the datalogger
	bool TIME_RECIEVED = false;
	if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
		DEBUG("time - ");
		if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
			DEBUG("snd . . ");
			HANDSHAKE_SENT = true;
		}
		else {
			DEBUGln("failed . . . no ack");
			return false; //if there is no response, returns false and exits function
		}
	}
	while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
		if (radio.receiveDone()) {
			if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
				theTimeStamp = *(TimeStamp*)radio.DATA; //save data
				DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
				DEBUG(theTimeStamp.timestamp);
				DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
				DEBUGln();
				TIME_RECIEVED = true;
				LED_STATE = false;
				digitalWrite(LED, LED_STATE);
			}
			if (radio.ACKRequested()) radio.sendACK();
		}
	}
	HANDSHAKE_SENT = false;
	return true;
}

/**
 * [Blink description]
 * @param t [description]
 */
void Blink(uint8_t t) {
	LED_STATE = !LED_STATE;
	digitalWrite(LED, LED_STATE);
	delay(t);
	LED_STATE = !LED_STATE;
	digitalWrite(LED, LED_STATE);
	delay(t);
}
/**
 * [setAddress description]
 * @return [description]
 */
uint8_t setAddress() {
	//sets network address based on which solder jumpers are closed
	uint8_t addr01, addr02, addr03;
	pinMode(N_SEL_1, INPUT_PULLUP);
	pinMode(N_SEL_2, INPUT_PULLUP);
	pinMode(N_SEL_4, INPUT_PULLUP);
	addr01 = !digitalRead(N_SEL_1);
	addr02 = !digitalRead(N_SEL_2) * 2;
	addr03 = !digitalRead(N_SEL_4) * 4;
	pinMode(N_SEL_1, OUTPUT);
	pinMode(N_SEL_2, OUTPUT);
	pinMode(N_SEL_4, OUTPUT);
	digitalWrite(N_SEL_1, HIGH);
	digitalWrite(N_SEL_2, HIGH);
	digitalWrite(N_SEL_4, HIGH);
	uint8_t addr = addr01 | addr02 | addr03;
	return addr;
}
<|endoftext|>


<commit_before>#include "BAMap.h"
#include <Arduboy.h>
#include "BAGlobal.h"
#include "ABMapSprites.h"

void drawMapAtPosition(BAPlayer *player, ABPoint position, bool showShips){

  // flip for watrer animation
  bool waterAnimationStepped = arduboy.everyXFrames(30);

    for(byte mapPosY = 0; mapPosY < GAME_BOARD_SIZE_HEIGHT; mapPosY++){
      for(byte mapPosX = 0; mapPosX < GAME_BOARD_SIZE_WIDTH; mapPosX++){

        int currentMapIndex = player->playerBoard[mapPosY][mapPosX];

          //=======================================
        // If it's a ship
        if(currentMapIndex >= 0 && showShips){
           // get actual ship from player
           BAShip currentShip = player->shipAtIndex(currentMapIndex);

           ABPoint shipPosition = currentShip.position;
           shipPosition.x = shipPosition.x*8 + MENU_WIDTH + position.x;
           shipPosition.y = shipPosition.y*8 + position.y;

           if(currentShip.horizontal)
            drawHorizontalShip(shipPosition, currentShip.fullLength, WHITE);
           else
            drawVerticalShip(shipPosition, currentShip.fullLength, WHITE);
        }

        //=======================================
        // If it's a Mountain
        else if(currentMapIndex == BAMapTileTypeMountain){
          arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
        }

        //=======================================
        // If it's a water sprite
        else if(currentMapIndex == BAMapTileTypeWater1){
           arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water1, 8, 8, WHITE);

           if(waterAnimationStepped) // set to next frame
             player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater2;
        }
        else if(currentMapIndex == BAMapTileTypeWater2){
           arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water2, 8, 8, WHITE);

           if(waterAnimationStepped) // set to next frame
             player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater3;
        }
        else if(currentMapIndex == BAMapTileTypeWater3){
          arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water3, 8, 8, WHITE);

           if(waterAnimationStepped) // set to next frame
             player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater0;
        }

        //=======================================
        // animate water
        if(currentMapIndex == BAMapTileTypeWater0 && waterAnimationStepped){
          // check probability for new water
          if(random(100) < 1)
            player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater1;
        }

        //=======================================
        // If it's a destroyed ship overdraw the field
        if(currentMapIndex == BAMapTileTypeDestroyedShip){
          arduboy.fillRect(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, 8, 8, BLACK);
          arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
        }

      }
    }
}

void drawMap(BAPlayer *player, bool showShips){
  drawMapAtPosition(player, ABPointMake(0,0), showShips);
}

<commit_msg>changed map iterration<commit_after>#include "BAMap.h"
#include <Arduboy.h>
#include "BAGlobal.h"
#include "ABMapSprites.h"

void drawMapAtPosition(BAPlayer *player, ABPoint position, bool showShips){

  // flip for watrer animation
  bool waterAnimationStepped = arduboy.everyXFrames(30);

    for(int mapPosY = 0; mapPosY < GAME_BOARD_SIZE_HEIGHT; mapPosY++){
      for(int mapPosX = 0; mapPosX < GAME_BOARD_SIZE_WIDTH; mapPosX++){

        int currentMapIndex = player->playerBoard[mapPosY][mapPosX];

          //=======================================
        // If it's a ship
        if(currentMapIndex >= 0 && showShips){
           // get actual ship from player
           BAShip currentShip = player->shipAtIndex(currentMapIndex);

           ABPoint shipPosition = currentShip.position;
           shipPosition.x = shipPosition.x*8 + MENU_WIDTH + position.x;
           shipPosition.y = shipPosition.y*8 + position.y;

           if(currentShip.horizontal)
            drawHorizontalShip(shipPosition, currentShip.fullLength, WHITE);
           else
            drawVerticalShip(shipPosition, currentShip.fullLength, WHITE);
        }

        //=======================================
        // If it's a Mountain
        else if(currentMapIndex == BAMapTileTypeMountain){
          arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
        }

        //=======================================
        // If it's a water sprite
        else if(currentMapIndex == BAMapTileTypeWater1){
           arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water1, 8, 8, WHITE);

           if(waterAnimationStepped) // set to next frame
             player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater2;
        }
        else if(currentMapIndex == BAMapTileTypeWater2){
           arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water2, 8, 8, WHITE);

           if(waterAnimationStepped) // set to next frame
             player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater3;
        }
        else if(currentMapIndex == BAMapTileTypeWater3){
          arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Water3, 8, 8, WHITE);

           if(waterAnimationStepped) // set to next frame
             player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater0;
        }

        //=======================================
        // animate water
        if(currentMapIndex == BAMapTileTypeWater0 && waterAnimationStepped){
          // check probability for new water
          if(random(100) < 1)
            player->playerBoard[mapPosY][mapPosX] = BAMapTileTypeWater1;
        }

        //=======================================
        // If it's a destroyed ship overdraw the field
        if(currentMapIndex == BAMapTileTypeDestroyedShip){
          arduboy.fillRect(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, 8, 8, BLACK);
          arduboy.drawBitmap(MENU_WIDTH+mapPosX*8 + position.x, mapPosY*8 + position.y, BAMap_Sprite_Mountain, 8, 8, WHITE);
        }

      }
    }
}

void drawMap(BAPlayer *player, bool showShips){
  drawMapAtPosition(player, ABPointMake(0,0), showShips);
}

<|endoftext|>


<commit_before>//
// Created by iskakoff on 22/08/16.
//

#include <gtest/gtest.h>
#include "edlib/Hamiltonian.h"
#include "edlib/HubbardModel.h"
#include "edlib/Storage.h"
#include "edlib/EDParams.h"
#include "edlib/StaticObservables.h"
#include "edlib/GreensFunction.h"
#include "edlib/ChiLoc.h"

#ifdef USE_MPI

class HubbardModelTestEnv : public ::testing::Environment {
  protected:
  virtual void SetUp() {
    char** argv;
    int argc = 0;
    int mpiError = MPI_Init(&argc, &argv);
  }

  virtual void TearDown() {
    MPI_Finalize();
  }

  ~HubbardModelTestEnv(){};

};

::testing::Environment* const foo_env = AddGlobalTestEnvironment(new HubbardModelTestEnv);

#endif

TEST(HubbardModelTest, ReferenceTest) {
  alps::params p;
  EDLib::define_parameters(p);
  p["NSITES"]=4;
  p["NSPINS"]=2;
  p["INPUT_FILE"]="test/input/GF_Chi/input.h5";
  p["arpack.SECTOR"]=false;
  p["storage.MAX_SIZE"]=864;
  p["storage.MAX_DIM"]=36;
  p["storage.EIGENVALUES_ONLY"]=false;
  p["storage.ORBITAL_NUMBER"]=1;
  p["arpack.NEV"]=100;
  p["lanc.BETA"]=20;
  p["lanc.EMIN"]=-4.0;
  p["lanc.EMAX"]=4.0;
  p["lanc.NOMEGA"]=1000;

#ifdef USE_MPI
  typedef EDLib::SRSHubbardHamiltonian HamType;
#else
  typedef EDLib::SOCSRHubbardHamiltonian HamType;
#endif
  HamType ham(p
#ifdef USE_MPI
  , MPI_COMM_WORLD
#endif
  );

  ham.diag();

  // Compute our GFs for the reference model.
  EDLib::gf::GreensFunction < HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(p, ham,alps::gf::statistics::statistics_type::FERMIONIC);
  greensFunction.compute();
  auto G = greensFunction.G();
  EDLib::StaticObservables<HamType> so(p);
  std::map<std::string, std::vector<double>> observables = so.calculate_static_observables(ham);
  EDLib::gf::ChiLoc<HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(p, ham, alps::gf::statistics::statistics_type::BOSONIC);
  // compute average magnetic moment
  double avg = 0.0;
  for(auto x : observables[so._M_]) {
    avg += x / (2.0*observables[so._M_].size());
  }
  // compute spin susceptibility
  susc.compute<EDLib::gf::SzOperator<double>>(&avg);
  auto ChiSz = susc.G();
  // compute average occupancy moment
  avg = 0.0;
  for(auto x : observables[so._N_]) {
    avg += x / double(observables[so._N_].size());
  }
  // Compute sharge susceptibility
  susc.compute<EDLib::gf::NOperator<double>>(&avg);
  auto ChiN = susc.G();

  // Read in the reference GFs.
  // FIXME Desperate kludges. Must take the indextypes from GFs instead.
  auto G_file = G;
  std::ifstream infile("test/input/GF_Chi/gom1.dat");
  for(size_t ii = 0; ii < 200; ++ii){
   double omega, real, imag;
   infile >> omega >> real >> imag;
   for(size_t is = 0; is < ham.model().spins(); ++is){
    G_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0), alps::gf::generic_index<alps::gf::index_mesh>(is)) = std::complex<double>(real, imag);
   }
  }
  infile.close();
  auto ChiSz_file = ChiSz;
  infile.open("test/input/GF_Chi/xiats.dat");
  for(size_t ii = 0; ii < 200; ++ii){
   double omega, real, imag;
   infile >> omega >> real >> imag;
   // S_z = 0.5 M, <S_z S_z> = 0.25 <M M>
   ChiSz_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-0.25 * real, 0.0);
  }
  infile.close();
  auto ChiN_file = ChiN;
  infile.open("test/input/GF_Chi/xiatd.dat");
  for(size_t ii = 0; ii < 200; ++ii){
   double omega, real, imag;
   infile >> omega >> real >> imag;
   ChiN_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-real, 0.0);
  }
  infile.close();

  // Subtract the reference GF from our result, the norm() is then the largest diff.
  G -= G_file;
  ASSERT_NEAR(G.norm(), 0.0, 1e-10);
  ChiSz -= ChiSz_file;
  ASSERT_NEAR(ChiSz.norm(), 0.0, 1e-9);
  ChiN -= ChiN_file;
  ASSERT_NEAR(ChiN.norm(), 0.0, 1e-9);

}
<commit_msg>Fix Lanczos_Test<commit_after>//
// Created by iskakoff on 22/08/16.
//

#include <gtest/gtest.h>
#include "edlib/Hamiltonian.h"
#include "edlib/HubbardModel.h"
#include "edlib/Storage.h"
#include "edlib/EDParams.h"
#include "edlib/StaticObservables.h"
#include "edlib/GreensFunction.h"
#include "edlib/ChiLoc.h"

#ifdef USE_MPI

class HubbardModelTestEnv : public ::testing::Environment {
  protected:
  virtual void SetUp() {
    char** argv;
    int argc = 0;
    int mpiError = MPI_Init(&argc, &argv);
  }

  virtual void TearDown() {
    MPI_Finalize();
  }

  ~HubbardModelTestEnv(){};

};

::testing::Environment* const foo_env = AddGlobalTestEnvironment(new HubbardModelTestEnv);

#endif

TEST(HubbardModelTest, ReferenceTest) {
  alps::params p;
  EDLib::define_parameters(p);
  p["NSITES"]=4;
  p["NSPINS"]=2;
  p["INPUT_FILE"]="test/input/GF_Chi/input.h5";
  p["arpack.SECTOR"]=false;
  p["storage.MAX_SIZE"]=864;
  p["storage.MAX_DIM"]=36;
  p["storage.EIGENVALUES_ONLY"]=0;
  p["storage.ORBITAL_NUMBER"]=1;
  p["arpack.NEV"]=100;
  p["lanc.BETA"]=20;
  p["lanc.EMIN"]=-4.0;
  p["lanc.EMAX"]=4.0;
  p["lanc.NOMEGA"]=1000;

#ifdef USE_MPI
  typedef EDLib::SRSHubbardHamiltonian HamType;
#else
  typedef EDLib::SOCSRHubbardHamiltonian HamType;
#endif
  HamType ham(p
#ifdef USE_MPI
  , MPI_COMM_WORLD
#endif
  );

  ham.diag();

  // Compute our GFs for the reference model.
  EDLib::gf::GreensFunction < HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(p, ham,alps::gf::statistics::statistics_type::FERMIONIC);
  greensFunction.compute();
  auto G = greensFunction.G();
  EDLib::StaticObservables<HamType> so(p);
  std::map<std::string, std::vector<double>> observables = so.calculate_static_observables(ham);
  EDLib::gf::ChiLoc<HamType, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(p, ham, alps::gf::statistics::statistics_type::BOSONIC);
  // compute average magnetic moment
  double avg = 0.0;
  for(auto x : observables[so._M_]) {
    avg += x / (2.0*observables[so._M_].size());
  }
  // compute spin susceptibility
  susc.compute<EDLib::gf::SzOperator<double>>(&avg);
  auto ChiSz = susc.G();
  // compute average occupancy moment
  avg = 0.0;
  for(auto x : observables[so._N_]) {
    avg += x / double(observables[so._N_].size());
  }
  // Compute sharge susceptibility
  susc.compute<EDLib::gf::NOperator<double>>(&avg);
  auto ChiN = susc.G();

  // Read in the reference GFs.
  // FIXME Desperate kludges. Must take the indextypes from GFs instead.
  auto G_file = G;
  std::ifstream infile("test/input/GF_Chi/gom1.dat");
  for(size_t ii = 0; ii < 200; ++ii){
   double omega, real, imag;
   infile >> omega >> real >> imag;
   for(size_t is = 0; is < ham.model().spins(); ++is){
    G_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0), alps::gf::generic_index<alps::gf::index_mesh>(is)) = std::complex<double>(real, imag);
   }
  }
  infile.close();
  auto ChiSz_file = ChiSz;
  infile.open("test/input/GF_Chi/xiats.dat");
  for(size_t ii = 0; ii < 200; ++ii){
   double omega, real, imag;
   infile >> omega >> real >> imag;
   // S_z = 0.5 M, <S_z S_z> = 0.25 <M M>
   ChiSz_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-0.25 * real, 0.0);
  }
  infile.close();
  auto ChiN_file = ChiN;
  infile.open("test/input/GF_Chi/xiatd.dat");
  for(size_t ii = 0; ii < 200; ++ii){
   double omega, real, imag;
   infile >> omega >> real >> imag;
   ChiN_file(alps::gf::generic_index<alps::gf::matsubara_mesh<alps::gf::mesh::POSITIVE_ONLY>>(ii), alps::gf::generic_index<alps::gf::index_mesh>(0)) = std::complex<double>(-real, 0.0);
  }
  infile.close();

  // Subtract the reference GF from our result, the norm() is then the largest diff.
  G -= G_file;
  ASSERT_NEAR(G.norm(), 0.0, 1e-10);
  ChiSz -= ChiSz_file;
  ASSERT_NEAR(ChiSz.norm(), 0.0, 1e-9);
  ChiN -= ChiN_file;
  ASSERT_NEAR(ChiN.norm(), 0.0, 1e-9);

}
<|endoftext|>


<commit_before>#pragma once

#include <unordered_map>

namespace AGE
{
	struct RenderPainter;

	struct RenderPipeline
	{
		std::unordered_map<size_t, RenderPainter> keys;
	};

}<commit_msg>culling old file removed<commit_after><|endoftext|>


<commit_before>/*******************************************************************************
* Copyright (c) 2016, ROBOTIS CO., LTD.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
*   list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
*   this list of conditions and the following disclaimer in the documentation
*   and/or other materials provided with the distribution.
*
* * Neither the name of ROBOTIS nor the names of its
*   contributors may be used to endorse or promote products derived from
*   this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*******************************************************************************/

/* Author: Taehoon Lim (Darby) */

#include "dynamixel_workbench_controllers/velocity_control.h"

using namespace velocity_control;

VelocityControl::VelocityControl()
    :node_handle_(""),
     node_handle_priv_("~")
{
  if (loadDynamixel())
  {
    checkLoadDynamixel();
  }
  else
  {
    ROS_ERROR("Cant' Load Dynamixel, Please check Parameter");
  }

  multi_driver_->initSyncWrite();

  writeValue_ = new WriteValue;

  writeValue_->torque.push_back(true);
  writeValue_->torque.push_back(true);

  multi_driver_->syncWriteTorque(writeValue_->torque);

  initDynamixelStatePublisher();
  initDynamixelInfoServer();
}

VelocityControl::~VelocityControl()
{
  writeValue_->torque.clear();
  writeValue_->torque.push_back(false);
  writeValue_->torque.push_back(false);
  multi_driver_->syncWriteTorque(writeValue_->torque);

  ros::shutdown();
}

bool VelocityControl::loadDynamixel()
{
  bool ret = false;

  dynamixel_driver::DynamixelInfo *left_info = new dynamixel_driver::DynamixelInfo;

  left_info->lode_info.device_name      = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
  left_info->lode_info.baud_rate        = node_handle_.param<int>("baud_rate", 57600);
  left_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);

  left_info->model_id                   = node_handle_.param<int>("left_id", 1);

  dynamixel_info_.push_back(left_info);

  dynamixel_driver::DynamixelInfo *right_info = new dynamixel_driver::DynamixelInfo;

  right_info->lode_info.device_name      = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
  right_info->lode_info.baud_rate        = node_handle_.param<int>("baud_rate", 57600);
  right_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);

  right_info->model_id                   = node_handle_.param<int>("right_id", 1);

  dynamixel_info_.push_back(right_info);

  multi_driver_ = new dynamixel_multi_driver::DynamixelMultiDriver(dynamixel_info_[MOTOR]->lode_info.device_name,
                                                                   dynamixel_info_[MOTOR]->lode_info.baud_rate,
                                                                   dynamixel_info_[MOTOR]->lode_info.protocol_version);

 ret =  multi_driver_->loadDynamixel(dynamixel_info_);

 return ret;
}

bool VelocityControl::setTorque(bool onoff)
{
  writeValue_->torque.clear();
  writeValue_->torque.push_back(onoff);
  writeValue_->torque.push_back(onoff);

  if (!multi_driver_->syncWriteTorque(writeValue_->torque))
  {
    ROS_ERROR("SyncWrite Torque Failed!");
    return false;
  }

  return true;
}

bool VelocityControl::setVelocity(int32_t left_vel, int32_t right_vel)
{
  writeValue_->vel.clear();
  writeValue_->vel.push_back(left_vel);
  writeValue_->vel.push_back(right_vel);

  if (!multi_driver_->syncWriteVelocity(writeValue_->vel))
  {
    ROS_ERROR("SyncWrite Velocity Failed!");
    return false;
  }

  return true;
}

bool VelocityControl::setMovingSpeed(uint16_t left_spd, uint16_t right_spd)
{
  writeValue_->spd.clear();
  writeValue_->spd.push_back(left_spd);
  writeValue_->spd.push_back(right_spd);

  if (!multi_driver_->syncWriteMovingSpeed(writeValue_->spd))
  {
    ROS_ERROR("SyncWrite Moving Speed Failed!");
    return false;
  }

  return true;
}

bool VelocityControl::checkLoadDynamixel()
{
  ROS_INFO("-----------------------------------------------------------------------");
  ROS_INFO("  dynamixel_workbench controller; velocity control example             ");
  ROS_INFO("-----------------------------------------------------------------------");
  ROS_INFO("PAN MOTOR INFO");
  ROS_INFO("ID    : %d", dynamixel_info_[LEFT]->model_id);
  ROS_INFO("MODEL : %s", dynamixel_info_[LEFT]->model_name.c_str());
  ROS_INFO(" ");
  ROS_INFO("TILT MOTOR INFO");
  ROS_INFO("ID    : %d", dynamixel_info_[RIGHT]->model_id);
  ROS_INFO("MODEL : %s", dynamixel_info_[RIGHT]->model_name.c_str());
  ROS_INFO("-----------------------------------------------------------------------");
}

bool VelocityControl::initDynamixelStatePublisher()
{
  dynamixel_state_list_pub_ = node_handle_.advertise<dynamixel_workbench_msgs::DynamixelStateList>("/velocity_control/dynamixel_state", 10);
}

bool VelocityControl::initDynamixelInfoServer()
{
  wheel_command_server = node_handle_.advertiseService("/wheel_command", &VelocityControl::wheelCommandMsgCallback, this);
}

bool VelocityControl::readDynamixelState()
{
  multi_driver_->readMultiRegister("torque_enable");

  multi_driver_->readMultiRegister("present_position");

  multi_driver_->readMultiRegister("goal_position");
  multi_driver_->readMultiRegister("moving");

  if (multi_driver_->getProtocolVersion() == 2.0)
  {
    if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
    {
      multi_driver_->readMultiRegister("goal_current");

      multi_driver_->readMultiRegister("present_current");
    }
    multi_driver_->readMultiRegister("goal_velocity");
    multi_driver_->readMultiRegister("present_velocity");
  }
  else
  {
    multi_driver_->readMultiRegister("moving_speed");
    multi_driver_->readMultiRegister("present_speed");
  }
}

bool VelocityControl::dynamixelStatePublish()
{
  readDynamixelState();

  dynamixel_workbench_msgs::DynamixelState     dynamixel_state[multi_driver_->multi_dynamixel_.size()];
  dynamixel_workbench_msgs::DynamixelStateList dynamixel_state_list;

  for (std::vector<dynamixel_tool::DynamixelTool *>::size_type num = 0; num < multi_driver_->multi_dynamixel_.size(); ++num)
  {
    dynamixel_state[num].model_name          = multi_driver_->multi_dynamixel_[num]->model_name_;
    dynamixel_state[num].id                  = multi_driver_->multi_dynamixel_[num]->id_;
    dynamixel_state[num].torque_enable       = multi_driver_->read_value_["torque_enable"]      ->at(num);
    dynamixel_state[num].present_position    = multi_driver_->read_value_["present_position"]   ->at(num);
    dynamixel_state[num].goal_position       = multi_driver_->read_value_["goal_position"]      ->at(num);
    dynamixel_state[num].moving              = multi_driver_->read_value_["moving"]             ->at(num);

    if (multi_driver_->getProtocolVersion() == 2.0)
    {
      if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
      {
        dynamixel_state[num].goal_current    = multi_driver_->read_value_["goal_current"]   ->at(num);
        dynamixel_state[num].present_current = multi_driver_->read_value_["present_current"]->at(num);
      }
      dynamixel_state[num].goal_velocity    = multi_driver_->read_value_["goal_velocity"]->at(num);
      dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_velocity"]->at(num);
    }
    else
    {
      dynamixel_state[num].goal_velocity    = multi_driver_->read_value_["moving_speed"]->at(num);
      dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_speed"]->at(num);
    }

    dynamixel_state_list.dynamixel_state.push_back(dynamixel_state[num]);
  }
  dynamixel_state_list_pub_.publish(dynamixel_state_list);

}

int32_t VelocityControl::convertVelocity2Value(float velocity)
{
  return (int32_t) (velocity * multi_driver_->multi_dynamixel_[MOTOR]->velocity_to_value_ratio_);
}

bool VelocityControl::controlLoop()
{
  dynamixelStatePublish();
}

bool VelocityControl::wheelCommandMsgCallback(dynamixel_workbench_msgs::WheelCommand::Request &req,
                                              dynamixel_workbench_msgs::WheelCommand::Response &res)
{
  sleep(0.01);

  static float right_vel = 0.0;
  static float left_vel  = 0.0;

  if (req.right_vel == 0.0 && req.left_vel == 0.0)
  {
    right_vel = 0.0;
    left_vel  = 0.0;
  }
  else
  {
    right_vel += req.right_vel;
    left_vel  += req.left_vel;
  }

  if (multi_driver_->getProtocolVersion() == 2.0)
  {
    setVelocity(convertVelocity2Value(left_vel), convertVelocity2Value(right_vel));
  }
  else
  {
    if (right_vel < 0.0 && left_vel < 0.0)
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel * (-1))));
    }
    else if (right_vel < 0.0 && left_vel > 0.0)
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) * (-1));
    }
    else if (right_vel > 0.0 && left_vel < 0.0)
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
    }
    else
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
    }
  }

  res.right_vel = right_vel;
  res.left_vel  = left_vel;
}

int main(int argc, char **argv)
{
  // Init ROS node
  ros::init(argc, argv, "velocity_control");
  VelocityControl vel_ctrl;

  ros::Rate loop_rate(250);

  while (ros::ok())
  {
    vel_ctrl.controlLoop();
    ros::spinOnce();
    loop_rate.sleep();
  }

  return 0;
}
<commit_msg>add pro condition<commit_after>/*******************************************************************************
* Copyright (c) 2016, ROBOTIS CO., LTD.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
*   list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
*   this list of conditions and the following disclaimer in the documentation
*   and/or other materials provided with the distribution.
*
* * Neither the name of ROBOTIS nor the names of its
*   contributors may be used to endorse or promote products derived from
*   this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*******************************************************************************/

/* Author: Taehoon Lim (Darby) */

#include "dynamixel_workbench_controllers/velocity_control.h"

using namespace velocity_control;

VelocityControl::VelocityControl()
    :node_handle_(""),
     node_handle_priv_("~")
{
  if (loadDynamixel())
  {
    checkLoadDynamixel();
  }
  else
  {
    ROS_ERROR("Cant' Load Dynamixel, Please check Parameter");
  }

  multi_driver_->initSyncWrite();

  writeValue_ = new WriteValue;

  writeValue_->torque.push_back(true);
  writeValue_->torque.push_back(true);

  multi_driver_->syncWriteTorque(writeValue_->torque);

  initDynamixelStatePublisher();
  initDynamixelInfoServer();
}

VelocityControl::~VelocityControl()
{
  writeValue_->torque.clear();
  writeValue_->torque.push_back(false);
  writeValue_->torque.push_back(false);
  multi_driver_->syncWriteTorque(writeValue_->torque);

  ros::shutdown();
}

bool VelocityControl::loadDynamixel()
{
  bool ret = false;

  dynamixel_driver::DynamixelInfo *left_info = new dynamixel_driver::DynamixelInfo;

  left_info->lode_info.device_name      = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
  left_info->lode_info.baud_rate        = node_handle_.param<int>("baud_rate", 57600);
  left_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);

  left_info->model_id                   = node_handle_.param<int>("left_id", 1);

  dynamixel_info_.push_back(left_info);

  dynamixel_driver::DynamixelInfo *right_info = new dynamixel_driver::DynamixelInfo;

  right_info->lode_info.device_name      = node_handle_.param<std::string>("device_name", "/dev/ttyUSB0");
  right_info->lode_info.baud_rate        = node_handle_.param<int>("baud_rate", 57600);
  right_info->lode_info.protocol_version = node_handle_.param<float>("protocol_version", 2.0);

  right_info->model_id                   = node_handle_.param<int>("right_id", 1);

  dynamixel_info_.push_back(right_info);

  multi_driver_ = new dynamixel_multi_driver::DynamixelMultiDriver(dynamixel_info_[MOTOR]->lode_info.device_name,
                                                                   dynamixel_info_[MOTOR]->lode_info.baud_rate,
                                                                   dynamixel_info_[MOTOR]->lode_info.protocol_version);

 ret =  multi_driver_->loadDynamixel(dynamixel_info_);

 return ret;
}

bool VelocityControl::setTorque(bool onoff)
{
  writeValue_->torque.clear();
  writeValue_->torque.push_back(onoff);
  writeValue_->torque.push_back(onoff);

  if (!multi_driver_->syncWriteTorque(writeValue_->torque))
  {
    ROS_ERROR("SyncWrite Torque Failed!");
    return false;
  }

  return true;
}

bool VelocityControl::setVelocity(int32_t left_vel, int32_t right_vel)
{
  writeValue_->vel.clear();
  writeValue_->vel.push_back(left_vel);
  writeValue_->vel.push_back(right_vel);

  if (!multi_driver_->syncWriteVelocity(writeValue_->vel))
  {
    ROS_ERROR("SyncWrite Velocity Failed!");
    return false;
  }

  return true;
}

bool VelocityControl::setMovingSpeed(uint16_t left_spd, uint16_t right_spd)
{
  writeValue_->spd.clear();
  writeValue_->spd.push_back(left_spd);
  writeValue_->spd.push_back(right_spd);

  if (!multi_driver_->syncWriteMovingSpeed(writeValue_->spd))
  {
    ROS_ERROR("SyncWrite Moving Speed Failed!");
    return false;
  }

  return true;
}

bool VelocityControl::checkLoadDynamixel()
{
  ROS_INFO("-----------------------------------------------------------------------");
  ROS_INFO("  dynamixel_workbench controller; velocity control example             ");
  ROS_INFO("-----------------------------------------------------------------------");
  ROS_INFO("PAN MOTOR INFO");
  ROS_INFO("ID    : %d", dynamixel_info_[LEFT]->model_id);
  ROS_INFO("MODEL : %s", dynamixel_info_[LEFT]->model_name.c_str());
  ROS_INFO(" ");
  ROS_INFO("TILT MOTOR INFO");
  ROS_INFO("ID    : %d", dynamixel_info_[RIGHT]->model_id);
  ROS_INFO("MODEL : %s", dynamixel_info_[RIGHT]->model_name.c_str());
  ROS_INFO("-----------------------------------------------------------------------");
}

bool VelocityControl::initDynamixelStatePublisher()
{
  dynamixel_state_list_pub_ = node_handle_.advertise<dynamixel_workbench_msgs::DynamixelStateList>("/velocity_control/dynamixel_state", 10);
}

bool VelocityControl::initDynamixelInfoServer()
{
  wheel_command_server = node_handle_.advertiseService("/wheel_command", &VelocityControl::wheelCommandMsgCallback, this);
}

bool VelocityControl::readDynamixelState()
{
  multi_driver_->readMultiRegister("torque_enable");

  multi_driver_->readMultiRegister("present_position");

  multi_driver_->readMultiRegister("goal_position");
  multi_driver_->readMultiRegister("moving");

  if (multi_driver_->getProtocolVersion() == 2.0)
  {
    if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
    {
      multi_driver_->readMultiRegister("goal_current");

      multi_driver_->readMultiRegister("present_current");
    }
    multi_driver_->readMultiRegister("goal_velocity");
    multi_driver_->readMultiRegister("present_velocity");
  }
  else
  {
    multi_driver_->readMultiRegister("moving_speed");
    multi_driver_->readMultiRegister("present_speed");
  }
}

bool VelocityControl::dynamixelStatePublish()
{
  readDynamixelState();

  dynamixel_workbench_msgs::DynamixelState     dynamixel_state[multi_driver_->multi_dynamixel_.size()];
  dynamixel_workbench_msgs::DynamixelStateList dynamixel_state_list;

  for (std::vector<dynamixel_tool::DynamixelTool *>::size_type num = 0; num < multi_driver_->multi_dynamixel_.size(); ++num)
  {
    dynamixel_state[num].model_name          = multi_driver_->multi_dynamixel_[num]->model_name_;
    dynamixel_state[num].id                  = multi_driver_->multi_dynamixel_[num]->id_;
    dynamixel_state[num].torque_enable       = multi_driver_->read_value_["torque_enable"]      ->at(num);
    dynamixel_state[num].present_position    = multi_driver_->read_value_["present_position"]   ->at(num);
    dynamixel_state[num].goal_position       = multi_driver_->read_value_["goal_position"]      ->at(num);
    dynamixel_state[num].moving              = multi_driver_->read_value_["moving"]             ->at(num);

    if (multi_driver_->getProtocolVersion() == 2.0)
    {
      if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("XM") != std::string::npos)
      {
        dynamixel_state[num].goal_current    = multi_driver_->read_value_["goal_current"]   ->at(num);
        dynamixel_state[num].present_current = multi_driver_->read_value_["present_current"]->at(num);
      }
      dynamixel_state[num].goal_velocity    = multi_driver_->read_value_["goal_velocity"]->at(num);
      dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_velocity"]->at(num);
    }
    else
    {
      dynamixel_state[num].goal_velocity    = multi_driver_->read_value_["moving_speed"]->at(num);
      dynamixel_state[num].present_velocity = multi_driver_->read_value_["present_speed"]->at(num);
    }

    dynamixel_state_list.dynamixel_state.push_back(dynamixel_state[num]);
  }
  dynamixel_state_list_pub_.publish(dynamixel_state_list);

}

int32_t VelocityControl::convertVelocity2Value(float velocity)
{
  return (int32_t) (velocity * multi_driver_->multi_dynamixel_[MOTOR]->velocity_to_value_ratio_);
}

bool VelocityControl::controlLoop()
{
  dynamixelStatePublish();
}

bool VelocityControl::wheelCommandMsgCallback(dynamixel_workbench_msgs::WheelCommand::Request &req,
                                              dynamixel_workbench_msgs::WheelCommand::Response &res)
{
  sleep(0.01);

  static float right_vel = 0.0;
  static float left_vel  = 0.0;

  if (req.right_vel == 0.0 && req.left_vel == 0.0)
  {
    right_vel = 0.0;
    left_vel  = 0.0;
  }
  else
  {
    right_vel += req.right_vel;
    left_vel  += req.left_vel;
  }

  if (multi_driver_->getProtocolVersion() == 2.0)
  {
    if (multi_driver_->multi_dynamixel_[MOTOR]->model_name_.find("PRO") != std::string::npos)
      setVelocity(convertVelocity2Value(left_vel), convertVelocity2Value(-right_vel));
    else
      setVelocity(convertVelocity2Value(left_vel), convertVelocity2Value(right_vel));
  }
  else
  {
    if (right_vel < 0.0 && left_vel < 0.0)
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel * (-1))));
    }
    else if (right_vel < 0.0 && left_vel > 0.0)
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) * (-1));
    }
    else if (right_vel > 0.0 && left_vel < 0.0)
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel * (-1))) + 1024, (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
    }
    else
    {
      setMovingSpeed((uint16_t)(convertVelocity2Value(left_vel)), (uint16_t)(convertVelocity2Value(right_vel)) + 1024);
    }
  }

  res.right_vel = right_vel;
  res.left_vel  = left_vel;
}

int main(int argc, char **argv)
{
  // Init ROS node
  ros::init(argc, argv, "velocity_control");
  VelocityControl vel_ctrl;

  ros::Rate loop_rate(250);

  while (ros::ok())
  {
    vel_ctrl.controlLoop();
    ros::spinOnce();
    loop_rate.sleep();
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Add gmock to main fil -User Stroy #8<commit_after>#include <gtest/gtest.h>
#include <gmock/gmock.h>
int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  ::testing::InitGoogleMock(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>// 031. Next Permutation
/**
 * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
 *
 * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
 *
 * The replacement must be in-place, do not allocate extra memory.
 *
 * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
 * 1,2,3  1,3,2
 * 3,2,1  1,2,3
 * 1,1,5  1,5,1
 *
 * Tags: Array
 *
 * Similar Problems: (M) Permutations (M) Permutations II (M) Permutation Sequence (M) Palindrome Permutation II
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <vector>
#include <iostream>

using namespace std;

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        if (n < 2)
        {
            return;
        }

        // start from the last element, search for the first pair in ascending order
        int i = n - 1;
        while ((i > 0) && (nums[i - 1] >= nums[i]))
        {
            i--;
        }

        // if found, start from the last element, search for the first element that is larger
        if (i != 0)
        {
            int j = n - 1;
            while ((j >= i) && (nums[i - 1] >= nums[j]))
            {
                j--;
            }
            // swap these two elements
            swap(nums[i - 1], nums[j]);
        }

        // reverse the rest of the array
        reverse(nums.begin() + i, nums.end());
        return;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    nums.push_back(1);
    nums.push_back(6);
    nums.push_back(6);
    nums.push_back(3);
    cout << "Current Permutation: ";
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << " ";
    }
    cout << endl;

    Solution mySolution;
    mySolution.nextPermutation(nums);
    cout << "Next Permutation: ";
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

<commit_msg>Update 031_Next_Permutation.cpp<commit_after>// 031. Next Permutation
/**
 * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
 *
 * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
 *
 * The replacement must be in-place, do not allocate extra memory.
 *
 * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
 * 1,2,3 -> 1,3,2
 * 3,2,1 -> 1,2,3
 * 1,1,5 -> 1,5,1
 *
 * Tags: Array
 *
 * Similar Problems: (M) Permutations (M) Permutations II (M) Permutation Sequence (M) Palindrome Permutation II
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <vector>
#include <iostream>

using namespace std;

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        if (n < 2)
        {
            return;
        }

        // start from the last element, search for the first pair in ascending order
        int i = n - 1;
        while ((i > 0) && (nums[i - 1] >= nums[i]))
        {
            i--;
        }

        // if found, start from the last element, search for the first element that is larger
        if (i != 0)
        {
            int j = n - 1;
            while ((j >= i) && (nums[i - 1] >= nums[j]))
            {
                j--;
            }
            // swap these two elements
            swap(nums[i - 1], nums[j]);
        }

        // reverse the rest of the array
        reverse(nums.begin() + i, nums.end());
        return;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    nums.push_back(1);
    nums.push_back(6);
    nums.push_back(6);
    nums.push_back(3);
    cout << "Current Permutation: ";
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << " ";
    }
    cout << endl;

    Solution mySolution;
    mySolution.nextPermutation(nums);
    cout << "Next Permutation: ";
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

<|endoftext|>