text stringlengths 54 60.6k |
|---|
<commit_before>/*
Copyright 2011 StormMQ Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <TestHarness.h>
#include "AmqpTypes/AmqpTypesTestSupport.h"
#include "AmqpTypes/AmqpMultiple.h"
SUITE(AmqpTypes)
{
class AmqpMultiplesFixture : public AmqpTypesFixture
{
public:
AmqpMultiplesFixture();
~AmqpMultiplesFixture();
public:
amqp_multiple_symbol_t multiple_ref;
amqp_multiple_symbol_t *multiple;
};
AmqpMultiplesFixture::AmqpMultiplesFixture() : multiple(0)
{
memset(&multiple_ref, '\0', sizeof(amqp_multiple_symbol_t));
}
AmqpMultiplesFixture::~AmqpMultiplesFixture()
{
amqp_multiple_symbol_cleanup(context, &multiple_ref);
amqp_multiple_symbol_cleanup(context, multiple);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_one_value)
{
test_data::multiple_symbol_one_value.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_variable(type));
CHECK(amqp_type_is_symbol(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(1, multiple->size);
amqp_symbol_t *symbol;
symbol = amqp_multiple_symbol_get(multiple, 0);
CHECK(amqp_symbol_compare_with_cstr(symbol, "PLAIN") == 0);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(1, multiple_ref.size);
symbol = amqp_multiple_symbol_get(&multiple_ref, 0);
CHECK(amqp_symbol_compare_with_cstr(symbol, "PLAIN") == 0);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_total_length)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
CHECK_EQUAL(11, amqp_multiple_symbol_total_length(multiple));
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_to_string)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
uint8_t buffer[512];
amqp_multiple_symbol_to_char_bytes(multiple, ", ", buffer, sizeof(buffer));
CHECK_EQUAL("PLAIN, Foo, Fum", (char *) buffer);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_to_string_with_small_buffer)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
uint8_t buffer[5];
amqp_multiple_symbol_to_char_bytes(multiple, ", ", buffer, sizeof(buffer));
CHECK_EQUAL("PLAI", (char *) buffer);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_empty_array)
{
test_data::empty_array_of_symbols.transfer_to(buffer);
type = amqp_decode(context, buffer);
ASSERT(type);
CHECK(amqp_type_is_array(type));
CHECK_EQUAL(0U, type->value.array.count);
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(0, multiple->size);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(0, multiple_ref.size);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_null)
{
test_data::multiple_symbol_null.transfer_to(buffer);
type = amqp_decode(context, buffer);
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(0, multiple->size);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(0, multiple_ref.size);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_many_values)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
// TODO - deal with case where get returns null (compare should return false)
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(multiple, 0), "PLAIN") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(multiple, 1), "Foo") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(multiple, 2), "Fum") == 0);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(3, multiple_ref.size);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(&multiple_ref, 0), "PLAIN") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(&multiple_ref, 1), "Foo") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(&multiple_ref, 2), "Fum") == 0);
}
}
<commit_msg>Add check to decode multiple symbol from zero length array.<commit_after>/*
Copyright 2011 StormMQ Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <TestHarness.h>
#include "AmqpTypes/AmqpTypesTestSupport.h"
#include "AmqpTypes/AmqpMultiple.h"
SUITE(AmqpTypes)
{
class AmqpMultiplesFixture : public AmqpTypesFixture
{
public:
AmqpMultiplesFixture();
~AmqpMultiplesFixture();
public:
amqp_multiple_symbol_t multiple_ref;
amqp_multiple_symbol_t *multiple;
};
AmqpMultiplesFixture::AmqpMultiplesFixture() : multiple(0)
{
memset(&multiple_ref, '\0', sizeof(amqp_multiple_symbol_t));
}
AmqpMultiplesFixture::~AmqpMultiplesFixture()
{
amqp_multiple_symbol_cleanup(context, &multiple_ref);
amqp_multiple_symbol_cleanup(context, multiple);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_one_value)
{
test_data::multiple_symbol_one_value.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_variable(type));
CHECK(amqp_type_is_symbol(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(1, multiple->size);
amqp_symbol_t *symbol;
symbol = amqp_multiple_symbol_get(multiple, 0);
CHECK(amqp_symbol_compare_with_cstr(symbol, "PLAIN") == 0);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(1, multiple_ref.size);
symbol = amqp_multiple_symbol_get(&multiple_ref, 0);
CHECK(amqp_symbol_compare_with_cstr(symbol, "PLAIN") == 0);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_total_length)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
CHECK_EQUAL(11, amqp_multiple_symbol_total_length(multiple));
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_to_string)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
uint8_t buffer[512];
amqp_multiple_symbol_to_char_bytes(multiple, ", ", buffer, sizeof(buffer));
CHECK_EQUAL("PLAIN, Foo, Fum", (char *) buffer);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_to_string_with_small_buffer)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
uint8_t buffer[5];
amqp_multiple_symbol_to_char_bytes(multiple, ", ", buffer, sizeof(buffer));
CHECK_EQUAL("PLAI", (char *) buffer);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_empty_array)
{
test_data::empty_array_of_symbols.transfer_to(buffer);
type = amqp_decode(context, buffer);
ASSERT(type);
CHECK(amqp_type_is_array(type));
CHECK_EQUAL(0U, type->value.array.count);
CHECK(amqp_type_is_symbol(amqp_type_array_type(type)));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(0, multiple->size);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(0, multiple_ref.size);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_null)
{
test_data::multiple_symbol_null.transfer_to(buffer);
type = amqp_decode(context, buffer);
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(0, multiple->size);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(0, multiple_ref.size);
}
TEST_FIXTURE(AmqpMultiplesFixture, multiple_symbol_many_values)
{
test_data::multiple_symbol_many_values.transfer_to(buffer);
type = amqp_decode(context, buffer);
CHECK(amqp_type_is_array(type));
multiple = amqp_multiple_symbol_create(context, type);
CHECK_EQUAL(3, multiple->size);
// TODO - deal with case where get returns null (compare should return false)
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(multiple, 0), "PLAIN") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(multiple, 1), "Foo") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(multiple, 2), "Fum") == 0);
int rc = amqp_multiple_symbol_initialize(context, &multiple_ref, type);
ASSERT(rc);
CHECK_EQUAL(3, multiple_ref.size);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(&multiple_ref, 0), "PLAIN") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(&multiple_ref, 1), "Foo") == 0);
CHECK(amqp_symbol_compare_with_cstr(amqp_multiple_symbol_get(&multiple_ref, 2), "Fum") == 0);
}
}
<|endoftext|> |
<commit_before>
#include <climits>
#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <sstream>
#include "Poco/Util/ServerApplication.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;
POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")
IndigoRequestHandler::IndigoRequestHandler()
{
}
void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &method = request.getMethod();
const string &uri = request.getURI();
Path uriPath;
bool process = true;
bool loggable = true;
if (method != "GET")
{
process = false;
if (method.length() > 32)
loggable = false;
sendMethodNotAllowed(response);
}
if (uri.length() > 256)
{
loggable = false;
if (uri.length() > 4096)
{
process = false;
sendRequestURITooLong(response);
}
}
if (process)
{
uriPath.assign(uri, Path::PATH_UNIX);
if (!uriPath.isAbsolute())
{
process = false;
sendBadRequest(response);
}
}
logRequest(request, loggable);
if (!process)
return;
if (uriPath.isDirectory() && uriPath.depth() == 0)
{
if (configuration.getRoot().empty())
{
sendVirtualRootDirectory(response);
return;
}
}
try
{
const Path &fsPath = resolveFSPath(uriPath);
const string &target = fsPath.toString();
File f(target);
if (f.isDirectory())
{
if (uriPath.isDirectory())
{
sendDirectory(response, target, uriPath.toString(Path::PATH_UNIX));
}
else
{
Path uriDirPath = uriPath;
uriDirPath.makeDirectory();
redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
}
}
else
{
const string &ext = fsPath.getExtension();
const string &mediaType = configuration.getMimeType(ext);
response.sendFile(target, mediaType);
}
}
catch (ShareNotFoundException &snfe)
{
sendNotFound(response);
}
catch (FileNotFoundException &fnfe)
{
sendNotFound(response);
}
catch (FileAccessDeniedException &fade)
{
sendForbidden(response);
}
catch (FileException &fe)
{
sendInternalServerError(response);
}
catch (PathSyntaxException &pse)
{
sendNotImplemented(response);
}
catch (...)
{
sendInternalServerError(response);
}
}
Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &shareName = uriPath[0];
string base = configuration.getSharePath(shareName);
int level = 1;
if (base.empty())
{
base = configuration.getRoot();
if (base.empty())
throw ShareNotFoundException();
level = 0;
}
Path fsPath(base);
fsPath.makeDirectory();
const int d = uriPath.depth() + (uriPath.isFile()? 1 : 0);
for (int i = level; i < d; i++)
{
fsPath.pushDirectory(uriPath[i]);
}
fsPath.makeFile();
return fsPath;
}
void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
bool root = (dirURI == "/");
ostream &out = response.send();
out << "<html>" << endl;
out << "<head>" << endl;
out << "<title>";
out << "Index of " << dirURI;
out << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << endl;
out << "<h1>";
out << "Index of " << dirURI;
out << "</h1>" << endl;
if (!root)
{
out << "<a href=\"../\"><Parent Directory></a><br>" << endl;
}
const int l = entries.size();
for (int i = 0; i < l; i++)
{
out << "<a href=\"" << entries[i] << "\">" << entries[i] << "</a>" << "<br>" << endl;
}
out << "</body>" << endl;
out << "</html>" << endl;
}
void IndigoRequestHandler::sendVirtualRootDirectory(HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> &shares = configuration.getShares();
vector<string> entries;
set<string>::const_iterator it;
const set<string>::const_iterator &end = shares.end();
for (it = shares.begin(); it != end; ++it)
{
const string &shareName = *it;
try
{
const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
File f(fsPath);
if (!f.isHidden())
{
string entry = shareName;
if (f.isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
sendDirectoryListing(response, "/", entries);
}
void IndigoRequestHandler::sendDirectory(HTTPServerResponse &response, const string &path, const string &dirURI)
{
vector<string> entries;
DirectoryIterator it(path);
DirectoryIterator end;
while (it != end)
{
try
{
if (!it->isHidden())
{
string entry = it.name();
if (it->isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
++it;
}
sendDirectoryListing(response, dirURI, entries);
}
void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
if (!permanent)
{
response.redirect(dirURI);
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
response.setContentLength(0);
response.setChunkedTransferEncoding(false);
response.set("Location", dirURI);
response.send();
}
}
void IndigoRequestHandler::logRequest(const HTTPServerRequest &request, bool loggable)
{
const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
if (app.isInteractive())
{
const string &method = request.getMethod();
const string &uri = request.getURI();
const string &host = request.clientAddress().host().toString();
string logString;
if (loggable)
logString = host + " - " + method + " " + uri;
else
logString = "Request from " + host;
app.logger().information(logString);
}
}
void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
if (response.sent())
return;
response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
const string &reason = response.getReason();
ostringstream ostr;
ostr << code;
ostream &out = response.send();
out << "<html>";
out << "<head><title>" + ostr.str() + " " + reason + "</title></head>";
out << "<body><h1>" + reason + "</h1></body>";
out << "</html>";
}
void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}
void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}
void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}
void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}
void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}
void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}
void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<commit_msg>Cosmetics.<commit_after>
#include <climits>
#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <sstream>
#include "Poco/Util/ServerApplication.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;
POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")
IndigoRequestHandler::IndigoRequestHandler()
{
}
void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &method = request.getMethod();
const string &uri = request.getURI();
Path uriPath;
bool process = true;
bool loggable = true;
if (method != "GET")
{
process = false;
if (method.length() > 32)
loggable = false;
sendMethodNotAllowed(response);
}
if (uri.length() > 256)
{
loggable = false;
if (uri.length() > 4096)
{
process = false;
sendRequestURITooLong(response);
}
}
if (process)
{
uriPath.assign(uri, Path::PATH_UNIX);
if (!uriPath.isAbsolute())
{
process = false;
sendBadRequest(response);
}
}
logRequest(request, loggable);
if (!process)
return;
if (uriPath.isDirectory() && uriPath.depth() == 0)
{
if (configuration.getRoot().empty())
{
sendVirtualRootDirectory(response);
return;
}
}
try
{
const Path &fsPath = resolveFSPath(uriPath);
const string &target = fsPath.toString();
File f(target);
if (f.isDirectory())
{
if (uriPath.isDirectory())
{
sendDirectory(response, target, uriPath.toString(Path::PATH_UNIX));
}
else
{
Path uriDirPath = uriPath;
uriDirPath.makeDirectory();
redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
}
}
else
{
const string &ext = fsPath.getExtension();
const string &mediaType = configuration.getMimeType(ext);
response.sendFile(target, mediaType);
}
}
catch (ShareNotFoundException &snfe)
{
sendNotFound(response);
}
catch (FileNotFoundException &fnfe)
{
sendNotFound(response);
}
catch (FileAccessDeniedException &fade)
{
sendForbidden(response);
}
catch (FileException &fe)
{
sendInternalServerError(response);
}
catch (PathSyntaxException &pse)
{
sendNotImplemented(response);
}
catch (...)
{
sendInternalServerError(response);
}
}
Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &shareName = uriPath[0];
string base = configuration.getSharePath(shareName);
int level = 1;
if (base.empty())
{
base = configuration.getRoot();
if (base.empty())
throw ShareNotFoundException();
level = 0;
}
Path fsPath(base);
fsPath.makeDirectory();
const int d = uriPath.depth() + (uriPath.isFile()? 1 : 0);
for (int i = level; i < d; i++)
{
fsPath.pushDirectory(uriPath[i]);
}
fsPath.makeFile();
return fsPath;
}
void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
bool root = (dirURI == "/");
ostream &out = response.send();
out << "<html>" << endl;
out << "<head>" << endl;
out << "<title>";
out << "Index of " << dirURI;
out << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << endl;
out << "<h1>";
out << "Index of " << dirURI;
out << "</h1>" << endl;
if (!root)
{
out << "<a href=\"../\"><Parent Directory></a><br>" << endl;
}
const int l = entries.size();
for (int i = 0; i < l; i++)
{
out << "<a href=\"" << entries[i] << "\">" << entries[i] << "</a>" << "<br>" << endl;
}
out << "</body>" << endl;
out << "</html>" << endl;
}
void IndigoRequestHandler::sendVirtualRootDirectory(HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> &shares = configuration.getShares();
vector<string> entries;
set<string>::const_iterator it;
const set<string>::const_iterator &end = shares.end();
for (it = shares.begin(); it != end; ++it)
{
const string &shareName = *it;
try
{
const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
File f(fsPath);
if (!f.isHidden())
{
string entry = shareName;
if (f.isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
sendDirectoryListing(response, "/", entries);
}
void IndigoRequestHandler::sendDirectory(HTTPServerResponse &response, const string &path, const string &dirURI)
{
vector<string> entries;
DirectoryIterator it(path);
DirectoryIterator end;
while (it != end)
{
try
{
if (!it->isHidden())
{
string entry = it.name();
if (it->isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
++it;
}
sendDirectoryListing(response, dirURI, entries);
}
void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
if (!permanent)
{
response.redirect(dirURI);
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
response.setContentLength(0);
response.setChunkedTransferEncoding(false);
response.set("Location", dirURI);
response.send();
}
}
void IndigoRequestHandler::logRequest(const HTTPServerRequest &request, bool loggable)
{
const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
if (app.isInteractive())
{
const string &method = request.getMethod();
const string &uri = request.getURI();
const string &host = request.clientAddress().host().toString();
string logString;
if (loggable)
logString = host + " - " + method + " " + uri;
else
logString = "Request from " + host;
app.logger().information(logString);
}
}
void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
if (response.sent())
return;
response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
const string &reason = response.getReason();
ostringstream ostr;
ostr << code;
ostream &out = response.send();
out << "<html>";
out << "<head><title>" + ostr.str() + " " + reason + "</title></head>";
out << "<body><h1>" + reason + "</h1></body>";
out << "</html>";
}
void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}
void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}
void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}
void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}
void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}
void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}
void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/uri.h>
#include <fnordmetric/environment.h>
#include <fnordmetric/adminui.h>
namespace fnordmetric {
AdminUI::AdminUI(
std::string path_prefix /* = "/admin" */) :
path_prefix_(path_prefix),
webui_bundle_("FnordMetric"),
webui_mount_(&webui_bundle_, path_prefix) {
webui_bundle_.addComponent("fnord/3rdparty/codemirror.js");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css");
webui_bundle_.addComponent("fnord/3rdparty/reset.css");
webui_bundle_.addComponent("fnord/components/fn-table.css");
webui_bundle_.addComponent("fnord/components/fn-button.css");
webui_bundle_.addComponent("fnord/components/fn-modal.css");
webui_bundle_.addComponent("fnord/components/fn-tabbar.css");
webui_bundle_.addComponent("fnord/components/fn-message.css");
webui_bundle_.addComponent("fnord/components/fn-tooltip.css");
webui_bundle_.addComponent("fnord/components/fn-dropdown.css");
webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css");
webui_bundle_.addComponent("fnord/components/fn-search.css");
webui_bundle_.addComponent("fnord/components/fn-input.css");
webui_bundle_.addComponent("fnord/components/fn-search.css");
webui_bundle_.addComponent("fnord/fnord.js");
webui_bundle_.addComponent("fnord/date_util.js");
webui_bundle_.addComponent("fnord/components/fn-appbar.html");
webui_bundle_.addComponent("fnord/components/fn-button.html");
webui_bundle_.addComponent("fnord/components/fn-button-group.html");
webui_bundle_.addComponent("fnord/components/fn-icon.html");
webui_bundle_.addComponent("fnord/components/fn-input.html");
webui_bundle_.addComponent("fnord/components/fn-loader.html");
webui_bundle_.addComponent("fnord/components/fn-menu.html");
webui_bundle_.addComponent("fnord/components/fn-search.html");
webui_bundle_.addComponent("fnord/components/fn-table.html");
webui_bundle_.addComponent("fnord/components/fn-splitpane.html");
webui_bundle_.addComponent("fnord/components/fn-codeeditor.html");
webui_bundle_.addComponent("fnord/components/fn-dropdown.html");
webui_bundle_.addComponent("fnord/components/fn-datepicker.html");
webui_bundle_.addComponent("fnord/components/fn-timeinput.html");
webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html");
webui_bundle_.addComponent("fnord/components/fn-tabbar.html");
webui_bundle_.addComponent("fnord/components/fn-modal.html");
webui_bundle_.addComponent("fnord/components/fn-pager.html");
webui_bundle_.addComponent("fnord/components/fn-tooltip.html");
webui_bundle_.addComponent("fnord/components/fn-flexbox.html");
webui_bundle_.addComponent("fnord/components/fn-checkbox.html");
webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html");
webui_bundle_.addComponent("fnord/components/fn-calendar.html");
webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html");
webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html");
webui_bundle_.addComponent("fnord-metricdb/metric-control.html");
webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html");
//webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css");
//webui_bundle_.addComponent("fnord/themes/midnight-blue.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js");
webui_bundle_.addComponent(
"fnordmetric/fnordmetric-embed-query-popup.html");
}
void AdminUI::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
fnord::URI uri(request->uri());
auto path = uri.path();
if (path == "/") {
response->setStatus(http::kStatusFound);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addHeader("Location", path_prefix_);
return;
}
if (path == "/fontawesome.woff") {
request->setURI(
StringUtil::format(
"$0/__components__/fnord/3rdparty/fontawesome.woff",
path_prefix_));
}
webui_mount_.handleHTTPRequest(request, response);
}
}
<commit_msg>added splitpane styles<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/uri.h>
#include <fnordmetric/environment.h>
#include <fnordmetric/adminui.h>
namespace fnordmetric {
AdminUI::AdminUI(
std::string path_prefix /* = "/admin" */) :
path_prefix_(path_prefix),
webui_bundle_("FnordMetric"),
webui_mount_(&webui_bundle_, path_prefix) {
webui_bundle_.addComponent("fnord/3rdparty/codemirror.js");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css");
webui_bundle_.addComponent("fnord/3rdparty/reset.css");
webui_bundle_.addComponent("fnord/components/fn-table.css");
webui_bundle_.addComponent("fnord/components/fn-button.css");
webui_bundle_.addComponent("fnord/components/fn-modal.css");
webui_bundle_.addComponent("fnord/components/fn-tabbar.css");
webui_bundle_.addComponent("fnord/components/fn-message.css");
webui_bundle_.addComponent("fnord/components/fn-tooltip.css");
webui_bundle_.addComponent("fnord/components/fn-dropdown.css");
webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css");
webui_bundle_.addComponent("fnord/components/fn-search.css");
webui_bundle_.addComponent("fnord/components/fn-input.css");
webui_bundle_.addComponent("fnord/components/fn-search.css");
webui_bundle_.addComponent("fnord/components/fn-splitpane.css");
webui_bundle_.addComponent("fnord/fnord.js");
webui_bundle_.addComponent("fnord/date_util.js");
webui_bundle_.addComponent("fnord/components/fn-appbar.html");
webui_bundle_.addComponent("fnord/components/fn-button.html");
webui_bundle_.addComponent("fnord/components/fn-button-group.html");
webui_bundle_.addComponent("fnord/components/fn-icon.html");
webui_bundle_.addComponent("fnord/components/fn-input.html");
webui_bundle_.addComponent("fnord/components/fn-loader.html");
webui_bundle_.addComponent("fnord/components/fn-menu.html");
webui_bundle_.addComponent("fnord/components/fn-search.html");
webui_bundle_.addComponent("fnord/components/fn-table.html");
webui_bundle_.addComponent("fnord/components/fn-splitpane.html");
webui_bundle_.addComponent("fnord/components/fn-codeeditor.html");
webui_bundle_.addComponent("fnord/components/fn-dropdown.html");
webui_bundle_.addComponent("fnord/components/fn-datepicker.html");
webui_bundle_.addComponent("fnord/components/fn-timeinput.html");
webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html");
webui_bundle_.addComponent("fnord/components/fn-tabbar.html");
webui_bundle_.addComponent("fnord/components/fn-modal.html");
webui_bundle_.addComponent("fnord/components/fn-pager.html");
webui_bundle_.addComponent("fnord/components/fn-tooltip.html");
webui_bundle_.addComponent("fnord/components/fn-flexbox.html");
webui_bundle_.addComponent("fnord/components/fn-checkbox.html");
webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html");
webui_bundle_.addComponent("fnord/components/fn-calendar.html");
webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html");
webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html");
webui_bundle_.addComponent("fnord-metricdb/metric-control.html");
webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html");
//webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css");
//webui_bundle_.addComponent("fnord/themes/midnight-blue.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js");
webui_bundle_.addComponent(
"fnordmetric/fnordmetric-embed-query-popup.html");
}
void AdminUI::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
fnord::URI uri(request->uri());
auto path = uri.path();
if (path == "/") {
response->setStatus(http::kStatusFound);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addHeader("Location", path_prefix_);
return;
}
if (path == "/fontawesome.woff") {
request->setURI(
StringUtil::format(
"$0/__components__/fnord/3rdparty/fontawesome.woff",
path_prefix_));
}
webui_mount_.handleHTTPRequest(request, response);
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed as defined on the LICENSE file found in the
* root directory of this source tree.
*/
#include <algorithm>
#include <ctime>
#include <boost/format.hpp>
#include <boost/io/detail/quoted_manip.hpp>
#include <osquery/config/config.h>
#include <osquery/core.h>
#include <osquery/data_logger.h>
#include <osquery/database.h>
#include <osquery/flags.h>
#include <osquery/killswitch.h>
#include <osquery/numeric_monitoring.h>
#include <osquery/process/process.h>
#include <osquery/profiler/profiler.h>
#include <osquery/query.h>
#include <osquery/utils/system/time.h>
#include "osquery/config/parsers/decorators.h"
#include "osquery/dispatcher/scheduler.h"
#include "osquery/sql/sqlite_util.h"
namespace osquery {
FLAG(uint64, schedule_timeout, 0, "Limit the schedule, 0 for no limit");
FLAG(uint64,
schedule_max_drift,
60,
"Max time drift in seconds. Scheduler tries to compensate the drift until "
"the drift exceed this value. After it the drift will be reseted to zero "
"and the compensation process will start from the beginning. It is needed "
"to avoid the problem of endless compensation (which is CPU greedy) after "
"a long SIGSTOP/SIGCONT pause or something similar. Set it to zero to "
"switch off a drift compensation. Default: 60");
FLAG(uint64,
schedule_reload,
300,
"Interval in seconds to reload database arenas");
FLAG(uint64, schedule_epoch, 0, "Epoch for scheduled queries");
HIDDEN_FLAG(bool, enable_monitor, true, "Enable the schedule monitor");
HIDDEN_FLAG(bool,
schedule_reload_sql,
false,
"Reload the SQL implementation during schedule reload");
/// Used to bypass (optimize-out) the set-differential of query results.
DECLARE_bool(events_optimize);
SQLInternal monitor(const std::string& name, const ScheduledQuery& query) {
// Snapshot the performance and times for the worker before running.
auto pid = std::to_string(PlatformProcess::getCurrentPid());
auto r0 = SQL::selectFrom({"resident_size", "user_time", "system_time"},
"processes",
"pid",
EQUALS,
pid);
auto t0 = getUnixTime();
Config::get().recordQueryStart(name);
SQLInternal sql(query.query, true);
// Snapshot the performance after, and compare.
auto t1 = getUnixTime();
auto r1 = SQL::selectFrom({"resident_size", "user_time", "system_time"},
"processes",
"pid",
EQUALS,
pid);
if (r0.size() > 0 && r1.size() > 0) {
// Always called while processes table is working.
Config::get().recordQueryPerformance(name, t1 - t0, r0[0], r1[0]);
}
return sql;
}
Status launchQuery(const std::string& name, const ScheduledQuery& query) {
// Execute the scheduled query and create a named query object.
LOG(INFO) << "Executing scheduled query " << name << ": " << query.query;
runDecorators(DECORATE_ALWAYS);
auto sql = monitor(name, query);
if (!sql.ok()) {
LOG(ERROR) << "Error executing scheduled query " << name << ": "
<< sql.getMessageString();
return Status::failure("Error executing scheduled query");
}
// Fill in a host identifier fields based on configuration or availability.
std::string ident = getHostIdentifier();
// A query log item contains an optional set of differential results or
// a copy of the most-recent execution alongside some query metadata.
QueryLogItem item;
item.name = name;
item.identifier = ident;
item.columns = sql.columns();
item.time = osquery::getUnixTime();
item.epoch = FLAGS_schedule_epoch;
item.calendar_time = osquery::getAsciiTime();
getDecorations(item.decorations);
if (query.options.count("snapshot") && query.options.at("snapshot")) {
// This is a snapshot query, emit results with a differential or state.
item.snapshot_results = std::move(sql.rows());
logSnapshotQuery(item);
return Status::success();
}
// Create a database-backed set of query results.
auto dbQuery = Query(name, query);
// Comparisons and stores must include escaped data.
sql.escapeResults();
Status status;
DiffResults& diff_results = item.results;
// Add this execution's set of results to the database-tracked named query.
// We can then ask for a differential from the last time this named query
// was executed by exact matching each row.
if (!FLAGS_events_optimize || !sql.eventBased()) {
status = dbQuery.addNewResults(
std::move(sql.rows()), item.epoch, item.counter, diff_results);
if (!status.ok()) {
std::string line = "Error adding new results to database for query " +
name + ": " + status.what();
LOG(ERROR) << line;
// If the database is not available then the daemon cannot continue.
Initializer::requestShutdown(EXIT_CATASTROPHIC, line);
}
} else {
diff_results.added = std::move(sql.rows());
}
if (query.options.count("removed") && !query.options.at("removed")) {
diff_results.removed.clear();
}
if (diff_results.added.empty() && diff_results.removed.empty()) {
// No diff results or events to emit.
return status;
}
VLOG(1) << "Found results for query: " << name;
status = logQueryLogItem(item);
if (!status.ok()) {
// If log directory is not available, then the daemon shouldn't continue.
std::string error = "Error logging the results of query: " + name + ": " +
status.toString();
LOG(ERROR) << error;
Initializer::requestShutdown(EXIT_CATASTROPHIC, error);
}
return status;
}
void SchedulerRunner::start() {
// Start the counter at the second.
auto i = osquery::getUnixTime();
for (; (timeout_ == 0) || (i <= timeout_); ++i) {
auto start_time_point = std::chrono::steady_clock::now();
Config::get().scheduledQueries(
([&i](std::string name, const ScheduledQuery& query) {
if (query.splayed_interval > 0 && i % query.splayed_interval == 0) {
TablePlugin::kCacheInterval = query.splayed_interval;
TablePlugin::kCacheStep = i;
{
CodeProfiler codeProfiler(
{(boost::format("scheduler.executing_query.%s") % name)
.str()});
const auto status = launchQuery(name, query);
};
}
}));
// Configuration decorators run on 60 second intervals only.
if ((i % 60) == 0) {
runDecorators(DECORATE_INTERVAL, i);
}
if (FLAGS_schedule_reload > 0 && (i % FLAGS_schedule_reload) == 0) {
if (FLAGS_schedule_reload_sql) {
SQLiteDBManager::resetPrimary();
}
resetDatabase();
}
// GLog is not re-entrant, so logs must be flushed in a dedicated thread.
if ((i % 3) == 0) {
relayStatusLogs(true);
}
auto loop_step_duration =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_time_point);
if (loop_step_duration + time_drift_ < interval_) {
pause(std::chrono::milliseconds(interval_ - loop_step_duration -
time_drift_));
time_drift_ = std::chrono::milliseconds::zero();
} else {
time_drift_ += loop_step_duration - interval_;
if (time_drift_ > max_time_drift_) {
// giving up
time_drift_ = std::chrono::milliseconds::zero();
}
}
if (interrupted()) {
break;
}
}
}
std::chrono::milliseconds SchedulerRunner::getCurrentTimeDrift() const
noexcept {
return time_drift_;
}
void startScheduler() {
startScheduler(static_cast<unsigned long int>(FLAGS_schedule_timeout), 1);
}
void startScheduler(unsigned long int timeout, size_t interval) {
Dispatcher::addService(std::make_shared<SchedulerRunner>(
timeout, interval, std::chrono::seconds{FLAGS_schedule_max_drift}));
}
} // namespace osquery
<commit_msg>Split query name and pack name<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed as defined on the LICENSE file found in the
* root directory of this source tree.
*/
#include <algorithm>
#include <ctime>
#include <boost/format.hpp>
#include <boost/io/detail/quoted_manip.hpp>
#include <osquery/config/config.h>
#include <osquery/core.h>
#include <osquery/data_logger.h>
#include <osquery/database.h>
#include <osquery/flags.h>
#include <osquery/killswitch.h>
#include <osquery/numeric_monitoring.h>
#include <osquery/process/process.h>
#include <osquery/profiler/profiler.h>
#include <osquery/query.h>
#include <osquery/utils/system/time.h>
#include "osquery/config/parsers/decorators.h"
#include "osquery/dispatcher/scheduler.h"
#include "osquery/sql/sqlite_util.h"
namespace osquery {
FLAG(uint64, schedule_timeout, 0, "Limit the schedule, 0 for no limit");
FLAG(uint64,
schedule_max_drift,
60,
"Max time drift in seconds. Scheduler tries to compensate the drift until "
"the drift exceed this value. After it the drift will be reseted to zero "
"and the compensation process will start from the beginning. It is needed "
"to avoid the problem of endless compensation (which is CPU greedy) after "
"a long SIGSTOP/SIGCONT pause or something similar. Set it to zero to "
"switch off a drift compensation. Default: 60");
FLAG(uint64,
schedule_reload,
300,
"Interval in seconds to reload database arenas");
FLAG(uint64, schedule_epoch, 0, "Epoch for scheduled queries");
HIDDEN_FLAG(bool, enable_monitor, true, "Enable the schedule monitor");
HIDDEN_FLAG(bool,
schedule_reload_sql,
false,
"Reload the SQL implementation during schedule reload");
/// Used to bypass (optimize-out) the set-differential of query results.
DECLARE_bool(events_optimize);
DECLARE_bool(enable_numeric_monitoring);
SQLInternal monitor(const std::string& name, const ScheduledQuery& query) {
if (FLAGS_enable_numeric_monitoring) {
CodeProfiler profiler(
{(boost::format("scheduler.pack.%s") % query.pack_name).str(),
(boost::format("scheduler.query.%s.%s") % query.pack_name % query.name)
.str()});
return SQLInternal(query.query, true);
} else {
// Snapshot the performance and times for the worker before running.
auto pid = std::to_string(PlatformProcess::getCurrentPid());
auto r0 = SQL::selectFrom({"resident_size", "user_time", "system_time"},
"processes",
"pid",
EQUALS,
pid);
auto t0 = getUnixTime();
Config::get().recordQueryStart(name);
SQLInternal sql(query.query, true);
// Snapshot the performance after, and compare.
auto t1 = getUnixTime();
auto r1 = SQL::selectFrom({"resident_size", "user_time", "system_time"},
"processes",
"pid",
EQUALS,
pid);
if (r0.size() > 0 && r1.size() > 0) {
// Always called while processes table is working.
Config::get().recordQueryPerformance(name, t1 - t0, r0[0], r1[0]);
}
return sql;
}
}
Status launchQuery(const std::string& name, const ScheduledQuery& query) {
// Execute the scheduled query and create a named query object.
LOG(INFO) << "Executing scheduled query " << name << ": " << query.query;
runDecorators(DECORATE_ALWAYS);
auto sql = monitor(name, query);
if (!sql.ok()) {
LOG(ERROR) << "Error executing scheduled query " << name << ": "
<< sql.getMessageString();
return Status::failure("Error executing scheduled query");
}
// Fill in a host identifier fields based on configuration or availability.
std::string ident = getHostIdentifier();
// A query log item contains an optional set of differential results or
// a copy of the most-recent execution alongside some query metadata.
QueryLogItem item;
item.name = name;
item.identifier = ident;
item.columns = sql.columns();
item.time = osquery::getUnixTime();
item.epoch = FLAGS_schedule_epoch;
item.calendar_time = osquery::getAsciiTime();
getDecorations(item.decorations);
if (query.options.count("snapshot") && query.options.at("snapshot")) {
// This is a snapshot query, emit results with a differential or state.
item.snapshot_results = std::move(sql.rows());
logSnapshotQuery(item);
return Status::success();
}
// Create a database-backed set of query results.
auto dbQuery = Query(name, query);
// Comparisons and stores must include escaped data.
sql.escapeResults();
Status status;
DiffResults& diff_results = item.results;
// Add this execution's set of results to the database-tracked named query.
// We can then ask for a differential from the last time this named query
// was executed by exact matching each row.
if (!FLAGS_events_optimize || !sql.eventBased()) {
status = dbQuery.addNewResults(
std::move(sql.rows()), item.epoch, item.counter, diff_results);
if (!status.ok()) {
std::string line = "Error adding new results to database for query " +
name + ": " + status.what();
LOG(ERROR) << line;
// If the database is not available then the daemon cannot continue.
Initializer::requestShutdown(EXIT_CATASTROPHIC, line);
}
} else {
diff_results.added = std::move(sql.rows());
}
if (query.options.count("removed") && !query.options.at("removed")) {
diff_results.removed.clear();
}
if (diff_results.added.empty() && diff_results.removed.empty()) {
// No diff results or events to emit.
return status;
}
VLOG(1) << "Found results for query: " << name;
status = logQueryLogItem(item);
if (!status.ok()) {
// If log directory is not available, then the daemon shouldn't continue.
std::string error = "Error logging the results of query: " + name + ": " +
status.toString();
LOG(ERROR) << error;
Initializer::requestShutdown(EXIT_CATASTROPHIC, error);
}
return status;
}
void SchedulerRunner::start() {
// Start the counter at the second.
auto i = osquery::getUnixTime();
for (; (timeout_ == 0) || (i <= timeout_); ++i) {
auto start_time_point = std::chrono::steady_clock::now();
Config::get().scheduledQueries(
([&i](const std::string& name, const ScheduledQuery& query) {
if (query.splayed_interval > 0 && i % query.splayed_interval == 0) {
TablePlugin::kCacheInterval = query.splayed_interval;
TablePlugin::kCacheStep = i;
const auto status = launchQuery(name, query);
}
}));
// Configuration decorators run on 60 second intervals only.
if ((i % 60) == 0) {
runDecorators(DECORATE_INTERVAL, i);
}
if (FLAGS_schedule_reload > 0 && (i % FLAGS_schedule_reload) == 0) {
if (FLAGS_schedule_reload_sql) {
SQLiteDBManager::resetPrimary();
}
resetDatabase();
}
// GLog is not re-entrant, so logs must be flushed in a dedicated thread.
if ((i % 3) == 0) {
relayStatusLogs(true);
}
auto loop_step_duration =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_time_point);
if (loop_step_duration + time_drift_ < interval_) {
pause(std::chrono::milliseconds(interval_ - loop_step_duration -
time_drift_));
time_drift_ = std::chrono::milliseconds::zero();
} else {
time_drift_ += loop_step_duration - interval_;
if (time_drift_ > max_time_drift_) {
// giving up
time_drift_ = std::chrono::milliseconds::zero();
}
}
if (interrupted()) {
break;
}
}
}
std::chrono::milliseconds SchedulerRunner::getCurrentTimeDrift() const
noexcept {
return time_drift_;
}
void startScheduler() {
startScheduler(static_cast<unsigned long int>(FLAGS_schedule_timeout), 1);
}
void startScheduler(unsigned long int timeout, size_t interval) {
Dispatcher::addService(std::make_shared<SchedulerRunner>(
timeout, interval, std::chrono::seconds{FLAGS_schedule_max_drift}));
}
} // namespace osquery
<|endoftext|> |
<commit_before>#include "mount.hpp"
#include <server/path.hpp>
#include <silicium/connecting_observable.hpp>
#include <silicium/total_consumer.hpp>
#include <silicium/http/http.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/sending_observable.hpp>
#include <silicium/socket_observable.hpp>
#include <silicium/received_from_socket_source.hpp>
#include <silicium/observable_source.hpp>
#include <silicium/virtualized_source.hpp>
#include <boost/program_options.hpp>
#include <boost/asio/io_service.hpp>
#include <iostream>
namespace
{
Si::http::request_header make_get_request(std::string host, std::string path)
{
Si::http::request_header header;
header.http_version = "HTTP/1.0";
header.method = "GET";
header.path = std::move(path);
header.arguments["Host"] = std::move(host);
return header;
}
void get_file(fileserver::unknown_digest const &requested_digest)
{
boost::asio::io_service io;
boost::asio::ip::tcp::socket socket(io);
Si::connecting_observable connector(socket, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), 8080));
auto connecting = Si::make_total_consumer(Si::make_coroutine<Si::nothing>([&connector, &socket, &requested_digest](Si::push_context<Si::nothing> &yield) -> void
{
{
boost::optional<boost::system::error_code> const error = yield.get_one(connector);
assert(error);
if (*error)
{
return;
}
}
{
std::vector<char> send_buffer;
auto send_sink = Si::make_container_sink(send_buffer);
Si::http::write_header(send_sink, make_get_request("localhost", "/" + fileserver::format_digest(requested_digest)));
Si::sending_observable sending(socket, boost::make_iterator_range(send_buffer.data(), send_buffer.data() + send_buffer.size()));
boost::optional<Si::error_or<std::size_t>> const error = yield.get_one(sending);
assert(error);
if (error->is_error())
{
return;
}
}
{
std::array<char, 4096> receive_buffer;
auto socket_source = Si::virtualize_source(Si::make_observable_source(Si::socket_observable(socket, boost::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size())), yield));
{
Si::received_from_socket_source response_source(socket_source);
boost::optional<Si::http::response_header> const response = Si::http::parse_response_header(response_source);
if (!response)
{
return;
}
}
for (;;)
{
auto piece = Si::get(socket_source);
if (!piece || piece->is_error())
{
break;
}
auto const &bytes = piece->get();
std::cout.write(bytes.begin, std::distance(bytes.begin, bytes.end));
}
}
}));
connecting.start();
io.run();
}
}
int main(int argc, char **argv)
{
std::string verb;
std::string digest;
boost::filesystem::path mount_point;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("verb", boost::program_options::value(&verb), "what to do (get)")
("digest,d", boost::program_options::value(&digest), "the hash of the file to get/mount")
("mountpoint", boost::program_options::value(&mount_point), "a directory to mount at")
;
boost::program_options::positional_options_description positional;
positional.add("verb", 1);
positional.add("digest", 1);
boost::program_options::variables_map vm;
try
{
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);
}
catch (boost::program_options::error const &ex)
{
std::cerr
<< ex.what() << '\n'
<< desc << "\n";
return 1;
}
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cerr << desc << "\n";
return 1;
}
auto const parse_digest = [&digest]() -> boost::optional<fileserver::unknown_digest>
{
auto parsed = fileserver::parse_digest(digest.begin(), digest.end());
if (!parsed)
{
std::cerr << "The digest must be an even number of hexidecimal digits.\n";
return boost::none;
}
if (parsed->empty())
{
std::cerr << "The digest must be empty\n";
return boost::none;
}
return parsed;
};
if (verb == "get")
{
auto requested = parse_digest();
if (!requested)
{
return 1;
}
get_file(*requested);
}
else if (verb == "mount")
{
auto requested = parse_digest();
if (!requested)
{
return 1;
}
fileserver::mount_directory(*requested, mount_point, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), 8080));
}
else
{
std::cerr
<< "Unknown verb\n"
<< desc << "\n";
return 1;
}
}
<commit_msg>client has --host option for the IPv4 address of the server<commit_after>#include "mount.hpp"
#include <server/path.hpp>
#include <silicium/connecting_observable.hpp>
#include <silicium/total_consumer.hpp>
#include <silicium/http/http.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/sending_observable.hpp>
#include <silicium/socket_observable.hpp>
#include <silicium/received_from_socket_source.hpp>
#include <silicium/observable_source.hpp>
#include <silicium/virtualized_source.hpp>
#include <boost/program_options.hpp>
#include <boost/asio/io_service.hpp>
#include <iostream>
namespace
{
Si::http::request_header make_get_request(std::string host, std::string path)
{
Si::http::request_header header;
header.http_version = "HTTP/1.0";
header.method = "GET";
header.path = std::move(path);
header.arguments["Host"] = std::move(host);
return header;
}
void get_file(fileserver::unknown_digest const &requested_digest)
{
boost::asio::io_service io;
boost::asio::ip::tcp::socket socket(io);
Si::connecting_observable connector(socket, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), 8080));
auto connecting = Si::make_total_consumer(Si::make_coroutine<Si::nothing>([&connector, &socket, &requested_digest](Si::push_context<Si::nothing> &yield) -> void
{
{
boost::optional<boost::system::error_code> const error = yield.get_one(connector);
assert(error);
if (*error)
{
return;
}
}
{
std::vector<char> send_buffer;
auto send_sink = Si::make_container_sink(send_buffer);
Si::http::write_header(send_sink, make_get_request("localhost", "/" + fileserver::format_digest(requested_digest)));
Si::sending_observable sending(socket, boost::make_iterator_range(send_buffer.data(), send_buffer.data() + send_buffer.size()));
boost::optional<Si::error_or<std::size_t>> const error = yield.get_one(sending);
assert(error);
if (error->is_error())
{
return;
}
}
{
std::array<char, 4096> receive_buffer;
auto socket_source = Si::virtualize_source(Si::make_observable_source(Si::socket_observable(socket, boost::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size())), yield));
{
Si::received_from_socket_source response_source(socket_source);
boost::optional<Si::http::response_header> const response = Si::http::parse_response_header(response_source);
if (!response)
{
return;
}
}
for (;;)
{
auto piece = Si::get(socket_source);
if (!piece || piece->is_error())
{
break;
}
auto const &bytes = piece->get();
std::cout.write(bytes.begin, std::distance(bytes.begin, bytes.end));
}
}
}));
connecting.start();
io.run();
}
}
int main(int argc, char **argv)
{
std::string verb;
std::string digest;
boost::filesystem::path mount_point;
std::string host;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("verb", boost::program_options::value(&verb), "what to do (get)")
("digest,d", boost::program_options::value(&digest), "the hash of the file to get/mount")
("mountpoint", boost::program_options::value(&mount_point), "a directory to mount at")
("host", boost::program_options::value(&host), "the IP address of the server")
;
boost::program_options::positional_options_description positional;
positional.add("verb", 1);
positional.add("digest", 1);
boost::program_options::variables_map vm;
try
{
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);
}
catch (boost::program_options::error const &ex)
{
std::cerr
<< ex.what() << '\n'
<< desc << "\n";
return 1;
}
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cerr << desc << "\n";
return 1;
}
auto const parse_digest = [&digest]() -> boost::optional<fileserver::unknown_digest>
{
auto parsed = fileserver::parse_digest(digest.begin(), digest.end());
if (!parsed)
{
std::cerr << "The digest must be an even number of hexidecimal digits.\n";
return boost::none;
}
if (parsed->empty())
{
std::cerr << "The digest must be empty\n";
return boost::none;
}
return parsed;
};
if (verb == "get")
{
auto requested = parse_digest();
if (!requested)
{
return 1;
}
get_file(*requested);
}
else if (verb == "mount")
{
auto requested = parse_digest();
if (!requested)
{
return 1;
}
boost::asio::ip::address_v4 server_address = boost::asio::ip::address_v4::loopback();
if (!host.empty())
{
boost::system::error_code ec;
server_address = boost::asio::ip::address_v4::from_string(host, ec);
if (ec)
{
std::cerr << ec.message() << '\n';
return 1;
}
}
fileserver::mount_directory(*requested, mount_point, boost::asio::ip::tcp::endpoint(server_address, 8080));
}
else
{
std::cerr
<< "Unknown verb\n"
<< desc << "\n";
return 1;
}
}
<|endoftext|> |
<commit_before>// Tuple unpacking using a tuple indexer
//
// Adapted from: http://loungecpp.wikidot.com/tips-and-tricks%3aindices
//
// tuple<A,B,C> result =
// tuple<A,B,C>(f(get<0>(x), f(get<1>(x), f(get<2>(x));
//
// Is replaced with
//
// tuple<Args...> result = tuple<Args...>(f(get<Indices>(x))...);
//
#include <iostream>
#include <tuple>
using namespace std;
template <std::size_t... Is>
struct TupleIndices {};
template <std::size_t N, std::size_t... Is>
struct build_indices : build_indices<N-1, N-1, Is...> {};
template <std::size_t... Is>
struct build_indices<0, Is...> : TupleIndices<Is...> {};
template <typename ...Ts>
using IndicesFor = build_indices<sizeof...(Ts)>;
template <typename Functor, typename Tuple, std::size_t... Indices>
Tuple apply_f_impl(Functor f, const Tuple& t, TupleIndices<Indices...>)
{
return Tuple(f(std::get<Indices>(t))...);
}
template <typename Functor, typename ...Ts>
tuple<Ts...> apply_f(Functor f, const tuple<Ts...>& t)
{
return apply_f_impl(f, t, IndicesFor<Ts...> {});
}
struct MyFunctor
{
template <typename T>
T operator()(const T & t) const { return 2*t; }
};
struct ToStream
{
ToStream(ostream& os) : m_os(os) {}
template<typename T>
T operator() (T t)
{
m_os << t << ",";
return t;
}
ostream& m_os;
};
template<typename ...Ts>
ostream& operator << (ostream& os, tuple<Ts...>t)
{
os << '(';
apply_f(ToStream(os), t);
os << "\b)";
return os;
}
int main()
{
tuple<int, double, char> x(5, 1.5, 'a');
auto y = apply_f(MyFunctor(),x);
cout << "Before: " << x << " After: " << y << endl;
}
<commit_msg>improved naming and dropped using namespace std<commit_after>// std::tuple unpacking using a std::tuple indexer
//
// Adapted from: http://loungecpp.wikidot.com/tips-and-tricks%3aindices
//
// std::tuple<A,B,C> result =
// std::tuple<A,B,C>(f(get<0>(x), f(get<1>(x), f(get<2>(x));
//
// Is replaced with
//
// std::tuple<Args...> result = std::tuple<Args...>(f(get<Indices>(x))...);
//
#include <iostream>
#include <tuple>
template <std::size_t... Indices>
struct TupleIndices {};
template <std::size_t N, std::size_t... Indices>
struct build_indices : build_indices<N-1, N-1, Indices...> {};
template <std::size_t... Indices>
struct build_indices<0, Indices...> : TupleIndices<Indices...> {};
template <typename ...Ts>
using IndicesFor = build_indices<sizeof...(Ts)>;
template <typename Functor, typename Tuple_t, std::size_t... Indices>
Tuple_t apply_f_impl(Functor f, const Tuple_t& t, TupleIndices<Indices...>)
{
return Tuple_t(f(std::get<Indices>(t))...);
}
template <typename Functor, typename ...Ts>
std::tuple<Ts...> apply_f(Functor f, const std::tuple<Ts...>& t)
{
return apply_f_impl(f, t, IndicesFor<Ts...> {});
}
struct MyFunctor
{
template <typename T>
T operator()(const T & t) const { return 2*t; }
};
struct ToStream
{
ToStream(std::ostream& os) : m_os(os) {}
template<typename T>
T operator() (T t)
{
m_os << t << ",";
return t;
}
std::ostream& m_os;
};
template<typename ...Ts>
std::ostream& operator << (std::ostream& os, std::tuple<Ts...>t)
{
os << '(';
apply_f(ToStream(os), t);
os << "\b)";
return os;
}
int main()
{
std::tuple<int, double, char> x(5, 1.5, 'a');
auto y = apply_f(MyFunctor(),x);
std::cout << "Before: " << x << " After: " << y << std::endl;
}
<|endoftext|> |
<commit_before>/* This software is released under the BSD License.
|
| Copyright (c) 2011, Kevin P. Barry [the resourcerver project]
| All rights reserved.
|
| Redistribution and use in source and binary forms, with or without
| modification, are permitted provided that the following conditions are met:
|
| - Redistributions of source code must retain the above copyright notice, this
| list of conditions and the following disclaimer.
|
| - Redistributions in binary form must reproduce the above copyright notice,
| this list of conditions and the following disclaimer in the documentation
| and/or other materials provided with the distribution.
|
| - Neither the name of the Resourcerver Project nor the names of its
| contributors may be used to endorse or promote products derived from this
| software without specific prior written permission.
|
| THIS SOFTWARE IS PROVIDED BY THE 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.
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
extern "C" {
#include "ipc-passthru.h"
}
extern "C" {
#include "param.h"
#include "attributes.h"
#include "api/client-timing.h"
#include "api/monitor-client.h"
#include "api/command-queue.h"
#include "plugins/rsvp-passthru-hook.h"
}
#include <string>
#include <string.h> //'strlen', 'strsep'
#include <unistd.h> //'close', 'read', 'write'
#include <fcntl.h> //'fcntl', open modes
#include <errno.h> //'errno'
#include <stddef.h> //'offsetof'
#include <sys/stat.h> //'stat'
#include <sys/socket.h> //sockets
#include <sys/un.h> //socket macros
#include "external/clist.hpp"
#include "global/condition-block.hpp"
extern "C" {
#include "messages.h"
#include "socket-table.h"
#include "security-filter.h"
}
struct passthru_specs;
typedef data::clist <passthru_specs> passthru_list;
static passthru_list thread_list;
static auto_mutex thread_list_mutex;
static bool accept_passthru = false;
void passthru_setup()
{
if (accept_passthru) return;
command_handle new_monitor = set_monitor_flags(monitor_registered_clients | monitor_registered_services);
command_reference monitor_status = send_command(new_monitor);
destroy_command(new_monitor);
accept_passthru = wait_command_event(monitor_status, event_complete, local_default_timeout()) & event_complete;
if (!accept_passthru)
log_message_passthru_disabled();
clear_command_status(monitor_status);
}
struct passthru_specs
{
passthru_specs() : incoming(), outgoing(), socket(-1), connection(-1), reference(NULL) {}
void run_thread()
{
char buffer[PARAM_MAX_INPUT_SECTION];
ssize_t current_size;
if (pthread_equal(incoming, pthread_self()))
{
send_short_func filter = send_command_filter();
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
while ((current_size = read(socket, buffer, sizeof buffer)) != 0)
{
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
pthread_testcancel();
if (current_size < 0 && errno != EINTR) break;
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
current_size = filter?
(*filter)(reference, connection, buffer, current_size) :
write(connection, buffer, current_size);
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (current_size < 0 && errno != EINTR) break;
}
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
incoming = pthread_t();
pthread_detach(pthread_self());
pthread_mutex_unlock(thread_list_mutex);
}
}
else if (pthread_equal(outgoing, pthread_self()))
{
receive_short_func filter = receive_command_filter();
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
while ((current_size = filter?
(*filter)(reference, connection, buffer, sizeof buffer) :
read(connection, buffer, sizeof buffer) ) != 0)
{
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
pthread_testcancel();
if (current_size < 0 && errno != EINTR) break;
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
current_size = write(socket, buffer, current_size);
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (current_size < 0 && errno != EINTR) break;
}
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
outgoing = pthread_t();
pthread_detach(pthread_self());
pthread_mutex_unlock(thread_list_mutex);
}
}
}
~passthru_specs()
{
if (channel.size() || sender.size())
log_message_steal_channel_exit(channel.c_str(), sender.c_str());
if (!pthread_equal(incoming, pthread_t())) pthread_cancel(incoming);
if (!pthread_equal(outgoing, pthread_t())) pthread_cancel(outgoing);
if (socket >= 0) shutdown(socket, SHUT_RDWR);
if (connection >= 0)
{
disconnect_general(reference, connection);
shutdown(connection, SHUT_RDWR);
}
}
pthread_t incoming, outgoing;
int socket, connection;
socket_reference reference;
std::string channel, socket_name, sender;
};
static int connect_to_socket(text_info);
static void *passthru_thread(void*);
void exit_passthru_threads()
{
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
thread_list.reset_list();
pthread_mutex_unlock(thread_list_mutex);
}
}
command_event __rsvp_passthru_hook_reserve_channel(const struct passthru_source_info *sSource, text_info nName)
{
if (!sSource) return event_rejected;
log_message_incoming_reserve_channel(sSource, nName);
if (!accept_passthru)
log_message_reserve_channel_deny(nName, sSource->sender);
int file_number = find_socket(nName, sSource->sender);
if (file_number < 0 || !reserve_socket(file_number, sSource->sender))
{
log_message_reserve_channel_deny(nName, sSource->sender);
return event_error;
}
else
{
log_message_reserve_channel(nName, sSource->sender);
return event_complete;
}
}
command_event __rsvp_passthru_hook_unreserve_channel(const struct passthru_source_info *sSource, text_info nName)
{
if (!sSource) return event_rejected;
log_message_incoming_unreserve_channel(sSource, nName);
if (!accept_passthru)
log_message_unreserve_channel_deny(nName, sSource->sender);
int file_number = find_socket(nName, sSource->sender);
if (file_number < 0 || !unreserve_socket(file_number, sSource->sender))
{
log_message_unreserve_channel_deny(nName, sSource->sender);
return event_error;
}
else
{
log_message_unreserve_channel(nName, sSource->sender);
return event_complete;
}
}
command_event __rsvp_passthru_hook_steal_channel(const struct passthru_source_info *sSource, text_info nName, text_info sSocket)
{
if (!sSource) return event_rejected;
//NOTE: not restricted to local forwarders; this applies to net forwarders, also
#ifdef PARAM_ABSOLUTE_LOCAL_SOCKETS
if (strlen(sSocket) < 1 || sSocket[0] != '/')
{
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
return event_rejected;
}
#endif
log_message_incoming_steal_channel(sSource, nName, sSocket);
if (!accept_passthru)
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
socket_reference reference = NULL;
int file_number = find_socket(nName, sSource->sender);
if (file_number < 0)
{
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
return event_error;
}
int passthru_socket = -1;
if ((passthru_socket = connect_to_socket(sSocket)) < 0 ||
!steal_socket(file_number, sSource->sender, &reference))
{
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
if (passthru_socket >= 0) close(passthru_socket);
return event_error;
}
log_message_steal_channel(nName, sSocket, sSource->sender);
int current_state = fcntl(file_number, F_GETFL);
fcntl(file_number, F_SETFL, current_state & ~O_NONBLOCK);
if (!thread_list_mutex.valid() || pthread_mutex_lock(thread_list_mutex) != 0) return event_error;
passthru_specs *new_passthru = &thread_list.add_element();
new_passthru->socket = passthru_socket;
new_passthru->connection = file_number;
new_passthru->reference = reference;
new_passthru->channel = nName;
new_passthru->socket_name = sSocket;
new_passthru->sender = sSource->sender;
bool success = true;
success &= pthread_create(&new_passthru->incoming, NULL, &passthru_thread,
static_cast <passthru_specs*> (new_passthru)) == 0;
success &= pthread_create(&new_passthru->outgoing, NULL, &passthru_thread,
static_cast <passthru_specs*> (new_passthru)) == 0;
pthread_mutex_unlock(thread_list_mutex);
return success? event_complete : event_error;
}
static int connect_to_socket(text_info sSocket)
{
struct stat file_status;
if (stat(sSocket, &file_status) < 0 || !S_ISSOCK(file_status.st_mode)) return -1;
/*create socket*/
struct sockaddr_un new_address;
size_t new_length = 0;
int new_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
if (new_socket < 0) return -1;
int current_state = fcntl(new_socket, F_GETFL);
fcntl(new_socket, F_SETFL, current_state | O_NONBLOCK);
current_state = fcntl(new_socket, F_GETFD);
fcntl(new_socket, F_SETFD, current_state | FD_CLOEXEC);
/*connect socket*/
new_address.sun_family = AF_LOCAL;
strncpy(new_address.sun_path, sSocket, sizeof new_address.sun_path);
new_length = (offsetof(struct sockaddr_un, sun_path) + SUN_LEN(&new_address) + 1);
int outcome = 0;
while ((outcome = connect(new_socket, (struct sockaddr*) &new_address, new_length)) < 0 && errno == EINTR);
if (outcome < 0)
{
close(new_socket);
return -1;
}
current_state = fcntl(new_socket, F_GETFL);
fcntl(new_socket, F_SETFL, current_state & ~O_NONBLOCK);
return new_socket;
}
static bool find_passthru_specs(passthru_list::const_return_type eElement, const passthru_specs *sSpecs)
{ return &eElement == sSpecs; }
static void *passthru_thread(void *sSpecs)
{
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
if (!sSpecs) return NULL;
passthru_specs *specs = (passthru_specs*) sSpecs;
specs->run_thread();
return NULL;
}
static bool find_passthru_name(passthru_list::const_return_type eElement, text_info nName)
{ return nName && eElement.sender == nName; }
void __monitor_update_hook(const struct monitor_update_data *dData)
{
if (!accept_passthru) return;
if (dData && (dData->event_type & monitor_remove) &&
(dData->event_type & (monitor_registered_clients | monitor_registered_services)))
{
info_list current_data = dData->event_data;
if (current_data) while (*current_data)
{
char delimiter[] = { standard_delimiter_char, 0x00 };
std::string copied_data = *current_data++;
char *tokens = &copied_data[0];
strsep(&tokens, delimiter); //discard pid
text_info deregister_name = strsep(&tokens, delimiter);
if (!deregister_name || !strlen(deregister_name)) continue;
unreserve_socket(-1, deregister_name);
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
thread_list.f_remove_pattern(deregister_name, &find_passthru_name);
pthread_mutex_unlock(thread_list_mutex);
}
}
}
}
<commit_msg>gamma.8 - minor update to passthru cleanup in socket forwarders<commit_after>/* This software is released under the BSD License.
|
| Copyright (c) 2011, Kevin P. Barry [the resourcerver project]
| All rights reserved.
|
| Redistribution and use in source and binary forms, with or without
| modification, are permitted provided that the following conditions are met:
|
| - Redistributions of source code must retain the above copyright notice, this
| list of conditions and the following disclaimer.
|
| - Redistributions in binary form must reproduce the above copyright notice,
| this list of conditions and the following disclaimer in the documentation
| and/or other materials provided with the distribution.
|
| - Neither the name of the Resourcerver Project nor the names of its
| contributors may be used to endorse or promote products derived from this
| software without specific prior written permission.
|
| THIS SOFTWARE IS PROVIDED BY THE 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.
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
extern "C" {
#include "ipc-passthru.h"
}
extern "C" {
#include "param.h"
#include "attributes.h"
#include "api/client-timing.h"
#include "api/monitor-client.h"
#include "api/command-queue.h"
#include "plugins/rsvp-passthru-hook.h"
}
#include <string>
#include <string.h> //'strlen', 'strsep'
#include <unistd.h> //'close', 'read', 'write'
#include <fcntl.h> //'fcntl', open modes
#include <errno.h> //'errno'
#include <stddef.h> //'offsetof'
#include <sys/stat.h> //'stat'
#include <sys/socket.h> //sockets
#include <sys/un.h> //socket macros
#include "external/clist.hpp"
#include "global/condition-block.hpp"
extern "C" {
#include "messages.h"
#include "socket-table.h"
#include "security-filter.h"
}
struct passthru_specs;
typedef data::clist <passthru_specs> passthru_list;
static passthru_list thread_list;
static auto_mutex thread_list_mutex;
static bool accept_passthru = false;
void passthru_setup()
{
if (accept_passthru) return;
command_handle new_monitor = set_monitor_flags(monitor_registered_clients | monitor_registered_services);
command_reference monitor_status = send_command(new_monitor);
destroy_command(new_monitor);
accept_passthru = wait_command_event(monitor_status, event_complete, local_default_timeout()) & event_complete;
if (!accept_passthru)
log_message_passthru_disabled();
clear_command_status(monitor_status);
}
struct passthru_specs
{
passthru_specs() : incoming(), outgoing(), socket(-1), connection(-1), reference(NULL) {}
void run_thread()
{
char buffer[PARAM_MAX_INPUT_SECTION];
ssize_t current_size;
if (pthread_equal(incoming, pthread_self()))
{
send_short_func filter = send_command_filter();
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
while ((current_size = read(socket, buffer, sizeof buffer)) != 0)
{
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
pthread_testcancel();
if (current_size < 0 && errno != EINTR) break;
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
current_size = filter?
(*filter)(reference, connection, buffer, current_size) :
write(connection, buffer, current_size);
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (current_size < 0 && errno != EINTR) break;
}
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
incoming = pthread_t();
pthread_detach(pthread_self());
pthread_mutex_unlock(thread_list_mutex);
}
}
else if (pthread_equal(outgoing, pthread_self()))
{
receive_short_func filter = receive_command_filter();
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
while ((current_size = filter?
(*filter)(reference, connection, buffer, sizeof buffer) :
read(connection, buffer, sizeof buffer) ) != 0)
{
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
pthread_testcancel();
if (current_size < 0 && errno != EINTR) break;
if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0) return;
current_size = write(socket, buffer, current_size);
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (current_size < 0 && errno != EINTR) break;
}
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return;
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
outgoing = pthread_t();
pthread_detach(pthread_self());
pthread_mutex_unlock(thread_list_mutex);
}
}
}
~passthru_specs()
{
if (channel.size() || sender.size())
log_message_steal_channel_exit(channel.c_str(), sender.c_str());
if (!pthread_equal(incoming, pthread_t())) pthread_cancel(incoming);
if (!pthread_equal(outgoing, pthread_t())) pthread_cancel(outgoing);
if (socket >= 0) shutdown(socket, SHUT_RDWR);
if (connection >= 0)
{
disconnect_general(reference, connection);
shutdown(connection, SHUT_RDWR);
}
}
pthread_t incoming, outgoing;
int socket, connection;
socket_reference reference;
std::string channel, socket_name, sender;
};
static int connect_to_socket(text_info);
static void *passthru_thread(void*);
void exit_passthru_threads()
{
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
thread_list.reset_list();
pthread_mutex_unlock(thread_list_mutex);
}
}
command_event __rsvp_passthru_hook_reserve_channel(const struct passthru_source_info *sSource, text_info nName)
{
if (!sSource) return event_rejected;
log_message_incoming_reserve_channel(sSource, nName);
if (!accept_passthru)
log_message_reserve_channel_deny(nName, sSource->sender);
int file_number = find_socket(nName, sSource->sender);
if (file_number < 0 || !reserve_socket(file_number, sSource->sender))
{
log_message_reserve_channel_deny(nName, sSource->sender);
return event_error;
}
else
{
log_message_reserve_channel(nName, sSource->sender);
return event_complete;
}
}
command_event __rsvp_passthru_hook_unreserve_channel(const struct passthru_source_info *sSource, text_info nName)
{
if (!sSource) return event_rejected;
log_message_incoming_unreserve_channel(sSource, nName);
if (!accept_passthru)
log_message_unreserve_channel_deny(nName, sSource->sender);
int file_number = find_socket(nName, sSource->sender);
if (file_number < 0 || !unreserve_socket(file_number, sSource->sender))
{
log_message_unreserve_channel_deny(nName, sSource->sender);
return event_error;
}
else
{
log_message_unreserve_channel(nName, sSource->sender);
return event_complete;
}
}
command_event __rsvp_passthru_hook_steal_channel(const struct passthru_source_info *sSource, text_info nName, text_info sSocket)
{
if (!sSource) return event_rejected;
//NOTE: not restricted to local forwarders; this applies to net forwarders, also
#ifdef PARAM_ABSOLUTE_LOCAL_SOCKETS
if (strlen(sSocket) < 1 || sSocket[0] != '/')
{
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
return event_rejected;
}
#endif
log_message_incoming_steal_channel(sSource, nName, sSocket);
if (!accept_passthru)
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
socket_reference reference = NULL;
int file_number = find_socket(nName, sSource->sender);
if (file_number < 0)
{
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
return event_error;
}
int passthru_socket = -1;
if ((passthru_socket = connect_to_socket(sSocket)) < 0 ||
!steal_socket(file_number, sSource->sender, &reference))
{
log_message_steal_channel_deny(nName, sSocket, sSource->sender);
if (passthru_socket >= 0) close(passthru_socket);
return event_error;
}
log_message_steal_channel(nName, sSocket, sSource->sender);
int current_state = fcntl(file_number, F_GETFL);
fcntl(file_number, F_SETFL, current_state & ~O_NONBLOCK);
if (!thread_list_mutex.valid() || pthread_mutex_lock(thread_list_mutex) != 0) return event_error;
passthru_specs *new_passthru = &thread_list.add_element();
new_passthru->socket = passthru_socket;
new_passthru->connection = file_number;
new_passthru->reference = reference;
new_passthru->channel = nName;
new_passthru->socket_name = sSocket;
new_passthru->sender = sSource->sender;
bool success = true;
success &= pthread_create(&new_passthru->incoming, NULL, &passthru_thread,
static_cast <passthru_specs*> (new_passthru)) == 0;
success &= pthread_create(&new_passthru->outgoing, NULL, &passthru_thread,
static_cast <passthru_specs*> (new_passthru)) == 0;
pthread_mutex_unlock(thread_list_mutex);
return success? event_complete : event_error;
}
static int connect_to_socket(text_info sSocket)
{
struct stat file_status;
if (stat(sSocket, &file_status) < 0 || !S_ISSOCK(file_status.st_mode)) return -1;
/*create socket*/
struct sockaddr_un new_address;
size_t new_length = 0;
int new_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
if (new_socket < 0) return -1;
int current_state = fcntl(new_socket, F_GETFL);
fcntl(new_socket, F_SETFL, current_state | O_NONBLOCK);
current_state = fcntl(new_socket, F_GETFD);
fcntl(new_socket, F_SETFD, current_state | FD_CLOEXEC);
/*connect socket*/
new_address.sun_family = AF_LOCAL;
strncpy(new_address.sun_path, sSocket, sizeof new_address.sun_path);
new_length = (offsetof(struct sockaddr_un, sun_path) + SUN_LEN(&new_address) + 1);
int outcome = 0;
while ((outcome = connect(new_socket, (struct sockaddr*) &new_address, new_length)) < 0 && errno == EINTR);
if (outcome < 0)
{
close(new_socket);
return -1;
}
current_state = fcntl(new_socket, F_GETFL);
fcntl(new_socket, F_SETFL, current_state & ~O_NONBLOCK);
return new_socket;
}
static bool find_passthru_specs(passthru_list::const_return_type eElement, const passthru_specs *sSpecs)
{ return &eElement == sSpecs; }
static void *passthru_thread(void *sSpecs)
{
if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL;
if (!sSpecs) return NULL;
passthru_specs *specs = (passthru_specs*) sSpecs;
specs->run_thread();
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
thread_list.f_remove_pattern(specs, &find_passthru_specs);
pthread_mutex_unlock(thread_list_mutex);
}
return NULL;
}
static bool find_passthru_name(passthru_list::const_return_type eElement, text_info nName)
{ return nName && eElement.sender == nName; }
void __monitor_update_hook(const struct monitor_update_data *dData)
{
if (!accept_passthru) return;
if (dData && (dData->event_type & monitor_remove) &&
(dData->event_type & (monitor_registered_clients | monitor_registered_services)))
{
info_list current_data = dData->event_data;
if (current_data) while (*current_data)
{
char delimiter[] = { standard_delimiter_char, 0x00 };
std::string copied_data = *current_data++;
char *tokens = &copied_data[0];
strsep(&tokens, delimiter); //discard pid
text_info deregister_name = strsep(&tokens, delimiter);
if (!deregister_name || !strlen(deregister_name)) continue;
unreserve_socket(-1, deregister_name);
if (thread_list_mutex.valid() && pthread_mutex_lock(thread_list_mutex) == 0)
{
thread_list.f_remove_pattern(deregister_name, &find_passthru_name);
pthread_mutex_unlock(thread_list_mutex);
}
}
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <fcntl.h>
#include <linux/fs.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include "linux_io_calls_no_eventfd.hpp"
#include "arch/linux/arch.hpp"
#include "config/args.hpp"
#include "utils2.hpp"
#include "logger.hpp"
perfmon_counter_t
pm_io_reads_completed("io_reads_completed[ioreads]"),
pm_io_writes_completed("io_writes_completed[iowrites]");
/* Async IO scheduler - the common base */
linux_io_calls_base_t::linux_io_calls_base_t(linux_event_queue_t *queue)
: queue(queue), n_pending(0), io_requests(this)
{
int res;
// Create aio context
aio_context = 0;
res = io_setup(MAX_CONCURRENT_IO_REQUESTS, &aio_context);
guarantee_xerr(res == 0, -res, "Could not setup aio context");
}
linux_io_calls_base_t::~linux_io_calls_base_t()
{
rassert(n_pending == 0);
// Destroy the AIO context
int res = io_destroy(aio_context);
guarantee_xerr(res == 0, -res, "Could not destroy aio context");
}
void linux_io_calls_base_t::aio_notify(iocb *event, int result) {
// Update stats
if (event->aio_lio_opcode == IO_CMD_PREAD) pm_io_reads_completed++;
else pm_io_writes_completed++;
// Schedule the requests we couldn't finish last time
n_pending--;
process_requests();
// Check for failure (because the higher-level code usually doesn't)
if (result != (int)event->u.c.nbytes) {
// Currently AIO is used only for disk files, not sockets.
// Thus, if something fails, we have a good reason to crash
// (note that that is not true for sockets: we should just
// close the socket and cleanup then).
guarantee_xerr(false, -result, "Read or write failed");
}
// Notify the interested party about the event
linux_iocallback_t *callback = (linux_iocallback_t*)event->data;
callback->on_io_complete();
// Free the iocb structure
delete event;
}
void linux_io_calls_base_t::process_requests() {
if (n_pending > TARGET_IO_QUEUE_DEPTH)
return;
int res = 0;
while(!io_requests.queue.empty()) {
res = io_requests.process_request_batch();
if(res < 0)
break;
}
guarantee_xerr(res >= 0 || res == -EAGAIN, -res, "Could not submit IO request");
}
linux_io_calls_base_t::queue_t::queue_t(linux_io_calls_base_t *parent)
: parent(parent)
{
queue.reserve(MAX_CONCURRENT_IO_REQUESTS);
}
int linux_io_calls_base_t::queue_t::process_request_batch() {
// Submit a batch
int res = 0;
if(queue.size() > 0) {
res = io_submit(parent->aio_context,
std::min(queue.size(), size_t(TARGET_IO_QUEUE_DEPTH / 2)),
&queue[0]);
if (res > 0) {
// TODO: erase will cause the vector to shift elements in
// the back. Perhaps we should optimize this somehow.
queue.erase(queue.begin(), queue.begin() + res);
parent->n_pending += res;
} else if (res < 0 && (-res) != EAGAIN) {
logERR("io_submit failed: (%d) %s\n", -res, strerror(-res));
}
}
return res;
}
linux_io_calls_base_t::queue_t::~queue_t() {
rassert(queue.size() == 0);
}
<commit_msg>Don't overcommit aio requests<commit_after>#include <algorithm>
#include <fcntl.h>
#include <linux/fs.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include "linux_io_calls_no_eventfd.hpp"
#include "arch/linux/arch.hpp"
#include "config/args.hpp"
#include "utils2.hpp"
#include "logger.hpp"
perfmon_counter_t
pm_io_reads_completed("io_reads_completed[ioreads]"),
pm_io_writes_completed("io_writes_completed[iowrites]");
/* Async IO scheduler - the common base */
linux_io_calls_base_t::linux_io_calls_base_t(linux_event_queue_t *queue)
: queue(queue), n_pending(0), io_requests(this)
{
int res;
// Create aio context
aio_context = 0;
res = io_setup(MAX_CONCURRENT_IO_REQUESTS, &aio_context);
guarantee_xerr(res == 0, -res, "Could not setup aio context");
}
linux_io_calls_base_t::~linux_io_calls_base_t()
{
rassert(n_pending == 0);
// Destroy the AIO context
int res = io_destroy(aio_context);
guarantee_xerr(res == 0, -res, "Could not destroy aio context");
}
void linux_io_calls_base_t::aio_notify(iocb *event, int result) {
// Update stats
if (event->aio_lio_opcode == IO_CMD_PREAD) pm_io_reads_completed++;
else pm_io_writes_completed++;
// Schedule the requests we couldn't finish last time
n_pending--;
process_requests();
// Check for failure (because the higher-level code usually doesn't)
if (result != (int)event->u.c.nbytes) {
// Currently AIO is used only for disk files, not sockets.
// Thus, if something fails, we have a good reason to crash
// (note that that is not true for sockets: we should just
// close the socket and cleanup then).
guarantee_xerr(false, -result, "Read or write failed");
}
// Notify the interested party about the event
linux_iocallback_t *callback = (linux_iocallback_t*)event->data;
callback->on_io_complete();
// Free the iocb structure
delete event;
}
void linux_io_calls_base_t::process_requests() {
if (n_pending > TARGET_IO_QUEUE_DEPTH)
return;
int res = 0;
while(!io_requests.queue.empty()) {
res = io_requests.process_request_batch();
if(res < 0)
break;
}
guarantee_xerr(res >= 0 || res == -EAGAIN, -res, "Could not submit IO request");
}
linux_io_calls_base_t::queue_t::queue_t(linux_io_calls_base_t *parent)
: parent(parent)
{
queue.reserve(MAX_CONCURRENT_IO_REQUESTS);
}
int linux_io_calls_base_t::queue_t::process_request_batch() {
if (parent->n_pending > TARGET_IO_QUEUE_DEPTH)
return -EAGAIN;
// Submit a batch
int res = 0;
if(queue.size() > 0) {
res = io_submit(parent->aio_context,
std::min(queue.size(), size_t(TARGET_IO_QUEUE_DEPTH / 2)),
&queue[0]);
if (res > 0) {
// TODO: erase will cause the vector to shift elements in
// the back. Perhaps we should optimize this somehow.
queue.erase(queue.begin(), queue.begin() + res);
parent->n_pending += res;
} else if (res < 0 && (-res) != EAGAIN) {
logERR("io_submit failed: (%d) %s\n", -res, strerror(-res));
}
}
return res;
}
linux_io_calls_base_t::queue_t::~queue_t() {
rassert(queue.size() == 0);
}
<|endoftext|> |
<commit_before>
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Per Thomas Hille, Oystein Djuvsland *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliCaloRawAnalyzer.h"
#include "AliCaloBunchInfo.h"
#include "AliCaloFitResults.h"
#include "AliHLTCaloRawAnalyzerComponentv3.h"
#include "AliHLTCaloChannelDataHeaderStruct.h"
#include "AliHLTCaloChannelDataStruct.h"
#include "AliHLTCaloMapper.h"
#include "AliHLTCaloSanityInspector.h"
#include "AliRawReaderMemory.h"
#include "AliCaloRawStreamV3.h"
#include "AliHLTCaloConstantsHandler.h"
#include "AliHLTCaloChannelRawDataStruct.h"
#include "AliLog.h"
#include "TStopwatch.h"
#include <vector>
using namespace std;
ClassImp(AliHLTCaloRawAnalyzerComponentv3);
AliHLTCaloRawAnalyzerComponentv3::AliHLTCaloRawAnalyzerComponentv3(TString det):AliHLTCaloProcessor(),
AliHLTCaloConstantsHandler(det),
fAnalyzerPtr(0),
fMapperPtr(0),
fCurrentSpec(-1),
fDebug(false),
fSanityInspectorPtr(0),
fRawReaderMemoryPtr(0),
fAltroRawStreamPtr(0),
fAlgorithm(0),
fOffset(0),
fBunchSizeCut(0),
fMinPeakPosition(0),
fMaxPeakPosition(100),
fDoPushBadRawData(false),
fDoPushRawData(false),
fRawDataWriter(0)
{
//Constructor
fSanityInspectorPtr = new AliHLTCaloSanityInspector();
if( fDoPushRawData == true )
{
fRawDataWriter = new RawDataWriter(fCaloConstants);
}
fRawReaderMemoryPtr = new AliRawReaderMemory();
fAltroRawStreamPtr = new AliCaloRawStreamV3(fRawReaderMemoryPtr, det);
}
AliHLTCaloRawAnalyzerComponentv3::~AliHLTCaloRawAnalyzerComponentv3()
{
//destructor
delete fRawReaderMemoryPtr;
delete fAltroRawStreamPtr;
delete fRawDataWriter;
delete fSanityInspectorPtr;
}
int
AliHLTCaloRawAnalyzerComponentv3::DoInit( int argc, const char** argv )
{
//See base class for documentation
int iResult=0;
for(int i = 0; i < argc; i++)
{
if(!strcmp("-offset", argv[i]))
{
fOffset = atoi(argv[i+1]);
}
if(!strcmp("-bunchsizecut", argv[i]))
{
fBunchSizeCut = atoi(argv[i+1]);
}
if(!strcmp("-minpeakposition", argv[i]))
{
fMinPeakPosition = atoi(argv[i+1]);
}
if(!strcmp("-maxpeakposition", argv[i]))
{
fMaxPeakPosition = atoi(argv[i+1]);
}
if(!strcmp("-pushrawdata", argv[i]))
{
fDoPushRawData = true;
}
if(!strcmp("-pushbaddata", argv[i]))
{
fDoPushBadRawData = true;
}
if(fDoPushBadRawData && fDoPushRawData)
{
HLTWarning("fDoPushBadRawData and fDoPushRawData in conflict, using fDoPushRawData");
fDoPushBadRawData = false;
}
if(!strcmp("-suppressalilogwarnings", argv[i]))
{
AliLog::SetGlobalLogLevel(AliLog::kError); //PHOS sometimes produces bad data -> Fill up the HLT logs...
}
}
return iResult;
}
int
AliHLTCaloRawAnalyzerComponentv3::DoDeinit()
{
//comment
if(fAltroRawStreamPtr)
{
delete fAltroRawStreamPtr;
fAltroRawStreamPtr = 0;
}
return 0;
}
void
AliHLTCaloRawAnalyzerComponentv3::PrintDebugInfo()
{
//comment
static TStopwatch watch; //CRAP PTH
static double wlast = -1;
static double wcurrent = 0;
if( true == fDebug )
{
if( fCaloEventCount %1000 == 0 )
{
cout << __FILE__ << __LINE__ << " : Processing event " << fCaloEventCount << endl;
wlast = wcurrent;
wcurrent = watch.RealTime();
cout << __FILE__ << __LINE__ << "The event rate is " <<
1000/( wcurrent - wlast ) << " Hz" << endl; watch.Start(kFALSE);
}
}
}
void
AliHLTCaloRawAnalyzerComponentv3::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier )
{
//comment
constBase = sizeof(AliHLTCaloChannelDataHeaderStruct);
inputMultiplier = 1.5;
}
bool
AliHLTCaloRawAnalyzerComponentv3::CheckInputDataType(const AliHLTComponentDataType &datatype)
{
//comment
vector <AliHLTComponentDataType> validTypes;
GetInputDataTypes(validTypes);
for(int i=0; i < validTypes.size(); i++ )
{
if ( datatype == validTypes.at(i) )
{
return true;
}
}
HLTDebug("Invalid Datatype");
return false;
}
int
AliHLTCaloRawAnalyzerComponentv3::DoEvent( const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, vector<AliHLTComponentBlockData>& outputBlocks )
{
//comment
if(!IsDataEvent())
{
size = 0;
return 0;
}
if( true == fDebug )
{ PrintDebugInfo();
};
Int_t blockSize = -1;
UInt_t totSize = 0;
const AliHLTComponentBlockData* iter = NULL;
unsigned long ndx;
for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
{
iter = blocks+ndx;
if( ! CheckInputDataType(iter->fDataType) )
{
continue;
}
if(iter->fSpecification != fCurrentSpec)
{
fCurrentSpec = iter->fSpecification;
InitMapping(iter->fSpecification);
}
blockSize = DoIt(iter, outputPtr, size, totSize); // Processing the block
totSize += blockSize; //Keeping track of the used size
AliHLTComponentBlockData bdChannelData;
FillBlockData( bdChannelData );
bdChannelData.fOffset = 0; //FIXME
bdChannelData.fSize = blockSize;
bdChannelData.fDataType = GetOutputDataType();
bdChannelData.fSpecification = iter->fSpecification;
outputBlocks.push_back(bdChannelData);
outputPtr += blockSize; //Updating position of the output buffer
}
fCaloEventCount++;
size = totSize; //telling the framework how much buffer space we have used.
return 0;
}//end DoEvent
Int_t
AliHLTCaloRawAnalyzerComponentv3::DoIt(const AliHLTComponentBlockData* iter, AliHLTUInt8_t* outputPtr, const AliHLTUInt32_t size, UInt_t& totSize)
{
//comment
int tmpsize= 0;
Int_t crazyness = 0;
Int_t nSamples = 0;
Short_t channelCount = 0;
AliHLTCaloChannelDataHeaderStruct *channelDataHeaderPtr = reinterpret_cast<AliHLTCaloChannelDataHeaderStruct*>(outputPtr);
AliHLTCaloChannelDataStruct *channelDataPtr = reinterpret_cast<AliHLTCaloChannelDataStruct*>(outputPtr+sizeof(AliHLTCaloChannelDataHeaderStruct));
totSize += sizeof( AliHLTCaloChannelDataHeaderStruct );
fRawReaderMemoryPtr->SetMemory( reinterpret_cast<UChar_t*>( iter->fPtr ), static_cast<ULong_t>( iter->fSize ) );
fRawReaderMemoryPtr->SetEquipmentID( fMapperPtr->GetDDLFromSpec( iter->fSpecification) + fCaloConstants->GetDDLOFFSET() );
fRawReaderMemoryPtr->Reset();
fRawReaderMemoryPtr->NextEvent();
if( fDoPushRawData == true)
{
fRawDataWriter->NewEvent( );
}
if(fAltroRawStreamPtr->NextDDL())
{
int cnt = 0;
fOffset = 0;
while( fAltroRawStreamPtr->NextChannel() )
{
if( fAltroRawStreamPtr->GetHWAddress() < 128 || ( fAltroRawStreamPtr->GetHWAddress() ^ 0x800) < 128 )
{
continue;
}
else
{
++ cnt;
UShort_t* firstBunchPtr = 0;
int chId = fMapperPtr->GetChannelID(iter->fSpecification, fAltroRawStreamPtr->GetHWAddress());
if( fDoPushRawData == true)
{
fRawDataWriter->SetChannelId( chId );
}
vector <AliCaloBunchInfo> bvctr;
while( fAltroRawStreamPtr->NextBunch() == true )
{
bvctr.push_back( AliCaloBunchInfo( fAltroRawStreamPtr->GetStartTimeBin(),
fAltroRawStreamPtr->GetBunchLength(),
fAltroRawStreamPtr->GetSignals() ) );
nSamples = fAltroRawStreamPtr->GetBunchLength();
if( fDoPushRawData == true)
{
fRawDataWriter->WriteBunchData( fAltroRawStreamPtr->GetSignals(),
nSamples, fAltroRawStreamPtr->GetEndTimeBin() );
}
firstBunchPtr = const_cast< UShort_t* >( fAltroRawStreamPtr->GetSignals() );
}
totSize += sizeof( AliHLTCaloChannelDataStruct );
if(totSize > size)
{
HLTError("Buffer overflow: Trying to write data of size: %d bytes. Output buffer available: %d bytes.", totSize, size);
return -1;
}
AliCaloFitResults res = fAnalyzerPtr->Evaluate( bvctr, fAltroRawStreamPtr->GetAltroCFG1(),
fAltroRawStreamPtr->GetAltroCFG2() );
HLTDebug("Channel energy: %f, max sig: %d, gain = %d, x = %d, z = %d", res.GetAmp(), res.GetMaxSig(),
(chId >> 12)&0x1, chId&0x3f, (chId >> 6)&0x3f);
{
channelDataPtr->fChannelID = chId;
channelDataPtr->fEnergy = static_cast<Float_t>( res.GetAmp() ) - fOffset;
channelDataPtr->fTime = static_cast<Float_t>( res.GetTof() );
channelDataPtr->fCrazyness = static_cast<Short_t>(crazyness);
channelCount++;
channelDataPtr++; // Updating position of the free output.
}
}
}
if( fDoPushRawData == true)
{
fRawDataWriter->NewChannel();
}
}
channelDataHeaderPtr->fNChannels = channelCount;
channelDataHeaderPtr->fAlgorithm = fAlgorithm;
channelDataHeaderPtr->fInfo = 0;
if( fDoPushRawData == true)
{
tmpsize += fRawDataWriter->CopyBufferToSharedMemory( (UShort_t *)channelDataPtr, size, totSize);
}
channelDataHeaderPtr->fHasRawData = fDoPushRawData;
HLTDebug("Number of channels: %d", channelCount);
tmpsize += sizeof(AliHLTCaloChannelDataStruct)*channelCount + sizeof(AliHLTCaloChannelDataHeaderStruct);
return tmpsize;
}
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::RawDataWriter(AliHLTCaloConstants* cConst) :
fRawDataBuffer(0),
fCurrentChannelSize(0),
fBufferIndex(0),
fBufferSize( 64*56*cConst->GetNGAINS()*cConst->GetALTROMAXSAMPLES() +1000 ),
fCurrentChannelIdPtr(0),
fCurrentChannelSizePtr(0),
fCurrentChannelDataPtr(0),
fTotalSize(0)
{
//comment
fRawDataBuffer = new UShort_t[fBufferSize];
Init();
}
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::~RawDataWriter()
{
delete [] fRawDataBuffer;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::Init()
{
//comment
fCurrentChannelIdPtr = fRawDataBuffer;
fCurrentChannelSizePtr = fRawDataBuffer +1;
fCurrentChannelDataPtr = fRawDataBuffer +2;
ResetBuffer();
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::NewEvent()
{
//comment
Init();
fTotalSize = 0;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::NewChannel( )
{
//comment
*fCurrentChannelSizePtr = fCurrentChannelSize;
fCurrentChannelIdPtr += fCurrentChannelSize;
fCurrentChannelSizePtr += fCurrentChannelSize;
fCurrentChannelDataPtr += fCurrentChannelSize;
fBufferIndex = 0;
fCurrentChannelSize = 2;
fTotalSize += 2;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::WriteBunchData(const UShort_t *bunchdata, const int length, const UInt_t starttimebin )
{
fCurrentChannelDataPtr[fBufferIndex] = starttimebin;
fCurrentChannelSize ++;
fBufferIndex++;
fCurrentChannelDataPtr[fBufferIndex] = length;
fCurrentChannelSize ++;
fBufferIndex++;
fTotalSize +=2;
for(int i=0; i < length; i++)
{
fCurrentChannelDataPtr[ fBufferIndex + i ] = bunchdata[i];
}
fCurrentChannelSize += length;
fTotalSize += length;
fBufferIndex += length;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::SetChannelId( const UShort_t channeldid )
{
*fCurrentChannelIdPtr = channeldid;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::ResetBuffer()
{
for(int i=0; i < fBufferSize ; i++ )
{
fRawDataBuffer[i] = 0;
}
}
int
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::CopyBufferToSharedMemory(UShort_t *memPtr, const int sizetotal, const int sizeused )
{
int sizerequested = (sizeof(int)*fTotalSize + sizeused);
if( sizerequested > sizetotal )
{
return 0;
}
else
{
for(int i=0; i < fTotalSize; i++)
{
memPtr[i] = fRawDataBuffer[i];
}
return fTotalSize;
}
}
<commit_msg>- fixing compilation warning<commit_after>
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Per Thomas Hille, Oystein Djuvsland *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliCaloRawAnalyzer.h"
#include "AliCaloBunchInfo.h"
#include "AliCaloFitResults.h"
#include "AliHLTCaloRawAnalyzerComponentv3.h"
#include "AliHLTCaloChannelDataHeaderStruct.h"
#include "AliHLTCaloChannelDataStruct.h"
#include "AliHLTCaloMapper.h"
#include "AliHLTCaloSanityInspector.h"
#include "AliRawReaderMemory.h"
#include "AliCaloRawStreamV3.h"
#include "AliHLTCaloConstantsHandler.h"
#include "AliHLTCaloChannelRawDataStruct.h"
#include "AliLog.h"
#include "TStopwatch.h"
#include <vector>
using namespace std;
ClassImp(AliHLTCaloRawAnalyzerComponentv3);
AliHLTCaloRawAnalyzerComponentv3::AliHLTCaloRawAnalyzerComponentv3(TString det):AliHLTCaloProcessor(),
AliHLTCaloConstantsHandler(det),
fAnalyzerPtr(0),
fMapperPtr(0),
fCurrentSpec(-1),
fDebug(false),
fSanityInspectorPtr(0),
fRawReaderMemoryPtr(0),
fAltroRawStreamPtr(0),
fAlgorithm(0),
fOffset(0),
fBunchSizeCut(0),
fMinPeakPosition(0),
fMaxPeakPosition(100),
fDoPushBadRawData(false),
fDoPushRawData(false),
fRawDataWriter(0)
{
//Constructor
fSanityInspectorPtr = new AliHLTCaloSanityInspector();
if( fDoPushRawData == true )
{
fRawDataWriter = new RawDataWriter(fCaloConstants);
}
fRawReaderMemoryPtr = new AliRawReaderMemory();
fAltroRawStreamPtr = new AliCaloRawStreamV3(fRawReaderMemoryPtr, det);
}
AliHLTCaloRawAnalyzerComponentv3::~AliHLTCaloRawAnalyzerComponentv3()
{
//destructor
delete fRawReaderMemoryPtr;
delete fAltroRawStreamPtr;
delete fRawDataWriter;
delete fSanityInspectorPtr;
}
int
AliHLTCaloRawAnalyzerComponentv3::DoInit( int argc, const char** argv )
{
//See base class for documentation
int iResult=0;
for(int i = 0; i < argc; i++)
{
if(!strcmp("-offset", argv[i]))
{
fOffset = atoi(argv[i+1]);
}
if(!strcmp("-bunchsizecut", argv[i]))
{
fBunchSizeCut = atoi(argv[i+1]);
}
if(!strcmp("-minpeakposition", argv[i]))
{
fMinPeakPosition = atoi(argv[i+1]);
}
if(!strcmp("-maxpeakposition", argv[i]))
{
fMaxPeakPosition = atoi(argv[i+1]);
}
if(!strcmp("-pushrawdata", argv[i]))
{
fDoPushRawData = true;
}
if(!strcmp("-pushbaddata", argv[i]))
{
fDoPushBadRawData = true;
}
if(fDoPushBadRawData && fDoPushRawData)
{
HLTWarning("fDoPushBadRawData and fDoPushRawData in conflict, using fDoPushRawData");
fDoPushBadRawData = false;
}
if(!strcmp("-suppressalilogwarnings", argv[i]))
{
AliLog::SetGlobalLogLevel(AliLog::kError); //PHOS sometimes produces bad data -> Fill up the HLT logs...
}
}
return iResult;
}
int
AliHLTCaloRawAnalyzerComponentv3::DoDeinit()
{
//comment
if(fAltroRawStreamPtr)
{
delete fAltroRawStreamPtr;
fAltroRawStreamPtr = 0;
}
return 0;
}
void
AliHLTCaloRawAnalyzerComponentv3::PrintDebugInfo()
{
//comment
static TStopwatch watch; //CRAP PTH
static double wlast = -1;
static double wcurrent = 0;
if( true == fDebug )
{
if( fCaloEventCount %1000 == 0 )
{
cout << __FILE__ << __LINE__ << " : Processing event " << fCaloEventCount << endl;
wlast = wcurrent;
wcurrent = watch.RealTime();
cout << __FILE__ << __LINE__ << "The event rate is " <<
1000/( wcurrent - wlast ) << " Hz" << endl; watch.Start(kFALSE);
}
}
}
void
AliHLTCaloRawAnalyzerComponentv3::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier )
{
//comment
constBase = sizeof(AliHLTCaloChannelDataHeaderStruct);
inputMultiplier = 1.5;
}
bool
AliHLTCaloRawAnalyzerComponentv3::CheckInputDataType(const AliHLTComponentDataType &datatype)
{
//comment
vector <AliHLTComponentDataType> validTypes;
GetInputDataTypes(validTypes);
for(UInt_t i=0; i < validTypes.size(); i++ )
{
if ( datatype == validTypes.at(i) )
{
return true;
}
}
HLTDebug("Invalid Datatype");
return false;
}
int
AliHLTCaloRawAnalyzerComponentv3::DoEvent( const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, vector<AliHLTComponentBlockData>& outputBlocks )
{
//comment
if(!IsDataEvent())
{
size = 0;
return 0;
}
if( true == fDebug )
{ PrintDebugInfo();
};
Int_t blockSize = -1;
UInt_t totSize = 0;
const AliHLTComponentBlockData* iter = NULL;
unsigned long ndx;
for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
{
iter = blocks+ndx;
if( ! CheckInputDataType(iter->fDataType) )
{
continue;
}
if(iter->fSpecification != fCurrentSpec)
{
fCurrentSpec = iter->fSpecification;
InitMapping(iter->fSpecification);
}
blockSize = DoIt(iter, outputPtr, size, totSize); // Processing the block
totSize += blockSize; //Keeping track of the used size
AliHLTComponentBlockData bdChannelData;
FillBlockData( bdChannelData );
bdChannelData.fOffset = 0; //FIXME
bdChannelData.fSize = blockSize;
bdChannelData.fDataType = GetOutputDataType();
bdChannelData.fSpecification = iter->fSpecification;
outputBlocks.push_back(bdChannelData);
outputPtr += blockSize; //Updating position of the output buffer
}
fCaloEventCount++;
size = totSize; //telling the framework how much buffer space we have used.
return 0;
}//end DoEvent
Int_t
AliHLTCaloRawAnalyzerComponentv3::DoIt(const AliHLTComponentBlockData* iter, AliHLTUInt8_t* outputPtr, const AliHLTUInt32_t size, UInt_t& totSize)
{
//comment
int tmpsize= 0;
Int_t crazyness = 0;
Int_t nSamples = 0;
Short_t channelCount = 0;
AliHLTCaloChannelDataHeaderStruct *channelDataHeaderPtr = reinterpret_cast<AliHLTCaloChannelDataHeaderStruct*>(outputPtr);
AliHLTCaloChannelDataStruct *channelDataPtr = reinterpret_cast<AliHLTCaloChannelDataStruct*>(outputPtr+sizeof(AliHLTCaloChannelDataHeaderStruct));
totSize += sizeof( AliHLTCaloChannelDataHeaderStruct );
fRawReaderMemoryPtr->SetMemory( reinterpret_cast<UChar_t*>( iter->fPtr ), static_cast<ULong_t>( iter->fSize ) );
fRawReaderMemoryPtr->SetEquipmentID( fMapperPtr->GetDDLFromSpec( iter->fSpecification) + fCaloConstants->GetDDLOFFSET() );
fRawReaderMemoryPtr->Reset();
fRawReaderMemoryPtr->NextEvent();
if( fDoPushRawData == true)
{
fRawDataWriter->NewEvent( );
}
if(fAltroRawStreamPtr->NextDDL())
{
int cnt = 0;
fOffset = 0;
while( fAltroRawStreamPtr->NextChannel() )
{
if( fAltroRawStreamPtr->GetHWAddress() < 128 || ( fAltroRawStreamPtr->GetHWAddress() ^ 0x800) < 128 )
{
continue;
}
else
{
++ cnt;
UShort_t* firstBunchPtr = 0;
int chId = fMapperPtr->GetChannelID(iter->fSpecification, fAltroRawStreamPtr->GetHWAddress());
if( fDoPushRawData == true)
{
fRawDataWriter->SetChannelId( chId );
}
vector <AliCaloBunchInfo> bvctr;
while( fAltroRawStreamPtr->NextBunch() == true )
{
bvctr.push_back( AliCaloBunchInfo( fAltroRawStreamPtr->GetStartTimeBin(),
fAltroRawStreamPtr->GetBunchLength(),
fAltroRawStreamPtr->GetSignals() ) );
nSamples = fAltroRawStreamPtr->GetBunchLength();
if( fDoPushRawData == true)
{
fRawDataWriter->WriteBunchData( fAltroRawStreamPtr->GetSignals(),
nSamples, fAltroRawStreamPtr->GetEndTimeBin() );
}
firstBunchPtr = const_cast< UShort_t* >( fAltroRawStreamPtr->GetSignals() );
}
totSize += sizeof( AliHLTCaloChannelDataStruct );
if(totSize > size)
{
HLTError("Buffer overflow: Trying to write data of size: %d bytes. Output buffer available: %d bytes.", totSize, size);
return -1;
}
AliCaloFitResults res = fAnalyzerPtr->Evaluate( bvctr, fAltroRawStreamPtr->GetAltroCFG1(),
fAltroRawStreamPtr->GetAltroCFG2() );
HLTDebug("Channel energy: %f, max sig: %d, gain = %d, x = %d, z = %d", res.GetAmp(), res.GetMaxSig(),
(chId >> 12)&0x1, chId&0x3f, (chId >> 6)&0x3f);
{
channelDataPtr->fChannelID = chId;
channelDataPtr->fEnergy = static_cast<Float_t>( res.GetAmp() ) - fOffset;
channelDataPtr->fTime = static_cast<Float_t>( res.GetTof() );
channelDataPtr->fCrazyness = static_cast<Short_t>(crazyness);
channelCount++;
channelDataPtr++; // Updating position of the free output.
}
}
}
if( fDoPushRawData == true)
{
fRawDataWriter->NewChannel();
}
}
channelDataHeaderPtr->fNChannels = channelCount;
channelDataHeaderPtr->fAlgorithm = fAlgorithm;
channelDataHeaderPtr->fInfo = 0;
if( fDoPushRawData == true)
{
tmpsize += fRawDataWriter->CopyBufferToSharedMemory( (UShort_t *)channelDataPtr, size, totSize);
}
channelDataHeaderPtr->fHasRawData = fDoPushRawData;
HLTDebug("Number of channels: %d", channelCount);
tmpsize += sizeof(AliHLTCaloChannelDataStruct)*channelCount + sizeof(AliHLTCaloChannelDataHeaderStruct);
return tmpsize;
}
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::RawDataWriter(AliHLTCaloConstants* cConst) :
fRawDataBuffer(0),
fCurrentChannelSize(0),
fBufferIndex(0),
fBufferSize( 64*56*cConst->GetNGAINS()*cConst->GetALTROMAXSAMPLES() +1000 ),
fCurrentChannelIdPtr(0),
fCurrentChannelSizePtr(0),
fCurrentChannelDataPtr(0),
fTotalSize(0)
{
//comment
fRawDataBuffer = new UShort_t[fBufferSize];
Init();
}
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::~RawDataWriter()
{
delete [] fRawDataBuffer;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::Init()
{
//comment
fCurrentChannelIdPtr = fRawDataBuffer;
fCurrentChannelSizePtr = fRawDataBuffer +1;
fCurrentChannelDataPtr = fRawDataBuffer +2;
ResetBuffer();
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::NewEvent()
{
//comment
Init();
fTotalSize = 0;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::NewChannel( )
{
//comment
*fCurrentChannelSizePtr = fCurrentChannelSize;
fCurrentChannelIdPtr += fCurrentChannelSize;
fCurrentChannelSizePtr += fCurrentChannelSize;
fCurrentChannelDataPtr += fCurrentChannelSize;
fBufferIndex = 0;
fCurrentChannelSize = 2;
fTotalSize += 2;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::WriteBunchData(const UShort_t *bunchdata, const int length, const UInt_t starttimebin )
{
fCurrentChannelDataPtr[fBufferIndex] = starttimebin;
fCurrentChannelSize ++;
fBufferIndex++;
fCurrentChannelDataPtr[fBufferIndex] = length;
fCurrentChannelSize ++;
fBufferIndex++;
fTotalSize +=2;
for(int i=0; i < length; i++)
{
fCurrentChannelDataPtr[ fBufferIndex + i ] = bunchdata[i];
}
fCurrentChannelSize += length;
fTotalSize += length;
fBufferIndex += length;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::SetChannelId( const UShort_t channeldid )
{
*fCurrentChannelIdPtr = channeldid;
}
void
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::ResetBuffer()
{
for(int i=0; i < fBufferSize ; i++ )
{
fRawDataBuffer[i] = 0;
}
}
int
AliHLTCaloRawAnalyzerComponentv3::RawDataWriter::CopyBufferToSharedMemory(UShort_t *memPtr, const int sizetotal, const int sizeused )
{
int sizerequested = (sizeof(int)*fTotalSize + sizeused);
if( sizerequested > sizetotal )
{
return 0;
}
else
{
for(int i=0; i < fTotalSize; i++)
{
memPtr[i] = fRawDataBuffer[i];
}
return fTotalSize;
}
}
<|endoftext|> |
<commit_before>/* $Id$ */
/*
* Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*****************************************************************************
SessionManager.cpp
Keeps track of the sessions within SoftHSM. The sessions are stored in a
vector. When a session is closed, its spot in the vector will be replaced
with NULL. Because we want to keep track of the session ID which is
equal to its location in the vector. New sessions will first fill up the NULL
locations and if there is no empty spots, then they are added to the end.
*****************************************************************************/
#include "SessionManager.h"
#include "log.h"
// Initialise the one-and-only instance
std::auto_ptr<SessionManager> SessionManager::instance(NULL);
// Return the one-and-only instance
SessionManager* SessionManager::i()
{
if (instance.get() == NULL)
{
instance = std::auto_ptr<SessionManager>(new SessionManager());
}
return instance.get();
}
// Constructor
SessionManager::SessionManager()
{
sessionsMutex = MutexFactory::i()->getMutex();
}
// Destructor
SessionManager::~SessionManager()
{
std::vector<Session*> toDelete = sessions;
sessions.clear();
for (std::vector<Session*>::iterator i = toDelete.begin(); i != toDelete.end(); i++)
{
if (*i != NULL) delete *i;
}
MutexFactory::i()->recycleMutex(sessionsMutex);
}
// Open a new session
CK_RV SessionManager::openSession
(
Slot *slot,
CK_FLAGS flags,
CK_VOID_PTR pApplication,
CK_NOTIFY notify,
CK_SESSION_HANDLE_PTR phSession
)
{
if (slot == NULL) return CKR_SLOT_ID_INVALID;
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// TODO: A lot of checks
// Create the session
// TODO: Save more information in the session
Session *session = new Session();
// First fill any empty spot in the list
for (std::vector<Session*>::iterator i = sessions.begin(); i != sessions.end(); i++)
{
if (*i != NULL)
{
continue;
}
*i = session;
return CKR_OK;
}
// Or add it to the end
sessions.push_back(session);
return CKR_OK;
}
// Close a session
CK_RV SessionManager::closeSession(CK_SESSION_HANDLE hSession)
{
if (hSession == CK_INVALID_HANDLE)
{
return CKR_SESSION_HANDLE_INVALID;
}
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// Check if we are out of range
if (sessions.size() <= hSession) return CKR_SESSION_HANDLE_INVALID;
// Check if it is a closed session
if (sessions[hSession-1] == NULL) return CKR_SESSION_HANDLE_INVALID;
// TODO: Logout if this is the last session on the token
// TODO: Remove session objects
// Close the session
delete sessions[hSession-1];
sessions[hSession-1] = NULL;
return CKR_OK;
}
// Close all sessions
CK_RV SessionManager::closeAllSessions(Slot *slot)
{
if (slot == NULL) return CKR_SLOT_ID_INVALID;
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// TODO: Close all sessions on this slot
// TODO: Remove session objects
// TODO: Logout from the token
return CKR_FUNCTION_NOT_SUPPORTED;
}
// Get session info
CK_RV SessionManager::getSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo)
{
// Get the session
Session *session = getSession(hSession);
if (session == NULL) return CKR_SESSION_HANDLE_INVALID;
return session->getSessionInfo(pInfo);
}
// Get the session
Session* SessionManager::getSession(CK_SESSION_HANDLE hSession)
{
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// We do not want to get a negative number below
if (hSession == CK_INVALID_HANDLE) return NULL;
// Check if we are out of range
if (sessions.size() <= hSession) return NULL;
return sessions[hSession - 1];
}
<commit_msg>Also give back a handle<commit_after>/* $Id$ */
/*
* Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*****************************************************************************
SessionManager.cpp
Keeps track of the sessions within SoftHSM. The sessions are stored in a
vector. When a session is closed, its spot in the vector will be replaced
with NULL. Because we want to keep track of the session ID which is
equal to its location in the vector. New sessions will first fill up the NULL
locations and if there is no empty spots, then they are added to the end.
*****************************************************************************/
#include "SessionManager.h"
#include "log.h"
// Initialise the one-and-only instance
std::auto_ptr<SessionManager> SessionManager::instance(NULL);
// Return the one-and-only instance
SessionManager* SessionManager::i()
{
if (instance.get() == NULL)
{
instance = std::auto_ptr<SessionManager>(new SessionManager());
}
return instance.get();
}
// Constructor
SessionManager::SessionManager()
{
sessionsMutex = MutexFactory::i()->getMutex();
}
// Destructor
SessionManager::~SessionManager()
{
std::vector<Session*> toDelete = sessions;
sessions.clear();
for (std::vector<Session*>::iterator i = toDelete.begin(); i != toDelete.end(); i++)
{
if (*i != NULL) delete *i;
}
MutexFactory::i()->recycleMutex(sessionsMutex);
}
// Open a new session
CK_RV SessionManager::openSession
(
Slot *slot,
CK_FLAGS flags,
CK_VOID_PTR pApplication,
CK_NOTIFY notify,
CK_SESSION_HANDLE_PTR phSession
)
{
if (phSession == NULL_PTR) return CKR_ARGUMENTS_BAD;
if (slot == NULL) return CKR_SLOT_ID_INVALID;
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// TODO: A lot of checks
// Create the session
// TODO: Save more information in the session
Session *session = new Session();
// First fill any empty spot in the list
for (int i = 0; i < sessions.size(); i++)
{
if (sessions[i] != NULL)
{
continue;
}
sessions[i] = session;
*phSession = i + 1;
return CKR_OK;
}
// Or add it to the end
sessions.push_back(session);
*phSession = sessions.size();
return CKR_OK;
}
// Close a session
CK_RV SessionManager::closeSession(CK_SESSION_HANDLE hSession)
{
if (hSession == CK_INVALID_HANDLE)
{
return CKR_SESSION_HANDLE_INVALID;
}
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// Check if we are out of range
if (sessions.size() <= hSession) return CKR_SESSION_HANDLE_INVALID;
// Check if it is a closed session
if (sessions[hSession-1] == NULL) return CKR_SESSION_HANDLE_INVALID;
// TODO: Logout if this is the last session on the token
// TODO: Remove session objects
// Close the session
delete sessions[hSession-1];
sessions[hSession-1] = NULL;
return CKR_OK;
}
// Close all sessions
CK_RV SessionManager::closeAllSessions(Slot *slot)
{
if (slot == NULL) return CKR_SLOT_ID_INVALID;
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// TODO: Close all sessions on this slot
// TODO: Remove session objects
// TODO: Logout from the token
return CKR_FUNCTION_NOT_SUPPORTED;
}
// Get session info
CK_RV SessionManager::getSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo)
{
// Get the session
Session *session = getSession(hSession);
if (session == NULL) return CKR_SESSION_HANDLE_INVALID;
return session->getSessionInfo(pInfo);
}
// Get the session
Session* SessionManager::getSession(CK_SESSION_HANDLE hSession)
{
// Lock access to the vector
MutexLocker lock(sessionsMutex);
// We do not want to get a negative number below
if (hSession == CK_INVALID_HANDLE) return NULL;
// Check if we are out of range
if (sessions.size() <= hSession) return NULL;
return sessions[hSession - 1];
}
<|endoftext|> |
<commit_before>#include "renderer/opengl/OpenGLTexture.h"
namespace lime {
static int *sAlpha16Table = 0;
bool gFullNPO2Support = false;
bool gPartialNPO2Support = false;
bool NonPO2Supported (bool inNotRepeating) {
static bool tried = false;
//OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC
#ifdef FORCE_NON_PO2
return true;
#endif
if (!tried) {
tried = true;
const char* extensions = (char*)glGetString (GL_EXTENSIONS);
gFullNPO2Support = strstr (extensions, "ARB_texture_non_power_of_two") != 0;
if (!gFullNPO2Support) {
gPartialNPO2Support = strstr (extensions, "GL_APPLE_texture_2D_limited_npot") != 0;
}
//printf("Full non-PO2 support : %d\n", gFullNPO2Support);
//printf("Partial non-PO2 support : %d\n", gPartialNPO2Support);
}
return (gFullNPO2Support || (gPartialNPO2Support && inNotRepeating));
}
void RGBX_to_RGB565 (uint8 *outDest, const uint8 *inSrc, int inPixels) {
unsigned short *dest = (unsigned short *)outDest;
const uint8 *src = inSrc;
for (int x = 0; x < inPixels; x++) {
*dest++ = ((src[0] << 8) & 0xf800) | ((src[1] << 3) & 0x07e0) | ((src[2] >> 3));
src += 4;
}
}
void RGBA_to_RGBA4444 (uint8 *outDest, const uint8 *inSrc, int inPixels) {
unsigned short *dest = (unsigned short *)outDest;
const uint8 *src = inSrc;
for (int x = 0; x < inPixels; x++) {
*dest++ = ((src[0] << 8) & 0xf000) | ((src[1] << 4) & 0x0f00) | ((src[2]) & 0x00f0) | ((src[3] >> 4));
src += 4;
}
}
int *getAlpha16Table () {
if (sAlpha16Table == 0) {
sAlpha16Table = new int[256];
for (int a = 0; a < 256; a++) {
sAlpha16Table[a] = a * (1 << 16) / 255;
}
}
return sAlpha16Table;
}
OpenGLTexture::OpenGLTexture (Surface *inSurface, unsigned int inFlags) {
mPixelWidth = inSurface->Width ();
mPixelHeight = inSurface->Height ();
mDirtyRect = Rect (0, 0);
mContextVersion = gTextureContextVersion;
bool non_po2 = NonPO2Supported (inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2);
//printf("Using non-power-of-2 texture %d\n",non_po2);
int w = non_po2 ? mPixelWidth : UpToPower2 (mPixelWidth);
int h = non_po2 ? mPixelHeight : UpToPower2 (mPixelHeight);
mCanRepeat = IsPower2 (w) && IsPower2 (h);
//__android_log_print(ANDROID_LOG_ERROR, "lime", "NewTexure %d %d", w, h);
mTextureWidth = w;
mTextureHeight = h;
bool usePreAlpha = inFlags & SURF_FLAGS_USE_PREMULTIPLIED_ALPHA;
bool hasPreAlpha = inFlags & SURF_FLAGS_HAS_PREMULTIPLIED_ALPHA;
int *multiplyAlpha = usePreAlpha && !hasPreAlpha ? getAlpha16Table () : 0;
bool copy_required = inSurface->GetBase () && (w != mPixelWidth || h != mPixelHeight || multiplyAlpha);
Surface *load = inSurface;
uint8 *buffer = 0;
PixelFormat fmt = inSurface->Format ();
GLuint store_format = (fmt == pfAlpha ? GL_ALPHA : GL_RGBA);
int pixels = GL_UNSIGNED_BYTE;
int gpuFormat = inSurface->GPUFormat ();
if (!inSurface->GetBase ()) {
if (gpuFormat != fmt)
switch (gpuFormat) {
case pfARGB4444: pixels = GL_UNSIGNED_SHORT_4_4_4_4; break;
case pfRGB565: pixels = GL_UNSIGNED_SHORT_5_6_5; break;
default: pixels = gpuFormat;
}
} else if (gpuFormat == pfARGB4444) {
pixels = GL_UNSIGNED_SHORT_4_4_4_4;
buffer = (uint8 *)malloc (mTextureWidth * mTextureHeight * 2);
for (int y = 0; y < mPixelHeight; y++)
RGBA_to_RGBA4444 (buffer + y * mTextureWidth * 2, inSurface->Row (y), mPixelWidth);
} else if ( gpuFormat == pfRGB565) {
pixels = GL_UNSIGNED_SHORT_5_6_5;
buffer = (uint8 *)malloc (mTextureWidth * mTextureHeight * 2);
for (int y = 0; y < mPixelHeight; y++)
RGBX_to_RGB565 (buffer + y * mTextureWidth * 2, inSurface->Row (y), mPixelWidth);
} else if (copy_required) {
int pw = (inSurface->Format () == pfAlpha ? 1 : 4);
buffer = (uint8 *)malloc (pw * mTextureWidth * mTextureHeight);
for (int y = 0; y < mPixelHeight; y++) {
const uint8 *src = inSurface->Row (y);
uint8 *b = buffer + (mTextureWidth * pw * y);
if (multiplyAlpha) {
for (int x = 0; x < mPixelWidth; x++) {
int a16 = multiplyAlpha[src[3]];
b[0] = (src[0] * a16) >> 16;
b[1] = (src[1] * a16) >> 16;
b[2] = (src[2] * a16) >> 16;
b[3] = src[3];
b += 4;
src += 4;
}
} else {
memcpy (b, src, mPixelWidth * pw);
b += mPixelWidth * pw;
}
// Duplicate last pixel to help with bilinear interpolation
if (w > mPixelWidth)
memcpy (b, buffer + ((mPixelWidth - 1) * pw), pw);
}
// Duplicate last Row to help with bilinear interpolation
if (h != mPixelHeight) {
uint8 *b = buffer + (mTextureWidth * pw * mPixelHeight);
uint8 *b0 = b - (mTextureWidth * pw);
memcpy (b, b0, (mPixelWidth + (w != mPixelWidth)) * pw);
}
} else {
buffer = (uint8 *)inSurface->Row (0);
}
glGenTextures (1, &mTextureID);
// __android_log_print(ANDROID_LOG_ERROR, "lime", "CreateTexture %d (%dx%d)",
// mTextureID, mPixelWidth, mPixelHeight);
glBindTexture (GL_TEXTURE_2D, mTextureID);
mRepeat = mCanRepeat;
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
glTexImage2D (GL_TEXTURE_2D, 0, store_format, w, h, 0, store_format, pixels, buffer);
if (buffer && buffer != inSurface->Row (0))
free (buffer);
mSmooth = true;
#ifndef LIME_GLES
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
#endif
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// TODO: Need replacement call for GLES2?
#ifdef GPH
glTexEnvx (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#endif
#ifndef LIME_FORCE_GLES2
//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#endif
//int err = glGetError();
//printf ("GL texture error: %i", err);
}
OpenGLTexture::~OpenGLTexture () {
if (mTextureID && mContextVersion == gTextureContextVersion && HardwareContext::current) {
//__android_log_print(ANDROID_LOG_ERROR, "lime", "DeleteTexture %d (%dx%d)",
//mTextureID, mPixelWidth, mPixelHeight);
HardwareContext::current->DestroyNativeTexture ((void *)(size_t)mTextureID);
}
}
void OpenGLTexture::Bind (class Surface *inSurface, int inSlot) {
if (inSlot >= 0 && &glActiveTexture) {
glActiveTexture (GL_TEXTURE0 + inSlot);
}
glBindTexture (GL_TEXTURE_2D, mTextureID);
if (gTextureContextVersion != mContextVersion) {
mContextVersion = gTextureContextVersion;
mDirtyRect = Rect (inSurface->Width (), inSurface->Height ());
}
if (inSurface->GetBase () && mDirtyRect.HasPixels ()) {
//__android_log_print(ANDROID_LOG_INFO, "lime", "UpdateDirtyRect! %d %d",
//mPixelWidth, mPixelHeight);
PixelFormat fmt = inSurface->Format ();
GLuint store_format = (fmt == pfAlpha ? GL_ALPHA : GL_RGBA);
glGetError ();
const uint8 *p0 = inSurface->Row (mDirtyRect.y) + (mDirtyRect.x * inSurface->BytesPP ());
#if defined(LIME_GLES)
// TODO: pixel transform & copy rect
for (int y = 0; y < mDirtyRect.h; y++) {
glTexSubImage2D (GL_TEXTURE_2D, 0, mDirtyRect.x, mDirtyRect.y + y, mDirtyRect.w, 1, store_format, GL_UNSIGNED_BYTE, p0 + (y * inSurface->GetStride ()));
}
#else
glPixelStorei (GL_UNPACK_ROW_LENGTH, inSurface->Width ());
glTexSubImage2D (GL_TEXTURE_2D, 0, mDirtyRect.x, mDirtyRect.y, mDirtyRect.w, mDirtyRect.h, store_format, GL_UNSIGNED_BYTE, p0);
glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
#endif
int err = glGetError ();
if (err != GL_NO_ERROR)
ELOG ("GL Error: %d", err);
mDirtyRect = Rect ();
}
}
void OpenGLTexture::BindFlags (bool inRepeat, bool inSmooth) {
if (!mCanRepeat) inRepeat = false;
if (mRepeat != inRepeat) {
mRepeat = inRepeat;
if (mRepeat) {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
} else {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
}
if (mSmooth != inSmooth) {
mSmooth = inSmooth;
if (mSmooth) {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
}
}
UserPoint OpenGLTexture::PixelToTex (const UserPoint &inPixels) {
return UserPoint (inPixels.x / mTextureWidth, inPixels.y / mTextureHeight);
}
UserPoint OpenGLTexture::TexToPaddedTex (const UserPoint &inTex) {
return UserPoint (inTex.x * mPixelWidth / mTextureWidth, inTex.y * mPixelHeight / mTextureHeight);
}
}
<commit_msg>Check unpack align for alpha texture updates, do single texsubimage2d call (thanks Hugh)<commit_after>#include "renderer/opengl/OpenGLTexture.h"
namespace lime {
static int *sAlpha16Table = 0;
bool gFullNPO2Support = false;
bool gPartialNPO2Support = false;
bool NonPO2Supported (bool inNotRepeating) {
static bool tried = false;
//OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC
#ifdef FORCE_NON_PO2
return true;
#endif
if (!tried) {
tried = true;
const char* extensions = (char*)glGetString (GL_EXTENSIONS);
gFullNPO2Support = strstr (extensions, "ARB_texture_non_power_of_two") != 0;
if (!gFullNPO2Support) {
gPartialNPO2Support = strstr (extensions, "GL_APPLE_texture_2D_limited_npot") != 0;
}
//printf("Full non-PO2 support : %d\n", gFullNPO2Support);
//printf("Partial non-PO2 support : %d\n", gPartialNPO2Support);
}
return (gFullNPO2Support || (gPartialNPO2Support && inNotRepeating));
}
void RGBX_to_RGB565 (uint8 *outDest, const uint8 *inSrc, int inPixels) {
unsigned short *dest = (unsigned short *)outDest;
const uint8 *src = inSrc;
for (int x = 0; x < inPixels; x++) {
*dest++ = ((src[0] << 8) & 0xf800) | ((src[1] << 3) & 0x07e0) | ((src[2] >> 3));
src += 4;
}
}
void RGBA_to_RGBA4444 (uint8 *outDest, const uint8 *inSrc, int inPixels) {
unsigned short *dest = (unsigned short *)outDest;
const uint8 *src = inSrc;
for (int x = 0; x < inPixels; x++) {
*dest++ = ((src[0] << 8) & 0xf000) | ((src[1] << 4) & 0x0f00) | ((src[2]) & 0x00f0) | ((src[3] >> 4));
src += 4;
}
}
int *getAlpha16Table () {
if (sAlpha16Table == 0) {
sAlpha16Table = new int[256];
for (int a = 0; a < 256; a++) {
sAlpha16Table[a] = a * (1 << 16) / 255;
}
}
return sAlpha16Table;
}
OpenGLTexture::OpenGLTexture (Surface *inSurface, unsigned int inFlags) {
mPixelWidth = inSurface->Width ();
mPixelHeight = inSurface->Height ();
mDirtyRect = Rect (0, 0);
mContextVersion = gTextureContextVersion;
bool non_po2 = NonPO2Supported (inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2);
//printf("Using non-power-of-2 texture %d\n",non_po2);
int w = non_po2 ? mPixelWidth : UpToPower2 (mPixelWidth);
int h = non_po2 ? mPixelHeight : UpToPower2 (mPixelHeight);
mCanRepeat = IsPower2 (w) && IsPower2 (h);
//__android_log_print(ANDROID_LOG_ERROR, "lime", "NewTexure %d %d", w, h);
mTextureWidth = w;
mTextureHeight = h;
bool usePreAlpha = inFlags & SURF_FLAGS_USE_PREMULTIPLIED_ALPHA;
bool hasPreAlpha = inFlags & SURF_FLAGS_HAS_PREMULTIPLIED_ALPHA;
int *multiplyAlpha = usePreAlpha && !hasPreAlpha ? getAlpha16Table () : 0;
bool copy_required = inSurface->GetBase () && (w != mPixelWidth || h != mPixelHeight || multiplyAlpha);
Surface *load = inSurface;
uint8 *buffer = 0;
PixelFormat fmt = inSurface->Format ();
GLuint store_format = (fmt == pfAlpha ? GL_ALPHA : GL_RGBA);
int pixels = GL_UNSIGNED_BYTE;
int gpuFormat = inSurface->GPUFormat ();
if (!inSurface->GetBase ()) {
if (gpuFormat != fmt)
switch (gpuFormat) {
case pfARGB4444: pixels = GL_UNSIGNED_SHORT_4_4_4_4; break;
case pfRGB565: pixels = GL_UNSIGNED_SHORT_5_6_5; break;
default: pixels = gpuFormat;
}
} else if (gpuFormat == pfARGB4444) {
pixels = GL_UNSIGNED_SHORT_4_4_4_4;
buffer = (uint8 *)malloc (mTextureWidth * mTextureHeight * 2);
for (int y = 0; y < mPixelHeight; y++)
RGBA_to_RGBA4444 (buffer + y * mTextureWidth * 2, inSurface->Row (y), mPixelWidth);
} else if ( gpuFormat == pfRGB565) {
pixels = GL_UNSIGNED_SHORT_5_6_5;
buffer = (uint8 *)malloc (mTextureWidth * mTextureHeight * 2);
for (int y = 0; y < mPixelHeight; y++)
RGBX_to_RGB565 (buffer + y * mTextureWidth * 2, inSurface->Row (y), mPixelWidth);
} else if (copy_required) {
int pw = (inSurface->Format () == pfAlpha ? 1 : 4);
buffer = (uint8 *)malloc (pw * mTextureWidth * mTextureHeight);
for (int y = 0; y < mPixelHeight; y++) {
const uint8 *src = inSurface->Row (y);
uint8 *b = buffer + (mTextureWidth * pw * y);
if (multiplyAlpha) {
for (int x = 0; x < mPixelWidth; x++) {
int a16 = multiplyAlpha[src[3]];
b[0] = (src[0] * a16) >> 16;
b[1] = (src[1] * a16) >> 16;
b[2] = (src[2] * a16) >> 16;
b[3] = src[3];
b += 4;
src += 4;
}
} else {
memcpy (b, src, mPixelWidth * pw);
b += mPixelWidth * pw;
}
// Duplicate last pixel to help with bilinear interpolation
if (w > mPixelWidth)
memcpy (b, buffer + ((mPixelWidth - 1) * pw), pw);
}
// Duplicate last Row to help with bilinear interpolation
if (h != mPixelHeight) {
uint8 *b = buffer + (mTextureWidth * pw * mPixelHeight);
uint8 *b0 = b - (mTextureWidth * pw);
memcpy (b, b0, (mPixelWidth + (w != mPixelWidth)) * pw);
}
} else {
buffer = (uint8 *)inSurface->Row (0);
}
glGenTextures (1, &mTextureID);
// __android_log_print(ANDROID_LOG_ERROR, "lime", "CreateTexture %d (%dx%d)",
// mTextureID, mPixelWidth, mPixelHeight);
glBindTexture (GL_TEXTURE_2D, mTextureID);
mRepeat = mCanRepeat;
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE);
glTexImage2D (GL_TEXTURE_2D, 0, store_format, w, h, 0, store_format, pixels, buffer);
if (buffer && buffer != inSurface->Row (0))
free (buffer);
mSmooth = true;
#ifndef LIME_GLES
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
#endif
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// TODO: Need replacement call for GLES2?
#ifdef GPH
glTexEnvx (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#endif
#ifndef LIME_FORCE_GLES2
//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
#endif
//int err = glGetError();
//printf ("GL texture error: %i", err);
}
OpenGLTexture::~OpenGLTexture () {
if (mTextureID && mContextVersion == gTextureContextVersion && HardwareContext::current) {
//__android_log_print(ANDROID_LOG_ERROR, "lime", "DeleteTexture %d (%dx%d)",
//mTextureID, mPixelWidth, mPixelHeight);
HardwareContext::current->DestroyNativeTexture ((void *)(size_t)mTextureID);
}
}
void OpenGLTexture::Bind (class Surface *inSurface, int inSlot) {
if (inSlot >= 0 && &glActiveTexture) {
glActiveTexture (GL_TEXTURE0 + inSlot);
}
glBindTexture (GL_TEXTURE_2D, mTextureID);
if (gTextureContextVersion != mContextVersion) {
mContextVersion = gTextureContextVersion;
mDirtyRect = Rect (inSurface->Width (), inSurface->Height ());
}
if (inSurface->GetBase () && mDirtyRect.HasPixels ()) {
//__android_log_print(ANDROID_LOG_INFO, "lime", "UpdateDirtyRect! %d %d",
//mPixelWidth, mPixelHeight);
PixelFormat fmt = inSurface->Format ();
int pw = inSurface->BytesPP ();
GLuint store_format = (fmt == pfAlpha ? GL_ALPHA : GL_RGBA);
glGetError ();
int x0 = mDirtyRect.x;
int y0 = mDirtyRect.y;
int dw = mDirtyRect.w;
int dh = mDirtyRect.h;
#if defined(LIME_GLES)
uint8 *buffer = 0;
if (pw == 1) {
// Make unpack align a multiple of 4 ...
if (inSurface->Width () > 3) {
dw = (dw + 3) & ~3;
if (x0 + dw > inSurface->Width ()) {
x0 = inSurface->Width () - dw;
}
}
const uint8 *p0 = inSurface->Row (y0) + (x0 * pw);
buffer = (uint8 *)malloc (pw * dw * dh);
for (int y = 0; y < dh; y++) {
memcpy (buffer + (y * dw), p0, dw);
p0 += inSurface->GetStride ();
}
} else {
// TODO: pre-alpha ?
buffer = (uint8 *)malloc (pw * dw * dh);
const uint8 *p0 = inSurface->Row (y0) + (x0 * pw);
for (int y = 0; y < mDirtyRect.h; y++) {
memcpy (buffer + (y * dw * pw), p0, dw * pw);
p0 += inSurface->GetStride ();
}
}
glTexSubImage2D (GL_TEXTURE_2D, 0, x0, y0, dw, dh, store_format, GL_UNSIGNED_BYTE, buffer);
free (buffer);
#else
const uint8 *p0 = inSurface->Row (y0) + (x0 * pw);
glPixelStorei (GL_UNPACK_ROW_LENGTH, inSurface->Width ());
glTexSubImage2D (GL_TEXTURE_2D, 0, x0, y0, dw, dh, store_format, GL_UNSIGNED_BYTE, p0);
glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
#endif
int err = glGetError ();
if (err != GL_NO_ERROR)
ELOG ("GL Error: %d", err);
mDirtyRect = Rect ();
}
}
void OpenGLTexture::BindFlags (bool inRepeat, bool inSmooth) {
if (!mCanRepeat) inRepeat = false;
if (mRepeat != inRepeat) {
mRepeat = inRepeat;
if (mRepeat) {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
} else {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
}
if (mSmooth != inSmooth) {
mSmooth = inSmooth;
if (mSmooth) {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else {
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
}
}
UserPoint OpenGLTexture::PixelToTex (const UserPoint &inPixels) {
return UserPoint (inPixels.x / mTextureWidth, inPixels.y / mTextureHeight);
}
UserPoint OpenGLTexture::TexToPaddedTex (const UserPoint &inTex) {
return UserPoint (inTex.x * mPixelWidth / mTextureWidth, inTex.y * mPixelHeight / mTextureHeight);
}
}
<|endoftext|> |
<commit_before>//=============================================================================
// SuperCPPCString.cpp
//
// v1.1.2 - 2016.02.17 by Abe Pralle
//
// See README.md for instructions.
//=============================================================================
#include "SuperCPPCString.h"
#include <cstring>
using namespace std;
namespace PROJECT_NAMESPACE
{
namespace SuperCPP
{
//=============================================================================
// CString
//=============================================================================
CString::CString() : characters(0), count(0)
{
}
CString::CString( const char* value ) : characters(0), count(0)
{
*this = value;
}
CString::CString( const CString& existing ) : characters(0), count(0)
{
*this = existing;
}
CString::~CString()
{
if (characters) delete characters;
}
CString& CString::operator=( const char* value )
{
if (characters) delete characters;
count = (int) strlen( value );
characters = new char[ count+1 ];
strcpy( characters, value );
return *this;
}
CString& CString::operator=( const CString& other )
{
if (characters) delete characters;
count = other.count;
this->characters = new char[ count+1 ];
strcpy( this->characters, other.characters );
return *this;
}
CString::operator char*()
{
if (characters) return characters;
*this = "";
return characters;
}
CString::operator const char*()
{
if (characters) return characters;
return "";
}
} // namespace SuperCPP
} // namespace PROJECT_NAMESPACE
<commit_msg>Updated libraries.<commit_after>//=============================================================================
// SuperCPPCString.cpp
//
// v1.1.2 - 2016.02.17 by Abe Pralle
//
// See README.md for instructions.
//=============================================================================
#include "SuperCPPCString.h"
#include <cstring>
using namespace std;
namespace PROJECT_NAMESPACE
{
namespace SuperCPP
{
//=============================================================================
// CString
//=============================================================================
CString::CString() : characters(0), count(0)
{
}
CString::CString( const char* value ) : characters(0), count(0)
{
*this = value;
}
CString::CString( const CString& existing ) : characters(0), count(0)
{
*this = existing;
}
CString::~CString()
{
if (characters) delete characters;
}
CString& CString::operator=( const char* value )
{
if (characters) delete characters;
count = (int) strlen( value );
characters = new char[ count+1 ];
strcpy( characters, value );
return *this;
}
CString& CString::operator=( const CString& other )
{
if (characters) delete characters;
count = other.count;
this->characters = new char[ count+1 ];
strcpy( this->characters, other.characters );
return *this;
}
CString::operator char*()
{
if (characters) return characters;
return (char*) "";
}
CString::operator const char*()
{
if (characters) return characters;
return "";
}
} // namespace SuperCPP
} // namespace PROJECT_NAMESPACE
<|endoftext|> |
<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Enchants/Effect.hpp>
#include <Rosetta/Models/Character.hpp>
namespace RosettaStone
{
Effect::Effect(GameTag gameTag, EffectOperator effectOperator, int value)
: m_gameTag(gameTag), m_effectOperator(effectOperator), m_value(value)
{
// Do nothing
}
void Effect::Apply(Character* character, bool isOneTurnEffect) const
{
if (isOneTurnEffect)
{
// TODO: Process one turn effect
}
const int prevValue = character->GetGameTag(m_gameTag);
switch (m_effectOperator)
{
case EffectOperator::ADD:
character->SetGameTag(m_gameTag, prevValue + m_value);
break;
case EffectOperator::SUB:
character->SetGameTag(m_gameTag, prevValue - m_value);
break;
case EffectOperator::MUL:
character->SetGameTag(m_gameTag, prevValue * m_value);
break;
case EffectOperator::SET:
character->SetGameTag(m_gameTag, m_value);
break;
default:
throw std::invalid_argument("Invalid effect operator!");
}
}
void Effect::Apply(AuraEffects& auraEffects) const
{
const int prevValue = auraEffects.GetGameTag(m_gameTag);
switch (m_effectOperator)
{
case EffectOperator::ADD:
auraEffects.SetGameTag(m_gameTag, prevValue + m_value);
break;
case EffectOperator::SUB:
auraEffects.SetGameTag(m_gameTag, prevValue - m_value);
break;
case EffectOperator::SET:
auraEffects.SetGameTag(m_gameTag, m_value);
break;
default:
throw std::invalid_argument("Invalid effect operator!");
}
}
void Effect::Remove(AuraEffects& auraEffects) const
{
if (m_gameTag == GameTag::HEALTH && m_effectOperator == EffectOperator::ADD)
{
auto owner = dynamic_cast<Character*>(auraEffects.GetOwner());
int prevDamage = owner->GetDamage();
owner->SetDamage(prevDamage - m_value);
}
const int prevValue = auraEffects.GetGameTag(m_gameTag);
switch (m_effectOperator)
{
case EffectOperator::ADD:
auraEffects.SetGameTag(m_gameTag, prevValue - m_value);
break;
case EffectOperator::SUB:
auraEffects.SetGameTag(m_gameTag, prevValue + m_value);
break;
case EffectOperator::SET:
auraEffects.SetGameTag(m_gameTag, prevValue - m_value);
break;
default:
throw std::invalid_argument("Invalid effect operator!");
}
}
} // namespace RosettaStone
<commit_msg>fix: Add missing <stdexcept> header file<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Enchants/Effect.hpp>
#include <Rosetta/Models/Character.hpp>
#include <stdexcept>
namespace RosettaStone
{
Effect::Effect(GameTag gameTag, EffectOperator effectOperator, int value)
: m_gameTag(gameTag), m_effectOperator(effectOperator), m_value(value)
{
// Do nothing
}
void Effect::Apply(Character* character, bool isOneTurnEffect) const
{
if (isOneTurnEffect)
{
// TODO: Process one turn effect
}
const int prevValue = character->GetGameTag(m_gameTag);
switch (m_effectOperator)
{
case EffectOperator::ADD:
character->SetGameTag(m_gameTag, prevValue + m_value);
break;
case EffectOperator::SUB:
character->SetGameTag(m_gameTag, prevValue - m_value);
break;
case EffectOperator::MUL:
character->SetGameTag(m_gameTag, prevValue * m_value);
break;
case EffectOperator::SET:
character->SetGameTag(m_gameTag, m_value);
break;
default:
throw std::invalid_argument("Invalid effect operator!");
}
}
void Effect::Apply(AuraEffects& auraEffects) const
{
const int prevValue = auraEffects.GetGameTag(m_gameTag);
switch (m_effectOperator)
{
case EffectOperator::ADD:
auraEffects.SetGameTag(m_gameTag, prevValue + m_value);
break;
case EffectOperator::SUB:
auraEffects.SetGameTag(m_gameTag, prevValue - m_value);
break;
case EffectOperator::SET:
auraEffects.SetGameTag(m_gameTag, m_value);
break;
default:
throw std::invalid_argument("Invalid effect operator!");
}
}
void Effect::Remove(AuraEffects& auraEffects) const
{
if (m_gameTag == GameTag::HEALTH && m_effectOperator == EffectOperator::ADD)
{
auto owner = dynamic_cast<Character*>(auraEffects.GetOwner());
int prevDamage = owner->GetDamage();
owner->SetDamage(prevDamage - m_value);
}
const int prevValue = auraEffects.GetGameTag(m_gameTag);
switch (m_effectOperator)
{
case EffectOperator::ADD:
auraEffects.SetGameTag(m_gameTag, prevValue - m_value);
break;
case EffectOperator::SUB:
auraEffects.SetGameTag(m_gameTag, prevValue + m_value);
break;
case EffectOperator::SET:
auraEffects.SetGameTag(m_gameTag, prevValue - m_value);
break;
default:
throw std::invalid_argument("Invalid effect operator!");
}
}
} // namespace RosettaStone
<|endoftext|> |
<commit_before>#include <type_traits>
#include <algorithm>
#include <sstream>
#include <mipp.h>
#include "Tools/Exception/exception.hpp"
#include "Tools/general_utils.h"
#include "Modem_optical.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
//
//std::vector<std::vector<float>> llrs;
//size_t llr_idx;
template <typename B, typename R, typename Q>
Modem_optical<B,R,Q>
::Modem_optical(const int N,
const tools::Distributions<R>& dist,
const tools::Noise<R>& noise,
const int n_frames)
: Modem<B,R,Q>(N, noise, n_frames),
dist(dist)
{
const std::string name = "Modem_optical";
this->set_name(name);
// std::ifstream file("/media/ohartmann/DATA/Documents/Projets/CNES_AIRBUS/matrices/2018_05_03/vectorTestIMS/TestVec ROP -32/AFF3CT/LLR.txt");
//
// if (!file.is_open())
// throw tools::runtime_error();
//
// unsigned length, n_llrs;
// file >> n_llrs >> length;
//
// llrs.resize(n_llrs, std::vector<float>(length));
//
// for (unsigned i = 0; i < n_llrs; i++)
// {
// for (unsigned j = 0; j < length; j++)
// file >> llrs[i][j];
// }
// llr_idx = 0;
}
template <typename B, typename R, typename Q>
Modem_optical<B,R,Q>
::~Modem_optical()
{
}
template <typename B, typename R, typename Q>
void Modem_optical<B,R,Q>
::set_noise(const tools::Noise<R>& noise)
{
Modem<B,R,Q>::set_noise(noise);
this->n->is_of_type_throw(tools::Noise_type::ROP);
this->current_dist = dist.get_distribution(this->n->get_noise());
if (this->current_dist == nullptr)
{
std::stringstream message;
message << "Undefined noise power 'this->n->get_noise()' in the given distributions"
" ('this->n->get_noise()' = " << this->n->get_noise() << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
}
template <typename B, typename R, typename Q>
void Modem_optical<B,R,Q>
::_modulate(const B *X_N1, R *X_N2, const int frame_id)
{
for (int i = 0; i < this->N; i++)
X_N2[i] = X_N1[i] ? (R)1 : (R)0;
}
namespace aff3ct
{
namespace module
{
template <>
void Modem_optical<int,float,float>
::_modulate(const int *X_N1, float *X_N2, const int frame_id)
{
using B = int;
using R = float;
unsigned size = (unsigned int)(this->N);
const auto vec_loop_size = (size / mipp::nElReg<B>()) * mipp::nElReg<B>();
const mipp::Reg<R> Rone = (R)1.0;
const mipp::Reg<R> Rzero = (R)0.0;
const mipp::Reg<B> Bzero = (B)0;
for (unsigned i = 0; i < vec_loop_size; i += mipp::nElReg<B>())
{
const auto x1b = mipp::Reg<B>(&X_N1[i]);
const auto x2r = mipp::blend(Rone, Rzero, x1b != Bzero);
x2r.store(&X_N2[i]);
}
for (unsigned i = vec_loop_size; i < size; i++)
X_N2[i] = X_N1[i] ? (R)1 : (R)0;
}
}
}
template <typename B,typename R, typename Q>
void Modem_optical<B,R,Q>
::_filter(const R *Y_N1, R *Y_N2, const int frame_id)
{
std::copy(Y_N1, Y_N1 + this->N_fil, Y_N2);
}
template <typename B, typename R, typename Q>
void Modem_optical<B,R,Q>
::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id)
{
if (!std::is_same<R,Q>::value)
throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'R' and 'Q' have to be the same.");
if (!std::is_floating_point<Q>::value)
throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'Q' has to be float or double.");
const Q min_value = 1e-10; // when prob_1 ou prob_0 = 0;
if (current_dist == nullptr)
throw tools::runtime_error(__FILE__, __LINE__, __func__, "No valid noise has been set.");
const auto& pdf_x = current_dist->get_pdf_x();
const auto& pdf_y0 = current_dist->get_pdf_y()[0];
const auto& pdf_y1 = current_dist->get_pdf_y()[1];
unsigned x_pos;
for (auto i = 0; i < this->N_fil; i++)
{
// find the position of the first x that is above the receiver val
auto x_above = std::lower_bound(pdf_x.begin(), pdf_x.end(), Y_N1[i]);
if (x_above == pdf_x.end()) // if last
x_pos = pdf_x.size() - 1;
else if (x_above == pdf_x.begin()) // if first
x_pos = 0;
else
{
x_pos = std::distance(pdf_x.begin(), x_above);
auto x_below = x_above - 1;
// find which between x_below and x_above is the nearest of Y_N1[i]
x_pos = (Y_N1[i] - *x_below) < (*x_above - Y_N1[i]) ? x_pos - 1 : x_pos;
}
// then get the matching probabilities
auto prob_0 = pdf_y0[x_pos] == (Q)0 ? min_value : pdf_y0[x_pos];
auto prob_1 = pdf_y1[x_pos] == (Q)0 ? min_value : pdf_y1[x_pos];
Y_N2[i] = std::log(prob_0/prob_1);
}
}
//template <typename B, typename R, typename Q>
//void Modem_optical<B,R,Q>
//::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id)
//{
// std::copy(llrs[llr_idx].begin(), llrs[llr_idx].end(), Y_N2);
// llr_idx = (llr_idx + 1) % llrs.size();
//};
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Modem_optical<B_8,R_8,R_8>;
template class aff3ct::module::Modem_optical<B_8,R_8,Q_8>;
template class aff3ct::module::Modem_optical<B_16,R_16,R_16>;
template class aff3ct::module::Modem_optical<B_16,R_16,Q_16>;
template class aff3ct::module::Modem_optical<B_32,R_32,R_32>;
template class aff3ct::module::Modem_optical<B_64,R_64,R_64>;
#else
template class aff3ct::module::Modem_optical<B,R,Q>;
#if !defined(PREC_32_BIT) && !defined(PREC_64_BIT)
template class aff3ct::module::Modem_optical<B,R,R>;
#endif
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>rewrite optical demodulator to use the get_closet function<commit_after>#include <type_traits>
#include <algorithm>
#include <sstream>
#include <mipp.h>
#include "Tools/Exception/exception.hpp"
#include "Tools/general_utils.h"
#include "Modem_optical.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
//
//std::vector<std::vector<float>> llrs;
//size_t llr_idx;
template <typename B, typename R, typename Q>
Modem_optical<B,R,Q>
::Modem_optical(const int N,
const tools::Distributions<R>& dist,
const tools::Noise<R>& noise,
const int n_frames)
: Modem<B,R,Q>(N, noise, n_frames),
dist(dist)
{
const std::string name = "Modem_optical";
this->set_name(name);
// std::ifstream file("/media/ohartmann/DATA/Documents/Projets/CNES_AIRBUS/matrices/2018_05_03/vectorTestIMS/TestVec ROP -32/AFF3CT/LLR.txt");
//
// if (!file.is_open())
// throw tools::runtime_error();
//
// unsigned length, n_llrs;
// file >> n_llrs >> length;
//
// llrs.resize(n_llrs, std::vector<float>(length));
//
// for (unsigned i = 0; i < n_llrs; i++)
// {
// for (unsigned j = 0; j < length; j++)
// file >> llrs[i][j];
// }
// llr_idx = 0;
}
template <typename B, typename R, typename Q>
Modem_optical<B,R,Q>
::~Modem_optical()
{
}
template <typename B, typename R, typename Q>
void Modem_optical<B,R,Q>
::set_noise(const tools::Noise<R>& noise)
{
Modem<B,R,Q>::set_noise(noise);
this->n->is_of_type_throw(tools::Noise_type::ROP);
this->current_dist = dist.get_distribution(this->n->get_noise());
if (this->current_dist == nullptr)
{
std::stringstream message;
message << "Undefined noise power 'this->n->get_noise()' in the given distributions"
" ('this->n->get_noise()' = " << this->n->get_noise() << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
}
template <typename B, typename R, typename Q>
void Modem_optical<B,R,Q>
::_modulate(const B *X_N1, R *X_N2, const int frame_id)
{
for (int i = 0; i < this->N; i++)
X_N2[i] = X_N1[i] ? (R)1 : (R)0;
}
namespace aff3ct
{
namespace module
{
template <>
void Modem_optical<int,float,float>
::_modulate(const int *X_N1, float *X_N2, const int frame_id)
{
using B = int;
using R = float;
unsigned size = (unsigned int)(this->N);
const auto vec_loop_size = (size / mipp::nElReg<B>()) * mipp::nElReg<B>();
const mipp::Reg<R> Rone = (R)1.0;
const mipp::Reg<R> Rzero = (R)0.0;
const mipp::Reg<B> Bzero = (B)0;
for (unsigned i = 0; i < vec_loop_size; i += mipp::nElReg<B>())
{
const auto x1b = mipp::Reg<B>(&X_N1[i]);
const auto x2r = mipp::blend(Rone, Rzero, x1b != Bzero);
x2r.store(&X_N2[i]);
}
for (unsigned i = vec_loop_size; i < size; i++)
X_N2[i] = X_N1[i] ? (R)1 : (R)0;
}
}
}
template <typename B,typename R, typename Q>
void Modem_optical<B,R,Q>
::_filter(const R *Y_N1, R *Y_N2, const int frame_id)
{
std::copy(Y_N1, Y_N1 + this->N_fil, Y_N2);
}
template <typename B, typename R, typename Q>
void Modem_optical<B,R,Q>
::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id)
{
if (!std::is_same<R,Q>::value)
throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'R' and 'Q' have to be the same.");
if (!std::is_floating_point<Q>::value)
throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'Q' has to be float or double.");
const Q min_value = 1e-10; // when prob_1 ou prob_0 = 0;
if (current_dist == nullptr)
throw tools::runtime_error(__FILE__, __LINE__, __func__, "No valid noise has been set.");
const auto& pdf_x = current_dist->get_pdf_x();
const auto& pdf_y0 = current_dist->get_pdf_y()[0];
const auto& pdf_y1 = current_dist->get_pdf_y()[1];
for (auto i = 0; i < this->N_fil; i++)
{
auto x_pos = tools::get_closest_index(pdf_x.begin(), pdf_x.end(), Y_N1[i]);
auto prob_0 = pdf_y0[x_pos] == (Q)0 ? min_value : pdf_y0[x_pos];
auto prob_1 = pdf_y1[x_pos] == (Q)0 ? min_value : pdf_y1[x_pos];
Y_N2[i] = std::log(prob_0/prob_1);
}
}
//template <typename B, typename R, typename Q>
//void Modem_optical<B,R,Q>
//::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id)
//{
// std::copy(llrs[llr_idx].begin(), llrs[llr_idx].end(), Y_N2);
// llr_idx = (llr_idx + 1) % llrs.size();
//};
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Modem_optical<B_8,R_8,R_8>;
template class aff3ct::module::Modem_optical<B_8,R_8,Q_8>;
template class aff3ct::module::Modem_optical<B_16,R_16,R_16>;
template class aff3ct::module::Modem_optical<B_16,R_16,Q_16>;
template class aff3ct::module::Modem_optical<B_32,R_32,R_32>;
template class aff3ct::module::Modem_optical<B_64,R_64,R_64>;
#else
template class aff3ct::module::Modem_optical<B,R,Q>;
#if !defined(PREC_32_BIT) && !defined(PREC_64_BIT)
template class aff3ct::module::Modem_optical<B,R,R>;
#endif
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include <fstream>
#include "ioHandler.h"
#include <map>
#include <unordered_map>
#include <boost/dynamic_bitset.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>
namespace
{
const size_t SUCCESS = 0;
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
typedef std::unordered_map<std::string, size_t> Counter;
typedef std::map <boost::dynamic_bitset<>, std::unique_ptr<ReadBase>> BitMap;
template <class T, class Impl>
void load_map(InputReader<T, Impl> &reader, Counter& counters, BitMap& read_map, size_t start, size_t length) {
while(reader.has_next()) {
auto i = reader.next();
++counters["TotalRecords"];
//std::cout << "read id: " << i->get_read().get_id() << std::endl;
//check for existance, store or compare quality and replace:
if (auto key=i->get_key(start, length)) {
if(!read_map.count(*key)) {
read_map[*key] = std::move(i);
} else if(i->avg_q_score() > read_map[*key]->avg_q_score()){
read_map[*key] = std::move(i);
++counters["Replaced"];
}
} else { // key had N
++counters["HasN"];
}
}
}
namespace bi = boost::iostreams;
namespace bf = boost::filesystem;
int check_open_r(const std::string& filename) {
bf::path p(filename);
if (!bf::exists(p)) {
throw std::runtime_error("File " + filename + " was not found.");
}
if (p.extension() == ".gz") {
return fileno(popen(("gunzip -c " + filename).c_str(), "r"));
} else {
return fileno(fopen(filename.c_str(), "r"));
}
}
int main(int argc, char** argv)
{
BitMap read_map;
Counter counters;
counters["TotalRecords"] = 0;
counters["Replaced"] = 0;
counters["HasN"] = 0;
size_t start, length = 0;
std::string prefix;
std::vector<std::string> default_pe = {"PE1", "PE2"};
bool fastq_out;
bool tab_out;
bool std_out;
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("version,v", "Version print")
("read1-input,1", po::value< std::vector<std::string> >(),
"Read 1 input <comma sep for multiple files>")
("read2-input,2", po::value< std::vector<std::string> >(),
"Read 2 input <comma sep for multiple files>")
("singleend-input,U", po::value< std::vector<std::string> >(),
"Single end read input <comma sep for multiple files>")
("tab-input,T", po::value< std::vector<std::string> >(),
"Tab input <comma sep for multiple files>")
("interleaved-input,I", po::value< std::vector<std::string> >(),
"Interleaved input I <comma sep for multiple files>")
("stdin-input,S", "STDIN input <MUST BE TAB DELIMITED INPUT>")
("start,s", po::value<size_t>(&start)->default_value(10), "Start location for unique ID <int>")
("length,l", po::value<size_t>(&length)->default_value(10), "Length of unique ID <int>")
("quality-check-off,q", "Quality Checking Off First Duplicate seen will be kept")
("gzip-output,g", "Output gzipped")
("interleaved-output, i", "Output to interleaved")
("fastq-output,f", po::bool_switch(&fastq_out)->default_value(false), "Fastq format output")
("force,F", po::bool_switch()->default_value(true), "Forces overwrite of files")
("tab-output,t", po::bool_switch(&tab_out)->default_value(false), "Tab-delimited output")
("to-stdout,O", po::bool_switch(&std_out)->default_value(false), "Prints to STDOUT in Tab Delimited")
("prefix,p", po::value<std::string>(&prefix)->default_value("output_nodup_"),
"Prefix for outputted files")
("log-file,L", "Output-Logfile")
("no-log,N", "No logfile <outputs to stderr>")
("help,h", "Prints help.");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // can throw
/** --help option
*/
if ( vm.count("help") || vm.size() == 0)
{
std::cout << "Super-Deduper" << std::endl
<< desc << std::endl;
return SUCCESS;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
if(vm.count("read1-input")) {
if (!vm.count("read2-input")) {
throw std::runtime_error("must specify both read1 and read2 input files.");
} else if (vm.count("read2-input") != vm.count("read1-input")) {
throw std::runtime_error("must have same number of input files for read1 and read2");
}
auto read1_files = vm["read1-input"].as<std::vector<std::string> >();
auto read2_files = vm["read2-input"].as<std::vector<std::string> >();
for(size_t i = 0; i < read1_files.size(); ++i) {
// todo: check file exists etc
//std::ifstream read1(read1_files[i], std::ifstream::in);
//std::ifstream read2(read2_files[i], std::ifstream::in);
bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle};
bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle};
InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2);
load_map(ifp, counters, read_map, start, length);
}
}
else if(vm.count("singleend-input")) {
auto read_files = vm["singleend-input"].as<std::vector<std::string> >();
for (auto file : read_files) {
std::ifstream read1(file, std::ifstream::in);
InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(read1);
load_map(ifs, counters, read_map, start, length);
}
}
if (fastq_out || (! std_out && ! tab_out) ) {
default_pe[0] += ".fastq";
default_pe[1] += ".fastq";
default_pe[0] = prefix + default_pe[0];
default_pe[1] = prefix + default_pe[1];
std::ofstream out1(default_pe[0], std::ofstream::out);
std::ofstream out2(default_pe[1], std::ofstream::out);
OutputWriter<PairedEndRead, PairedEndReadOutFastq> ofs(out1, out2);
for(auto const &i : read_map) {
ofs.write(*dynamic_cast<PairedEndRead*>(i.second.get()));
}
}
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
// application code here //
}
catch(std::exception& e)
{
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
std::cerr << "TotalRecords:" << counters["TotalRecords"] << "\tReplaced:" << counters["Replaced"]
<< "\tKept:" << read_map.size() << "\tRemoved:" << counters["TotalRecords"] - read_map.size()
<< "\tHasN:" << counters["HasN"] << std::endl;
return SUCCESS;
}
<commit_msg>minor change in output<commit_after>#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include <fstream>
#include "ioHandler.h"
#include <map>
#include <unordered_map>
#include <boost/dynamic_bitset.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>
namespace
{
const size_t SUCCESS = 0;
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
typedef std::unordered_map<std::string, size_t> Counter;
typedef std::map <boost::dynamic_bitset<>, std::unique_ptr<ReadBase>> BitMap;
template <class T, class Impl>
void load_map(InputReader<T, Impl> &reader, Counter& counters, BitMap& read_map, size_t start, size_t length) {
while(reader.has_next()) {
auto i = reader.next();
++counters["TotalRecords"];
//std::cout << "read id: " << i->get_read().get_id() << std::endl;
//check for existance, store or compare quality and replace:
if (auto key=i->get_key(start, length)) {
if(!read_map.count(*key)) {
read_map[*key] = std::move(i);
} else if(i->avg_q_score() > read_map[*key]->avg_q_score()){
read_map[*key] = std::move(i);
++counters["Replaced"];
}
} else { // key had N
++counters["HasN"];
}
}
}
namespace bi = boost::iostreams;
namespace bf = boost::filesystem;
int check_open_r(const std::string& filename) {
bf::path p(filename);
if (!bf::exists(p)) {
throw std::runtime_error("File " + filename + " was not found.");
}
if (p.extension() == ".gz") {
return fileno(popen(("gunzip -c " + filename).c_str(), "r"));
} else {
return fileno(fopen(filename.c_str(), "r"));
}
}
int main(int argc, char** argv)
{
BitMap read_map;
Counter counters;
counters["TotalRecords"] = 0;
counters["Replaced"] = 0;
counters["HasN"] = 0;
size_t start, length = 0;
std::string prefix;
std::vector<std::string> default_pe = {"PE1", "PE2"};
bool fastq_out;
bool tab_out;
bool std_out;
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("version,v", "Version print")
("read1-input,1", po::value< std::vector<std::string> >(),
"Read 1 input <comma sep for multiple files>")
("read2-input,2", po::value< std::vector<std::string> >(),
"Read 2 input <comma sep for multiple files>")
("singleend-input,U", po::value< std::vector<std::string> >(),
"Single end read input <comma sep for multiple files>")
("tab-input,T", po::value< std::vector<std::string> >(),
"Tab input <comma sep for multiple files>")
("interleaved-input,I", po::value< std::vector<std::string> >(),
"Interleaved input I <comma sep for multiple files>")
("stdin-input,S", "STDIN input <MUST BE TAB DELIMITED INPUT>")
("start,s", po::value<size_t>(&start)->default_value(10), "Start location for unique ID <int>")
("length,l", po::value<size_t>(&length)->default_value(10), "Length of unique ID <int>")
("quality-check-off,q", "Quality Checking Off First Duplicate seen will be kept")
("gzip-output,g", "Output gzipped")
("interleaved-output, i", "Output to interleaved")
("fastq-output,f", po::bool_switch(&fastq_out)->default_value(false), "Fastq format output")
("force,F", po::bool_switch()->default_value(true), "Forces overwrite of files")
("tab-output,t", po::bool_switch(&tab_out)->default_value(false), "Tab-delimited output")
("to-stdout,O", po::bool_switch(&std_out)->default_value(false), "Prints to STDOUT in Tab Delimited")
("prefix,p", po::value<std::string>(&prefix)->default_value("output_nodup_"),
"Prefix for outputted files")
("log-file,L", "Output-Logfile")
("no-log,N", "No logfile <outputs to stderr>")
("help,h", "Prints help.");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // can throw
/** --help option
*/
if ( vm.count("help") || vm.size() == 0)
{
std::cout << "Super-Deduper" << std::endl
<< desc << std::endl;
return SUCCESS;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
if(vm.count("read1-input")) {
if (!vm.count("read2-input")) {
throw std::runtime_error("must specify both read1 and read2 input files.");
} else if (vm.count("read2-input") != vm.count("read1-input")) {
throw std::runtime_error("must have same number of input files for read1 and read2");
}
auto read1_files = vm["read1-input"].as<std::vector<std::string> >();
auto read2_files = vm["read2-input"].as<std::vector<std::string> >();
for(size_t i = 0; i < read1_files.size(); ++i) {
// todo: check file exists etc
//std::ifstream read1(read1_files[i], std::ifstream::in);
//std::ifstream read2(read2_files[i], std::ifstream::in);
bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle};
bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle};
InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2);
load_map(ifp, counters, read_map, start, length);
}
}
else if(vm.count("singleend-input")) {
auto read_files = vm["singleend-input"].as<std::vector<std::string> >();
for (auto file : read_files) {
std::ifstream read1(file, std::ifstream::in);
InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(read1);
load_map(ifs, counters, read_map, start, length);
}
}
if (fastq_out || (! std_out && ! tab_out) ) {
default_pe[0] += ".fastq";
default_pe[1] += ".fastq";
default_pe[0] = prefix + default_pe[0];
default_pe[1] = prefix + default_pe[1];
std::ofstream out1(default_pe[0], std::ofstream::out);
std::ofstream out2(default_pe[1], std::ofstream::out);
OutputWriter<PairedEndRead, PairedEndReadOutFastq> ofs(out1, out2);
for(auto const &i : read_map) {
ofs.write(*dynamic_cast<PairedEndRead*>(i.second.get()));
}
}
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return ERROR_IN_COMMAND_LINE;
}
}
catch(std::exception& e)
{
std::cerr << "\n\tUnhandled Exception: "
<< e.what() << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
std::cerr << "TotalRecords:" << counters["TotalRecords"] << "\tReplaced:" << counters["Replaced"]
<< "\tKept:" << read_map.size() << "\tRemoved:" << counters["TotalRecords"] - read_map.size()
<< "\tHasN:" << counters["HasN"] << std::endl;
return SUCCESS;
}
<|endoftext|> |
<commit_before>/**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2011 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/StreamTubeClient>
#include "TelepathyQt4/stream-tube-client-internal.h"
#include "TelepathyQt4/_gen/stream-tube-client.moc.hpp"
#include "TelepathyQt4/_gen/stream-tube-client-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include "TelepathyQt4/simple-stream-tube-handler.h"
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/ClientRegistrar>
#include <TelepathyQt4/IncomingStreamTubeChannel>
#include <TelepathyQt4/PendingStreamTubeConnection>
#include <TelepathyQt4/StreamTubeChannel>
#include <QHash>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT StreamTubeClient::Private
{
Private(const ClientRegistrarPtr ®istrar,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &maybeClientName,
bool monitorConnections,
bool bypassApproval)
: registrar(registrar),
handler(SimpleStreamTubeHandler::create(
p2pServices, roomServices, false, monitorConnections, bypassApproval)),
clientName(maybeClientName),
isRegistered(false),
acceptsAsTcp(false), acceptsAsUnix(false),
tcpGenerator(0), requireCredentials(false)
{
if (clientName.isEmpty()) {
clientName = QString::fromLatin1("TpQt4STubeClient_%1_%2")
.arg(registrar->dbusConnection().baseService()
.replace(QLatin1Char(':'), QLatin1Char('_'))
.replace(QLatin1Char('.'), QLatin1Char('_')))
.arg((intptr_t) this, 0, 16);
}
}
void ensureRegistered()
{
if (isRegistered) {
return;
}
debug() << "Register StreamTubeClient with name " << clientName;
if (registrar->registerClient(handler, clientName)) {
isRegistered = true;
} else {
warning() << "StreamTubeClient" << clientName
<< "registration failed";
}
}
ClientRegistrarPtr registrar;
SharedPtr<SimpleStreamTubeHandler> handler;
QString clientName;
bool isRegistered;
bool acceptsAsTcp, acceptsAsUnix;
const TcpSourceAddressGenerator *tcpGenerator;
bool requireCredentials;
QHash<StreamTubeChannelPtr, TubeWrapper *> tubes;
};
StreamTubeClient::TubeWrapper::TubeWrapper(
const AccountPtr &acc,
const IncomingStreamTubeChannelPtr &tube,
const QHostAddress &sourceAddress,
quint16 sourcePort)
: mAcc(acc), mTube(tube), mSourceAddress(sourceAddress), mSourcePort(sourcePort)
{
connect(tube->acceptTubeAsTcpSocket(sourceAddress, sourcePort),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onTubeAccepted(Tp::PendingOperation*)));
connect(tube.data(),
SIGNAL(newConnection(uint)),
SLOT(onNewConnection(uint)));
connect(tube.data(),
SIGNAL(connectionClosed(uint,QString,QString)),
SLOT(onConnectionClosed(uint,QString,QString)));
}
StreamTubeClient::TubeWrapper::TubeWrapper(
const AccountPtr &acc,
const IncomingStreamTubeChannelPtr &tube,
bool requireCredentials)
: mAcc(acc), mTube(tube), mSourcePort(0)
{
connect(tube->acceptTubeAsUnixSocket(requireCredentials),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onTubeAccepted(Tp::PendingOperation*)));
connect(tube.data(),
SIGNAL(newConnection(uint)),
SLOT(onNewConnection(uint)));
connect(tube.data(),
SIGNAL(connectionClosed(uint,QString,QString)),
SLOT(onConnectionClosed(uint,QString,QString)));
}
void StreamTubeClient::TubeWrapper::onTubeAccepted(Tp::PendingOperation *op)
{
emit acceptFinished(this, qobject_cast<Tp::PendingStreamTubeConnection *>(op));
}
void StreamTubeClient::TubeWrapper::onNewConnection(uint conn)
{
emit newConnection(this, conn);
}
void StreamTubeClient::TubeWrapper::onConnectionClosed(uint conn, const QString &error,
const QString &message)
{
emit connectionClosed(this, conn, error, message);
}
StreamTubeClientPtr StreamTubeClient::create(
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval,
const AccountFactoryConstPtr &accountFactory,
const ConnectionFactoryConstPtr &connectionFactory,
const ChannelFactoryConstPtr &channelFactory,
const ContactFactoryConstPtr &contactFactory)
{
return create(
QDBusConnection::sessionBus(),
accountFactory,
connectionFactory,
channelFactory,
contactFactory,
p2pServices,
roomServices,
clientName,
monitorConnections,
bypassApproval);
}
StreamTubeClientPtr StreamTubeClient::create(
const QDBusConnection &bus,
const AccountFactoryConstPtr &accountFactory,
const ConnectionFactoryConstPtr &connectionFactory,
const ChannelFactoryConstPtr &channelFactory,
const ContactFactoryConstPtr &contactFactory,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
{
return create(
ClientRegistrar::create(
bus,
accountFactory,
connectionFactory,
channelFactory,
contactFactory),
p2pServices,
roomServices,
clientName,
monitorConnections,
bypassApproval);
}
StreamTubeClientPtr StreamTubeClient::create(
const AccountManagerPtr &accountManager,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
{
return create(
accountManager->dbusConnection(),
accountManager->accountFactory(),
accountManager->connectionFactory(),
accountManager->channelFactory(),
accountManager->contactFactory(),
p2pServices,
roomServices,
clientName,
monitorConnections,
bypassApproval);
}
StreamTubeClientPtr StreamTubeClient::create(
const ClientRegistrarPtr ®istrar,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
{
return StreamTubeClientPtr(
new StreamTubeClient(registrar, p2pServices, roomServices, clientName,
monitorConnections, bypassApproval));
}
StreamTubeClient::StreamTubeClient(
const ClientRegistrarPtr ®istrar,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
: mPriv(new Private(registrar, p2pServices, roomServices, clientName, monitorConnections, bypassApproval))
{
connect(mPriv->handler.data(),
SIGNAL(invokedForTube(
Tp::AccountPtr,
Tp::StreamTubeChannelPtr,
QDateTime,
Tp::ChannelRequestHints)),
SLOT(onInvokedForTube(
Tp::AccountPtr,
Tp::StreamTubeChannelPtr,
QDateTime,
Tp::ChannelRequestHints)));
}
/**
* Class destructor.
*/
StreamTubeClient::~StreamTubeClient()
{
if (isRegistered()) {
mPriv->registrar->unregisterClient(mPriv->handler);
}
foreach (TubeWrapper *wrapper, mPriv->tubes.values()) {
wrapper->deleteLater();
}
delete mPriv;
}
ClientRegistrarPtr StreamTubeClient::registrar() const
{
return mPriv->registrar;
}
QString StreamTubeClient::clientName() const
{
return mPriv->clientName;
}
bool StreamTubeClient::isRegistered() const
{
return mPriv->isRegistered;
}
bool StreamTubeClient::monitorsConnections() const
{
return mPriv->handler->monitorsConnections();
}
bool StreamTubeClient::acceptsAsTcp() const
{
return mPriv->acceptsAsTcp;
}
const StreamTubeClient::TcpSourceAddressGenerator *StreamTubeClient::generator() const
{
if (!acceptsAsTcp()) {
warning() << "StreamTubeClient::generator() used, but not accepting as TCP, returning 0";
return 0;
}
return mPriv->tcpGenerator;
}
bool StreamTubeClient::acceptsAsUnix() const
{
return mPriv->acceptsAsUnix;
}
void StreamTubeClient::setToAcceptAsTcp(const TcpSourceAddressGenerator *generator)
{
mPriv->tcpGenerator = generator;
mPriv->acceptsAsTcp = true;
mPriv->acceptsAsUnix = false;
mPriv->ensureRegistered();
}
void StreamTubeClient::setToAcceptAsUnix(bool requireCredentials)
{
mPriv->tcpGenerator = 0;
mPriv->acceptsAsTcp = false;
mPriv->acceptsAsUnix = true;
mPriv->requireCredentials = requireCredentials;
mPriv->ensureRegistered();
}
QList<QPair<AccountPtr, IncomingStreamTubeChannelPtr> > StreamTubeClient::tubes() const
{
QList<QPair<AccountPtr, IncomingStreamTubeChannelPtr> > tubes;
foreach (TubeWrapper *wrapper, mPriv->tubes.values()) {
tubes.push_back(qMakePair(wrapper->mAcc, wrapper->mTube));
}
return tubes;
}
QHash<QPair<AccountPtr, IncomingStreamTubeChannelPtr>, QSet<uint> >
StreamTubeClient::connections() const
{
QHash<QPair<AccountPtr, IncomingStreamTubeChannelPtr>, QSet<uint> > conns;
if (!monitorsConnections()) {
warning() << "StreamTubeClient::connections() used, but connection monitoring is disabled";
return conns;
}
QPair<AccountPtr, IncomingStreamTubeChannelPtr> tube;
foreach (tube, tubes()) {
QSet<uint> tubeConns = QSet<uint>::fromList(tube.second->connections());
if (!tubeConns.empty()) {
conns.insert(tube, tubeConns);
}
}
return conns;
}
void StreamTubeClient::onInvokedForTube(
const AccountPtr &acc,
const StreamTubeChannelPtr &tube,
const QDateTime &time,
const ChannelRequestHints &hints)
{
Q_ASSERT(isRegistered());
Q_ASSERT(!tube->isRequested());
Q_ASSERT(tube->isValid()); // SSTH won't emit invalid tubes
if (mPriv->tubes.contains(tube)) {
debug() << "Ignoring StreamTubeClient reinvocation for tube" << tube->objectPath();
return;
}
IncomingStreamTubeChannelPtr incoming = IncomingStreamTubeChannelPtr::qObjectCast(tube);
if (!incoming) {
warning() << "The ChannelFactory used by StreamTubeClient must construct" <<
"IncomingStreamTubeChannel subclasses for Requested=false StreamTubes";
tube->requestClose();
return;
}
TubeWrapper *wrapper = 0;
if (mPriv->acceptsAsTcp) {
QPair<QHostAddress, quint16> srcAddr =
qMakePair(QHostAddress(QHostAddress::Any), quint16(0));
if (mPriv->tcpGenerator) {
srcAddr = mPriv->tcpGenerator->nextSourceAddress(acc, incoming);
}
wrapper = new TubeWrapper(acc, incoming, srcAddr.first, srcAddr.second);
} else {
Q_ASSERT(mPriv->acceptsAsUnix); // we should only be registered when we're set to accept as either TCP or Unix
wrapper = new TubeWrapper(acc, incoming, mPriv->requireCredentials);
}
connect(wrapper,
SIGNAL(acceptFinished(TubeWrapper*,Tp::PendingStreamTubeConnection*)),
SLOT(onAcceptFinished(TubeWrapper*,Tp::PendingStreamTubeConnection*)));
connect(tube.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onTubeInvalidated(Tp::DBusProxy*,QString,QString)));
if (monitorsConnections()) {
connect(wrapper,
SIGNAL(newConnection(TubeWrapper*,uint)),
SLOT(onNewConnection(TubeWrapper*,uint)));
connect(wrapper,
SIGNAL(connectionClosed(TubeWrapper*,uint,QString,QString)),
SLOT(onConnectionClosed(TubeWrapper*,uint,QString,QString)));
}
mPriv->tubes.insert(tube, wrapper);
emit tubeOffered(acc, incoming);
}
void StreamTubeClient::onAcceptFinished(TubeWrapper *wrapper, PendingStreamTubeConnection *conn)
{
Q_ASSERT(wrapper != NULL);
Q_ASSERT(conn != NULL);
if (!mPriv->tubes.contains(wrapper->mTube)) {
debug() << "StreamTubeClient ignoring Accept result for invalidated tube"
<< wrapper->mTube->objectPath();
return;
}
if (conn->isError()) {
warning() << "StreamTubeClient couldn't accept tube" << wrapper->mTube->objectPath() << '-'
<< conn->errorName() << ':' << conn->errorMessage();
if (wrapper->mTube->isValid()) {
wrapper->mTube->requestClose();
}
wrapper->mTube->disconnect(this);
emit tubeClosed(wrapper->mAcc, wrapper->mTube, conn->errorName(), conn->errorMessage());
mPriv->tubes.remove(wrapper->mTube);
wrapper->deleteLater();
return;
}
debug() << "StreamTubeClient accepted tube" << wrapper->mTube->objectPath();
if (conn->addressType() == SocketAddressTypeIPv4
|| conn->addressType() == SocketAddressTypeIPv6) {
QPair<QHostAddress, quint16> addr = conn->ipAddress();
emit tubeAcceptedAsTcp(addr.first, addr.second, wrapper->mSourceAddress,
wrapper->mSourcePort, wrapper->mAcc, wrapper->mTube);
} else {
emit tubeAcceptedAsUnix(conn->localAddress(), conn->requiresCredentials(),
conn->credentialByte(), wrapper->mAcc, wrapper->mTube);
}
}
void StreamTubeClient::onTubeInvalidated(Tp::DBusProxy *proxy, const QString &error,
const QString &message)
{
StreamTubeChannelPtr tube(qobject_cast<StreamTubeChannel *>(proxy));
Q_ASSERT(!tube.isNull());
TubeWrapper *wrapper = mPriv->tubes.value(tube);
if (!wrapper) {
// Accept finish with error already removed it
return;
}
debug() << "Client StreamTube" << tube->objectPath() << "invalidated - " << error << ':'
<< message;
emit tubeClosed(wrapper->mAcc, wrapper->mTube, error, message);
mPriv->tubes.remove(tube);
delete wrapper;
}
void StreamTubeClient::onNewConnection(
TubeWrapper *wrapper,
uint conn)
{
Q_ASSERT(monitorsConnections());
emit newConnection(wrapper->mAcc, wrapper->mTube, conn);
}
void StreamTubeClient::onConnectionClosed(
TubeWrapper *wrapper,
uint conn,
const QString &error,
const QString &message)
{
Q_ASSERT(monitorsConnections());
emit connectionClosed(wrapper->mAcc, wrapper->mTube, conn, error, message);
}
} // Tp
<commit_msg>STC: Don't attempt to use Port access control if it's not supported<commit_after>/**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2011 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/StreamTubeClient>
#include "TelepathyQt4/stream-tube-client-internal.h"
#include "TelepathyQt4/_gen/stream-tube-client.moc.hpp"
#include "TelepathyQt4/_gen/stream-tube-client-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include "TelepathyQt4/simple-stream-tube-handler.h"
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/ClientRegistrar>
#include <TelepathyQt4/IncomingStreamTubeChannel>
#include <TelepathyQt4/PendingStreamTubeConnection>
#include <TelepathyQt4/StreamTubeChannel>
#include <QAbstractSocket>
#include <QHash>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT StreamTubeClient::Private
{
Private(const ClientRegistrarPtr ®istrar,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &maybeClientName,
bool monitorConnections,
bool bypassApproval)
: registrar(registrar),
handler(SimpleStreamTubeHandler::create(
p2pServices, roomServices, false, monitorConnections, bypassApproval)),
clientName(maybeClientName),
isRegistered(false),
acceptsAsTcp(false), acceptsAsUnix(false),
tcpGenerator(0), requireCredentials(false)
{
if (clientName.isEmpty()) {
clientName = QString::fromLatin1("TpQt4STubeClient_%1_%2")
.arg(registrar->dbusConnection().baseService()
.replace(QLatin1Char(':'), QLatin1Char('_'))
.replace(QLatin1Char('.'), QLatin1Char('_')))
.arg((intptr_t) this, 0, 16);
}
}
void ensureRegistered()
{
if (isRegistered) {
return;
}
debug() << "Register StreamTubeClient with name " << clientName;
if (registrar->registerClient(handler, clientName)) {
isRegistered = true;
} else {
warning() << "StreamTubeClient" << clientName
<< "registration failed";
}
}
ClientRegistrarPtr registrar;
SharedPtr<SimpleStreamTubeHandler> handler;
QString clientName;
bool isRegistered;
bool acceptsAsTcp, acceptsAsUnix;
const TcpSourceAddressGenerator *tcpGenerator;
bool requireCredentials;
QHash<StreamTubeChannelPtr, TubeWrapper *> tubes;
};
StreamTubeClient::TubeWrapper::TubeWrapper(
const AccountPtr &acc,
const IncomingStreamTubeChannelPtr &tube,
const QHostAddress &sourceAddress,
quint16 sourcePort)
: mAcc(acc), mTube(tube), mSourceAddress(sourceAddress), mSourcePort(sourcePort)
{
if (sourcePort != 0) {
if ((sourceAddress.protocol() == QAbstractSocket::IPv4Protocol &&
!tube->supportsIPv4SocketsWithSpecifiedAddress()) ||
(sourceAddress.protocol() == QAbstractSocket::IPv6Protocol &&
!tube->supportsIPv6SocketsWithSpecifiedAddress())) {
debug() << "StreamTubeClient falling back to Localhost AC for tube" <<
tube->objectPath();
mSourceAddress = sourceAddress.protocol() == QAbstractSocket::IPv4Protocol ?
QHostAddress::Any : QHostAddress::AnyIPv6;
mSourcePort = 0;
}
}
connect(tube->acceptTubeAsTcpSocket(mSourceAddress, mSourcePort),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onTubeAccepted(Tp::PendingOperation*)));
connect(tube.data(),
SIGNAL(newConnection(uint)),
SLOT(onNewConnection(uint)));
connect(tube.data(),
SIGNAL(connectionClosed(uint,QString,QString)),
SLOT(onConnectionClosed(uint,QString,QString)));
}
StreamTubeClient::TubeWrapper::TubeWrapper(
const AccountPtr &acc,
const IncomingStreamTubeChannelPtr &tube,
bool requireCredentials)
: mAcc(acc), mTube(tube), mSourcePort(0)
{
connect(tube->acceptTubeAsUnixSocket(requireCredentials),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onTubeAccepted(Tp::PendingOperation*)));
connect(tube.data(),
SIGNAL(newConnection(uint)),
SLOT(onNewConnection(uint)));
connect(tube.data(),
SIGNAL(connectionClosed(uint,QString,QString)),
SLOT(onConnectionClosed(uint,QString,QString)));
}
void StreamTubeClient::TubeWrapper::onTubeAccepted(Tp::PendingOperation *op)
{
emit acceptFinished(this, qobject_cast<Tp::PendingStreamTubeConnection *>(op));
}
void StreamTubeClient::TubeWrapper::onNewConnection(uint conn)
{
emit newConnection(this, conn);
}
void StreamTubeClient::TubeWrapper::onConnectionClosed(uint conn, const QString &error,
const QString &message)
{
emit connectionClosed(this, conn, error, message);
}
StreamTubeClientPtr StreamTubeClient::create(
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval,
const AccountFactoryConstPtr &accountFactory,
const ConnectionFactoryConstPtr &connectionFactory,
const ChannelFactoryConstPtr &channelFactory,
const ContactFactoryConstPtr &contactFactory)
{
return create(
QDBusConnection::sessionBus(),
accountFactory,
connectionFactory,
channelFactory,
contactFactory,
p2pServices,
roomServices,
clientName,
monitorConnections,
bypassApproval);
}
StreamTubeClientPtr StreamTubeClient::create(
const QDBusConnection &bus,
const AccountFactoryConstPtr &accountFactory,
const ConnectionFactoryConstPtr &connectionFactory,
const ChannelFactoryConstPtr &channelFactory,
const ContactFactoryConstPtr &contactFactory,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
{
return create(
ClientRegistrar::create(
bus,
accountFactory,
connectionFactory,
channelFactory,
contactFactory),
p2pServices,
roomServices,
clientName,
monitorConnections,
bypassApproval);
}
StreamTubeClientPtr StreamTubeClient::create(
const AccountManagerPtr &accountManager,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
{
return create(
accountManager->dbusConnection(),
accountManager->accountFactory(),
accountManager->connectionFactory(),
accountManager->channelFactory(),
accountManager->contactFactory(),
p2pServices,
roomServices,
clientName,
monitorConnections,
bypassApproval);
}
StreamTubeClientPtr StreamTubeClient::create(
const ClientRegistrarPtr ®istrar,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
{
return StreamTubeClientPtr(
new StreamTubeClient(registrar, p2pServices, roomServices, clientName,
monitorConnections, bypassApproval));
}
StreamTubeClient::StreamTubeClient(
const ClientRegistrarPtr ®istrar,
const QStringList &p2pServices,
const QStringList &roomServices,
const QString &clientName,
bool monitorConnections,
bool bypassApproval)
: mPriv(new Private(registrar, p2pServices, roomServices, clientName, monitorConnections, bypassApproval))
{
connect(mPriv->handler.data(),
SIGNAL(invokedForTube(
Tp::AccountPtr,
Tp::StreamTubeChannelPtr,
QDateTime,
Tp::ChannelRequestHints)),
SLOT(onInvokedForTube(
Tp::AccountPtr,
Tp::StreamTubeChannelPtr,
QDateTime,
Tp::ChannelRequestHints)));
}
/**
* Class destructor.
*/
StreamTubeClient::~StreamTubeClient()
{
if (isRegistered()) {
mPriv->registrar->unregisterClient(mPriv->handler);
}
foreach (TubeWrapper *wrapper, mPriv->tubes.values()) {
wrapper->deleteLater();
}
delete mPriv;
}
ClientRegistrarPtr StreamTubeClient::registrar() const
{
return mPriv->registrar;
}
QString StreamTubeClient::clientName() const
{
return mPriv->clientName;
}
bool StreamTubeClient::isRegistered() const
{
return mPriv->isRegistered;
}
bool StreamTubeClient::monitorsConnections() const
{
return mPriv->handler->monitorsConnections();
}
bool StreamTubeClient::acceptsAsTcp() const
{
return mPriv->acceptsAsTcp;
}
const StreamTubeClient::TcpSourceAddressGenerator *StreamTubeClient::generator() const
{
if (!acceptsAsTcp()) {
warning() << "StreamTubeClient::generator() used, but not accepting as TCP, returning 0";
return 0;
}
return mPriv->tcpGenerator;
}
bool StreamTubeClient::acceptsAsUnix() const
{
return mPriv->acceptsAsUnix;
}
void StreamTubeClient::setToAcceptAsTcp(const TcpSourceAddressGenerator *generator)
{
mPriv->tcpGenerator = generator;
mPriv->acceptsAsTcp = true;
mPriv->acceptsAsUnix = false;
mPriv->ensureRegistered();
}
void StreamTubeClient::setToAcceptAsUnix(bool requireCredentials)
{
mPriv->tcpGenerator = 0;
mPriv->acceptsAsTcp = false;
mPriv->acceptsAsUnix = true;
mPriv->requireCredentials = requireCredentials;
mPriv->ensureRegistered();
}
QList<QPair<AccountPtr, IncomingStreamTubeChannelPtr> > StreamTubeClient::tubes() const
{
QList<QPair<AccountPtr, IncomingStreamTubeChannelPtr> > tubes;
foreach (TubeWrapper *wrapper, mPriv->tubes.values()) {
tubes.push_back(qMakePair(wrapper->mAcc, wrapper->mTube));
}
return tubes;
}
QHash<QPair<AccountPtr, IncomingStreamTubeChannelPtr>, QSet<uint> >
StreamTubeClient::connections() const
{
QHash<QPair<AccountPtr, IncomingStreamTubeChannelPtr>, QSet<uint> > conns;
if (!monitorsConnections()) {
warning() << "StreamTubeClient::connections() used, but connection monitoring is disabled";
return conns;
}
QPair<AccountPtr, IncomingStreamTubeChannelPtr> tube;
foreach (tube, tubes()) {
QSet<uint> tubeConns = QSet<uint>::fromList(tube.second->connections());
if (!tubeConns.empty()) {
conns.insert(tube, tubeConns);
}
}
return conns;
}
void StreamTubeClient::onInvokedForTube(
const AccountPtr &acc,
const StreamTubeChannelPtr &tube,
const QDateTime &time,
const ChannelRequestHints &hints)
{
Q_ASSERT(isRegistered());
Q_ASSERT(!tube->isRequested());
Q_ASSERT(tube->isValid()); // SSTH won't emit invalid tubes
if (mPriv->tubes.contains(tube)) {
debug() << "Ignoring StreamTubeClient reinvocation for tube" << tube->objectPath();
return;
}
IncomingStreamTubeChannelPtr incoming = IncomingStreamTubeChannelPtr::qObjectCast(tube);
if (!incoming) {
warning() << "The ChannelFactory used by StreamTubeClient must construct" <<
"IncomingStreamTubeChannel subclasses for Requested=false StreamTubes";
tube->requestClose();
return;
}
TubeWrapper *wrapper = 0;
if (mPriv->acceptsAsTcp) {
QPair<QHostAddress, quint16> srcAddr =
qMakePair(QHostAddress(QHostAddress::Any), quint16(0));
if (mPriv->tcpGenerator) {
srcAddr = mPriv->tcpGenerator->nextSourceAddress(acc, incoming);
}
wrapper = new TubeWrapper(acc, incoming, srcAddr.first, srcAddr.second);
} else {
Q_ASSERT(mPriv->acceptsAsUnix); // we should only be registered when we're set to accept as either TCP or Unix
wrapper = new TubeWrapper(acc, incoming, mPriv->requireCredentials);
}
connect(wrapper,
SIGNAL(acceptFinished(TubeWrapper*,Tp::PendingStreamTubeConnection*)),
SLOT(onAcceptFinished(TubeWrapper*,Tp::PendingStreamTubeConnection*)));
connect(tube.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onTubeInvalidated(Tp::DBusProxy*,QString,QString)));
if (monitorsConnections()) {
connect(wrapper,
SIGNAL(newConnection(TubeWrapper*,uint)),
SLOT(onNewConnection(TubeWrapper*,uint)));
connect(wrapper,
SIGNAL(connectionClosed(TubeWrapper*,uint,QString,QString)),
SLOT(onConnectionClosed(TubeWrapper*,uint,QString,QString)));
}
mPriv->tubes.insert(tube, wrapper);
emit tubeOffered(acc, incoming);
}
void StreamTubeClient::onAcceptFinished(TubeWrapper *wrapper, PendingStreamTubeConnection *conn)
{
Q_ASSERT(wrapper != NULL);
Q_ASSERT(conn != NULL);
if (!mPriv->tubes.contains(wrapper->mTube)) {
debug() << "StreamTubeClient ignoring Accept result for invalidated tube"
<< wrapper->mTube->objectPath();
return;
}
if (conn->isError()) {
warning() << "StreamTubeClient couldn't accept tube" << wrapper->mTube->objectPath() << '-'
<< conn->errorName() << ':' << conn->errorMessage();
if (wrapper->mTube->isValid()) {
wrapper->mTube->requestClose();
}
wrapper->mTube->disconnect(this);
emit tubeClosed(wrapper->mAcc, wrapper->mTube, conn->errorName(), conn->errorMessage());
mPriv->tubes.remove(wrapper->mTube);
wrapper->deleteLater();
return;
}
debug() << "StreamTubeClient accepted tube" << wrapper->mTube->objectPath();
if (conn->addressType() == SocketAddressTypeIPv4
|| conn->addressType() == SocketAddressTypeIPv6) {
QPair<QHostAddress, quint16> addr = conn->ipAddress();
emit tubeAcceptedAsTcp(addr.first, addr.second, wrapper->mSourceAddress,
wrapper->mSourcePort, wrapper->mAcc, wrapper->mTube);
} else {
emit tubeAcceptedAsUnix(conn->localAddress(), conn->requiresCredentials(),
conn->credentialByte(), wrapper->mAcc, wrapper->mTube);
}
}
void StreamTubeClient::onTubeInvalidated(Tp::DBusProxy *proxy, const QString &error,
const QString &message)
{
StreamTubeChannelPtr tube(qobject_cast<StreamTubeChannel *>(proxy));
Q_ASSERT(!tube.isNull());
TubeWrapper *wrapper = mPriv->tubes.value(tube);
if (!wrapper) {
// Accept finish with error already removed it
return;
}
debug() << "Client StreamTube" << tube->objectPath() << "invalidated - " << error << ':'
<< message;
emit tubeClosed(wrapper->mAcc, wrapper->mTube, error, message);
mPriv->tubes.remove(tube);
delete wrapper;
}
void StreamTubeClient::onNewConnection(
TubeWrapper *wrapper,
uint conn)
{
Q_ASSERT(monitorsConnections());
emit newConnection(wrapper->mAcc, wrapper->mTube, conn);
}
void StreamTubeClient::onConnectionClosed(
TubeWrapper *wrapper,
uint conn,
const QString &error,
const QString &message)
{
Q_ASSERT(monitorsConnections());
emit connectionClosed(wrapper->mAcc, wrapper->mTube, conn, error, message);
}
} // Tp
<|endoftext|> |
<commit_before>//
// ImportOSM.cpp: The main Builder class of the VTBuilder
//
// Copyright (c) 2006-2012 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "vtui/Helper.h"
#include "Builder.h"
// Layers
//#include "RawLayer.h"
#include "RoadLayer.h"
#include "StructLayer.h"
#include "WaterLayer.h"
////////////////////////////////////////////////////////////////////////
// Visitor class, for XML parsing of an OpenStreetMap file.
//
struct OSMNode {
DPoint2 p;
int id;
bool signal_lights;
};
class VisitorOSM : public XMLVisitor
{
public:
VisitorOSM(RoadMapEdit *rm) : m_state(0), m_pMap(rm) {}
void startElement(const char *name, const XMLAttributes &atts);
void endElement(const char *name);
void data(const char *s, int length);
void SetSignalLights();
private:
//string m_data;
int m_state;
int m_rec;
std::vector<OSMNode> m_nodes;
int find_node(int id)
{
for (size_t i = 0; i < m_nodes.size(); i++)
if (m_nodes[i].id == id)
return (int)i;
return -1;
}
std::vector<int> m_refs;
RoadMapEdit *m_pMap;
LinkEdit *m_pLink;
bool m_bAddLink;
};
void VisitorOSM::SetSignalLights()
{
// For all the nodes which have signal lights, set the state
for (uint i = 0; i < m_nodes.size(); i++)
{
OSMNode &node = m_nodes[i];
if (node.signal_lights)
{
TNode *tnode = m_pMap->FindNodeByID(node.id);
if (tnode)
{
for (int j = 0; j < tnode->NumLinks(); j++)
tnode->SetIntersectType(j, IT_LIGHT);
}
}
}
m_pMap->GuessIntersectionTypes();
}
void VisitorOSM::startElement(const char *name, const XMLAttributes &atts)
{
const char *val;
if (m_state == 0)
{
if (!strcmp(name, "node"))
{
DPoint2 p;
int id;
val = atts.getValue("id");
if (val)
id = atoi(val);
val = atts.getValue("lon");
if (val)
p.x = atof(val);
val = atts.getValue("lat");
if (val)
p.y = atof(val);
//TNode *node = m_pMap->NewNode();
//node->m_p = p;
//node->m_id = id;
//m_pMap->AddNode(node)
OSMNode node;
node.p = p;
node.id = id;
node.signal_lights = false;
m_nodes.push_back(node);
m_state = 1;
}
else if (!strcmp(name, "way"))
{
m_pLink = m_pMap->NewLink();
m_pLink->m_iLanes = 2;
m_refs.clear();
m_state = 2;
m_bAddLink = true;
}
}
else if (m_state == 1 && !strcmp(name, "tag"))
{
vtString key, value;
val = atts.getValue("k");
if (val)
key = val;
val = atts.getValue("v");
if (val)
value = val;
// Node key/value
if (key == "highway")
{
if (value == "traffic_signals") //
{
m_nodes[m_nodes.size()-1].signal_lights = true;
}
}
}
else if (m_state == 2)
{
if (!strcmp(name, "nd"))
{
val = atts.getValue("ref");
if (val)
{
int ref = atoi(val);
m_refs.push_back(ref);
}
}
else if (!strcmp(name, "tag"))
{
vtString key, value;
val = atts.getValue("k");
if (val)
key = val;
val = atts.getValue("v");
if (val)
value = val;
// There are hundreds of possible Way tags
if (key == "natural") // value is coastline, marsh, etc.
m_bAddLink = false;
if (key == "route" && value == "ferry")
m_bAddLink = false;
if (key == "highway")
{
if (value == "motorway") // like a freeway
m_pLink->m_iLanes = 4;
if (value == "motorway_link") // on/offramp
m_pLink->m_iLanes = 1;
if (value == "unclassified") // lowest form of the interconnecting grid network.
m_pLink->m_iLanes = 1;
if (value == "unsurfaced")
m_pLink->m_Surface = SURFT_DIRT;
if (value == "track")
{
m_pLink->m_iLanes = 1;
m_pLink->m_Surface = SURFT_2TRACK;
}
if (value == "bridleway")
m_pLink->m_Surface = SURFT_GRAVEL;
if (value == "footway")
{
m_pLink->m_iLanes = 1;
m_pLink->m_Surface = SURFT_GRAVEL;
}
}
if (key == "waterway")
m_bAddLink = false;
if (key == "railway")
m_pLink->m_Surface = SURFT_RAILROAD;
if (key == "aeroway")
m_bAddLink = false;
if (key == "aerialway")
m_bAddLink = false;
if (key == "power")
m_bAddLink = false;
if (key == "man_made")
m_bAddLink = false;
if (key == "leisure")
m_bAddLink = false;
if (key == "amenity")
m_bAddLink = false;
if (key == "abutters")
m_bAddLink = false;
if (key == "surface")
{
if (value == "paved")
m_pLink->m_Surface = SURFT_PAVED;
if (value == "unpaved")
m_pLink->m_Surface = SURFT_GRAVEL;
}
if (key == "lanes")
m_pLink->m_iLanes = atoi(value);
}
}
}
void VisitorOSM::endElement(const char *name)
{
if (m_state == 1 && !strcmp(name, "node"))
{
m_state = 0;
}
else if (m_state == 2 && !strcmp(name, "way"))
{
// Look at the referenced nodes, turn them into a vt link
uint refs = (uint)m_refs.size();
// must have at least 2 refs
if (refs >= 2 && m_bAddLink == true)
{
int ref_first = m_refs[0];
int ref_last = m_refs[refs-1];
int idx_first = find_node(ref_first);
int idx_last = find_node(ref_last);
TNode *node0 = m_pMap->FindNodeByID(m_nodes[idx_first].id);
if (!node0)
{
// doesn't exist, create it
node0 = m_pMap->NewNode();
node0->SetPos(m_nodes[idx_first].p);
node0->m_id = m_nodes[idx_first].id;
m_pMap->AddNode(node0);
}
m_pLink->SetNode(0, node0);
TNode *node1 = m_pMap->FindNodeByID(m_nodes[idx_last].id);
if (!node1)
{
// doesn't exist, create it
node1 = m_pMap->NewNode();
node1->SetPos(m_nodes[idx_last].p);
node1->m_id = m_nodes[idx_last].id;
m_pMap->AddNode(node1);
}
m_pLink->SetNode(1, node1);
// Copy all the points
for (uint r = 0; r < refs; r++)
{
int idx = find_node(m_refs[r]);
m_pLink->Append(m_nodes[idx].p);
}
m_pMap->AddLink(m_pLink);
// point node to links
node0->AddLink(m_pLink);
node1->AddLink(m_pLink);
m_pLink->ComputeExtent();
m_pLink = NULL;
}
m_state = 0;
}
}
void VisitorOSM::data(const char *s, int length)
{
//m_data.append(string(s, length));
}
/**
* Import what we can from OpenStreetMap.
*/
void Builder::ImportDataFromOSM(const wxString &strFileName)
{
// Avoid trouble with '.' and ',' in Europe
// OSM always has English punctuation
LocaleWrap normal_numbers(LC_NUMERIC, "C");
std::string fname_local = strFileName.ToUTF8();
// OSM is always in Geo WGS84
vtProjection proj;
proj.SetWellKnownGeogCS("WGS84");
vtRoadLayer *rlayer = new vtRoadLayer;
rlayer->SetProjection(proj);
VisitorOSM visitor(rlayer);
try
{
readXML(fname_local, visitor, NULL);
}
catch (xh_exception &ex)
{
DisplayAndLog(ex.getFormattedMessage().c_str());
return;
}
visitor.SetSignalLights();
bool success = AddLayerWithCheck(rlayer, true);
}
<commit_msg>Improving import of roads from OSM<commit_after>//
// ImportOSM.cpp: The main Builder class of the VTBuilder
//
// Copyright (c) 2006-2012 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <map>
#include "vtui/Helper.h"
#include "Builder.h"
// Layers
//#include "RawLayer.h"
#include "RoadLayer.h"
#include "StructLayer.h"
#include "WaterLayer.h"
////////////////////////////////////////////////////////////////////////
// Visitor class, for XML parsing of an OpenStreetMap file.
//
struct OSMNode {
DPoint2 p;
bool signal_lights;
};
class VisitorOSM : public XMLVisitor
{
public:
VisitorOSM(RoadMapEdit *rm) : m_state(0), m_pMap(rm) {}
void startElement(const char *name, const XMLAttributes &atts);
void endElement(const char *name);
void data(const char *s, int length);
void SetSignalLights();
private:
//string m_data;
int m_state;
int m_rec;
typedef std::map<int, OSMNode> NodeMap;
NodeMap m_nodes;
std::vector<int> m_refs;
RoadMapEdit *m_pMap;
LayerType m_WayType;
int m_iRoadLanes;
SurfaceType m_eSurfaceType;
};
void VisitorOSM::SetSignalLights()
{
// For all the nodes which have signal lights, set the state
for (NodeMap::iterator it = m_nodes.begin(); it != m_nodes.end(); it++)
{
OSMNode &node = it->second;
if (node.signal_lights)
{
TNode *tnode = m_pMap->FindNodeByID(it->first);
if (tnode)
{
for (int j = 0; j < tnode->NumLinks(); j++)
tnode->SetIntersectType(j, IT_LIGHT);
}
}
}
m_pMap->GuessIntersectionTypes();
}
void VisitorOSM::startElement(const char *name, const XMLAttributes &atts)
{
const char *val;
if (m_state == 0)
{
if (!strcmp(name, "node"))
{
DPoint2 p;
int id;
val = atts.getValue("id");
if (val)
id = atoi(val);
val = atts.getValue("lon");
if (val)
p.x = atof(val);
val = atts.getValue("lat");
if (val)
p.y = atof(val);
OSMNode node;
node.p = p;
node.signal_lights = false;
m_nodes[id] = node;
m_state = 1;
}
else if (!strcmp(name, "way"))
{
m_refs.clear();
m_state = 2;
m_WayType = LT_UNKNOWN;
// Defaults
m_iRoadLanes = 2;
m_eSurfaceType = SURFT_PAVED;
}
}
else if (m_state == 1 && !strcmp(name, "tag"))
{
vtString key, value;
val = atts.getValue("k");
if (val)
key = val;
val = atts.getValue("v");
if (val)
value = val;
// Node key/value
if (key == "highway")
{
if (value == "traffic_signals") //
{
m_nodes[m_nodes.size()-1].signal_lights = true;
}
}
}
else if (m_state == 2)
{
if (!strcmp(name, "nd"))
{
val = atts.getValue("ref");
if (val)
{
int ref = atoi(val);
m_refs.push_back(ref);
}
}
else if (!strcmp(name, "tag"))
{
vtString key, value;
val = atts.getValue("k");
if (val)
key = val;
val = atts.getValue("v");
if (val)
value = val;
// There are hundreds of possible Way tags
if (key == "natural") // value is coastline, marsh, etc.
m_WayType = LT_UNKNOWN;
if (key == "route" && value == "ferry")
m_WayType = LT_UNKNOWN;
if (key == "highway")
{
m_WayType = LT_ROAD;
if (value == "motorway") // like a freeway
m_iRoadLanes = 4;
if (value == "motorway_link") // on/offramp
m_iRoadLanes = 1;
if (value == "unclassified") // lowest form of the interconnecting grid network.
m_iRoadLanes = 1;
if (value == "unsurfaced")
m_eSurfaceType = SURFT_DIRT;
if (value == "track")
{
m_iRoadLanes = 1;
m_eSurfaceType = SURFT_2TRACK;
}
if (value == "bridleway")
m_eSurfaceType = SURFT_GRAVEL;
if (value == "footway")
{
m_iRoadLanes = 1;
m_eSurfaceType = SURFT_GRAVEL;
}
if (value == "primary") // An actual highway, or arterial
m_iRoadLanes = 2; // Doesn't tell us much useful
}
if (key == "waterway")
m_WayType = LT_WATER;
if (key == "railway")
m_eSurfaceType = SURFT_RAILROAD;
if (key == "aeroway")
m_WayType = LT_UNKNOWN; // Airport features, like runways
if (key == "aerialway")
m_WayType = LT_UNKNOWN;
if (key == "power")
m_WayType = LT_UNKNOWN;
if (key == "man_made")
m_WayType = LT_UNKNOWN; // Piers, towers, windmills, etc.
if (key == "leisure")
m_WayType = LT_UNKNOWN; // gardens, golf courses, public lawns, etc.
if (key == "amenity")
m_WayType = LT_UNKNOWN; // mostly, types of building classified by use
if (key == "abutters")
{
// describes the predominant usage of land along a road or other way
}
if (key == "surface")
{
if (value == "asphalt")
m_eSurfaceType = SURFT_PAVED;
if (value == "compacted")
m_eSurfaceType = SURFT_GRAVEL;
if (value == "concrete")
m_eSurfaceType = SURFT_PAVED;
if (value == "dirt")
m_eSurfaceType = SURFT_DIRT;
if (value == "earth")
m_eSurfaceType = SURFT_DIRT;
if (value == "fine_gravel")
m_eSurfaceType = SURFT_GRAVEL;
if (value == "ground")
m_eSurfaceType = SURFT_2TRACK; // or SURFT_TRAIL
if (value == "gravel")
m_eSurfaceType = SURFT_GRAVEL;
if (value == "paved")
m_eSurfaceType = SURFT_PAVED;
if (value == "sand")
m_eSurfaceType = SURFT_DIRT;
if (value == "unpaved")
m_eSurfaceType = SURFT_GRAVEL; // or SURFT_DIRT
}
if (key == "lanes")
m_iRoadLanes = atoi(value);
}
}
}
void VisitorOSM::endElement(const char *name)
{
if (m_state == 1 && !strcmp(name, "node"))
{
m_state = 0;
}
else if (m_state == 2 && !strcmp(name, "way"))
{
// Look at the referenced nodes, turn them into a vt link
uint refs = (uint)m_refs.size();
// must have at least 2 refs
if (refs >= 2 && m_WayType == LT_ROAD)
{
LinkEdit *link = m_pMap->NewLink();
link->m_iLanes = m_iRoadLanes;
link->m_Surface = m_eSurfaceType;
int ref_first = m_refs[0];
int ref_last = m_refs[refs-1];
TNode *node0 = m_pMap->FindNodeByID(ref_first);
if (!node0)
{
// doesn't exist, create it
node0 = m_pMap->NewNode();
node0->SetPos(m_nodes[ref_first].p);
node0->m_id = ref_first;
m_pMap->AddNode(node0);
}
link->SetNode(0, node0);
TNode *node1 = m_pMap->FindNodeByID(ref_last);
if (!node1)
{
// doesn't exist, create it
node1 = m_pMap->NewNode();
node1->SetPos(m_nodes[ref_last].p);
node1->m_id = ref_last;
m_pMap->AddNode(node1);
}
link->SetNode(1, node1);
// Copy all the points
for (uint r = 0; r < refs; r++)
{
int idx = m_refs[r];
link->Append(m_nodes[idx].p);
}
m_pMap->AddLink(link);
// point node to links
node0->AddLink(link);
node1->AddLink(link);
link->ComputeExtent();
}
m_state = 0;
}
}
void VisitorOSM::data(const char *s, int length)
{
//m_data.append(string(s, length));
}
/**
* Import what we can from OpenStreetMap.
*/
void Builder::ImportDataFromOSM(const wxString &strFileName)
{
// Avoid trouble with '.' and ',' in Europe
// OSM always has English punctuation
LocaleWrap normal_numbers(LC_NUMERIC, "C");
std::string fname_local = strFileName.ToUTF8();
// OSM is always in Geo WGS84
vtProjection proj;
proj.SetWellKnownGeogCS("WGS84");
vtRoadLayer *rlayer = new vtRoadLayer;
rlayer->SetProjection(proj);
VisitorOSM visitor(rlayer);
try
{
readXML(fname_local, visitor, NULL);
}
catch (xh_exception &ex)
{
DisplayAndLog(ex.getFormattedMessage().c_str());
return;
}
visitor.SetSignalLights();
bool success = AddLayerWithCheck(rlayer, true);
}
<|endoftext|> |
<commit_before>//
// Content3d.cpp
//
// 3D Content Management class.
//
// Copyright (c) 2003-2004 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//
#include "vtlib/vtlib.h"
#include "vtdata/FilePath.h"
#include "vtdata/vtLog.h"
#include "Content3d.h"
#include "TerrainScene.h"
vtItem3d::vtItem3d()
{
m_pNode = NULL;
}
vtItem3d::~vtItem3d()
{
if (m_pNode)
m_pNode->Release();
m_pNode = NULL;
}
/**
* Load the model(s) associated with an item. If there are several models,
* generally these are different levels of detail (LOD) for the item.
*/
bool vtItem3d::LoadModels()
{
VTLOG(" Loading models for item.\n");
if (m_pNode)
return true; // already loaded
int i, models = NumModels();
// attempt to instantiate the item
vtLOD *pLod=NULL;
if (models > 1)
{
pLod = new vtLOD;
m_pNode = pLod;
}
float ranges[20];
ranges[0] = 0.0f;
for (i = 0; i < models; i++)
{
vtModel *model = GetModel(i);
vtNode *pNode = NULL;
// perhaps it's directly resolvable
pNode = vtNode::LoadModel(model->m_filename);
// if there are some data path(s) to search, use them
if (!pNode)
{
vtString fullpath = FindFileOnPaths(vtGetDataPath(), model->m_filename);
if (fullpath != "")
pNode = vtNode::LoadModel(fullpath);
}
if (pNode)
VTLOG(" Loaded successfully.\n");
else
{
VTLOG(" Couldn't load model from %hs\n",
(const char *) model->m_filename);
return false;
}
if (model->m_scale != 1.0f)
{
// Wrap in a transform node so that we can scale/rotate the node
vtTransform *pTrans = new vtTransform();
pTrans->SetName2("scaling xform");
pTrans->AddChild(pNode);
pTrans->Identity();
pTrans->Scale3(model->m_scale, model->m_scale, model->m_scale);
pNode = pTrans;
}
if (models > 1)
pLod->AddChild(pNode);
else
m_pNode = pNode;
if (models > 1)
ranges[i+1] = model->m_distance;
}
if (models > 1)
pLod->SetRanges(ranges, models+1);
return true;
}
//
// An item can store some extents, which give a rough indication of
// the 2D area taken up by the model, useful for drawing it in traditional
// 2D GIS environments like VTBuilder.
//
// Whenever a model is added, or the scale factor changes, the extents
// should be updated.
//
void vtItem3d::UpdateExtents()
{
m_extents.Empty();
if (m_pNode == NULL)
return;
// A good way to do it would be to try to get a tight bounding box,
// but that's non-trivial to compute with OSG. For now, settle for
// making a rectangle from the loose bounding sphere.
// Both the 3D model and the extents are in approximate meters and
// centered on the item's local origin.
FSphere sph;
m_pNode->GetBoundSphere(sph);
m_extents.left = sph.center.x - sph.radius;
m_extents.right = sph.center.x + sph.radius;
// However, the XY extents of the extents have Y pointing up, whereas
// the world coords have Z pointing down.
m_extents.top = -sph.center.z + sph.radius;
m_extents.bottom = -sph.center.z - sph.radius;
}
///////////////////////////////////////////////////////////////////////
vtContentManager3d::vtContentManager3d()
{
m_pGroup = NULL;
}
void vtContentManager3d::ReleaseContents()
{
if (m_pGroup)
m_pGroup->Release();
m_pGroup = NULL;
}
vtContentManager3d::~vtContentManager3d()
{
ReleaseContents();
}
vtNode *vtContentManager3d::CreateNodeFromItemname(const char *itemname)
{
vtItem3d *pItem = (vtItem3d *) FindItemByName(itemname);
if (!pItem)
return NULL;
if (!pItem->m_pNode)
{
if (!pItem->LoadModels())
return NULL;
if (!m_pGroup)
{
m_pGroup = new vtGroup();
m_pGroup->SetName2("Content Manager Container Group");
}
// Add to content container: must keep a reference to each item's
// model node so it doesn't get deleted which the manager is alive.
m_pGroup->AddChild(pItem->m_pNode);
}
return pItem->m_pNode;
}
<commit_msg>don't release nodes in ~vtItem3d<commit_after>//
// Content3d.cpp
//
// 3D Content Management class.
//
// Copyright (c) 2003-2004 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//
#include "vtlib/vtlib.h"
#include "vtdata/FilePath.h"
#include "vtdata/vtLog.h"
#include "Content3d.h"
#include "TerrainScene.h"
vtItem3d::vtItem3d()
{
m_pNode = NULL;
}
vtItem3d::~vtItem3d()
{
// Don't need to explicitly release the item's node here, because all nodes
// are released when the the manager's group is released.
m_pNode = NULL;
}
/**
* Load the model(s) associated with an item. If there are several models,
* generally these are different levels of detail (LOD) for the item.
*/
bool vtItem3d::LoadModels()
{
VTLOG(" Loading models for item.\n");
if (m_pNode)
return true; // already loaded
int i, models = NumModels();
// attempt to instantiate the item
vtLOD *pLod=NULL;
if (models > 1)
{
pLod = new vtLOD;
m_pNode = pLod;
}
float ranges[20];
ranges[0] = 0.0f;
for (i = 0; i < models; i++)
{
vtModel *model = GetModel(i);
vtNode *pNode = NULL;
// perhaps it's directly resolvable
pNode = vtNode::LoadModel(model->m_filename);
// if there are some data path(s) to search, use them
if (!pNode)
{
vtString fullpath = FindFileOnPaths(vtGetDataPath(), model->m_filename);
if (fullpath != "")
pNode = vtNode::LoadModel(fullpath);
}
if (pNode)
VTLOG(" Loaded successfully.\n");
else
{
VTLOG(" Couldn't load model from %hs\n",
(const char *) model->m_filename);
return false;
}
if (model->m_scale != 1.0f)
{
// Wrap in a transform node so that we can scale/rotate the node
vtTransform *pTrans = new vtTransform();
pTrans->SetName2("scaling xform");
pTrans->AddChild(pNode);
pTrans->Identity();
pTrans->Scale3(model->m_scale, model->m_scale, model->m_scale);
pNode = pTrans;
}
if (models > 1)
pLod->AddChild(pNode);
else
m_pNode = pNode;
if (models > 1)
ranges[i+1] = model->m_distance;
}
if (models > 1)
pLod->SetRanges(ranges, models+1);
return true;
}
//
// An item can store some extents, which give a rough indication of
// the 2D area taken up by the model, useful for drawing it in traditional
// 2D GIS environments like VTBuilder.
//
// Whenever a model is added, or the scale factor changes, the extents
// should be updated.
//
void vtItem3d::UpdateExtents()
{
m_extents.Empty();
if (m_pNode == NULL)
return;
// A good way to do it would be to try to get a tight bounding box,
// but that's non-trivial to compute with OSG. For now, settle for
// making a rectangle from the loose bounding sphere.
// Both the 3D model and the extents are in approximate meters and
// centered on the item's local origin.
FSphere sph;
m_pNode->GetBoundSphere(sph);
m_extents.left = sph.center.x - sph.radius;
m_extents.right = sph.center.x + sph.radius;
// However, the XY extents of the extents have Y pointing up, whereas
// the world coords have Z pointing down.
m_extents.top = -sph.center.z + sph.radius;
m_extents.bottom = -sph.center.z - sph.radius;
}
///////////////////////////////////////////////////////////////////////
vtContentManager3d::vtContentManager3d()
{
m_pGroup = NULL;
}
void vtContentManager3d::ReleaseContents()
{
if (m_pGroup)
m_pGroup->Release();
m_pGroup = NULL;
}
vtContentManager3d::~vtContentManager3d()
{
ReleaseContents();
}
vtNode *vtContentManager3d::CreateNodeFromItemname(const char *itemname)
{
vtItem3d *pItem = (vtItem3d *) FindItemByName(itemname);
if (!pItem)
return NULL;
if (!pItem->m_pNode)
{
if (!pItem->LoadModels())
return NULL;
if (!m_pGroup)
{
m_pGroup = new vtGroup();
m_pGroup->SetName2("Content Manager Container Group");
}
// Add to content container: must keep a reference to each item's
// model node so it doesn't get deleted while the manager is alive.
m_pGroup->AddChild(pItem->m_pNode);
}
return pItem->m_pNode;
}
<|endoftext|> |
<commit_before>#include <handy/handy.h>
#include <sys/wait.h>
using namespace std;
using namespace handy;
struct Report {
long connected;
long retry;
long sended;
long recved;
Report() { memset(this, 0, sizeof(*this)); }
};
int main(int argc, const char* argv[]) {
if (argc < 9) {
printf("usage %s <host> <begin port> <end port> <conn count> <create seconds> <subprocesses> <hearbeat interval> <send size> <management port>\n", argv[0]);
return 1;
}
int c = 1;
string host = argv[c++];
int begin_port = atoi(argv[c++]);
int end_port = atoi(argv[c++]);
int conn_count = atoi(argv[c++]);
int create_seconds = atoi(argv[c++]);
int processes = atoi(argv[c++]);
conn_count = conn_count / processes;
int heartbeat_interval = atoi(argv[c++]);
int bsz = atoi(argv[c++]);
int man_port = atoi(argv[c++]);
int pid = 1;
for (int i = 0; i < processes; i ++) {
pid = fork();
if (pid == 0) { // a child process, break
sleep(1);
break;
}
}
Signal::signal(SIGPIPE, []{});
EventBase base;
if (pid == 0) { //child process
char *buf = new char[bsz];
ExitCaller ec1([=] {delete[] buf; });
Slice msg(buf, bsz);
char heartbeat[] = "heartbeat";
int send = 0;
int connected = 0;
int retry = 0;
int recved = 0;
vector<TcpConnPtr> allConns;
info("creating %d connections", conn_count);
for (int k = 0; k < create_seconds * 10; k ++) {
base.runAfter(100*k, [&]{
int c = conn_count / create_seconds / 10;
for (int i = 0; i < c; i++) {
short port = begin_port + (i % (end_port - begin_port));
auto con = TcpConn::createConnection(&base, host, port, 20*1000);
allConns.push_back(con);
con->setReconnectInterval(20*1000);
con->onMsg(new LengthCodec, [&](const TcpConnPtr& con, const Slice& msg) {
if (heartbeat_interval == 0) { // echo the msg if no interval
con->sendMsg(msg);
send++;
}
recved ++;
});
con->onState([&, i](const TcpConnPtr &con) {
TcpConn::State st = con->getState();
if (st == TcpConn::Connected) {
connected++;
// send ++;
// con->sendMsg(msg);
} else if (st == TcpConn::Failed || st == TcpConn::Closed) { //连接出错
if (st == TcpConn::Closed) { connected--; }
retry++;
}
});
}
});
}
if (heartbeat_interval) {
base.runAfter(heartbeat_interval * 1000, [&] {
for (int i = 0; i < heartbeat_interval; i ++) {
base.runAfter(i*1000, [&,i]{
size_t block = allConns.size() / heartbeat_interval;
for (size_t j=i*block; j<(i+1)*block && j<allConns.size(); j++) {
if (allConns[j]->getState() == TcpConn::Connected) {
allConns[j]->sendMsg(msg);
send++;
}
}
});
}
}, heartbeat_interval * 1000);
}
TcpConnPtr report = TcpConn::createConnection(&base, "127.0.0.1", man_port, 3000);
report->onMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) {
if (msg == "exit") {
info("recv exit msg from master, so exit");
base.exit();
}
});
report->onState([&](const TcpConnPtr& con) {
if (con->getState() == TcpConn::Closed) {
base.exit();
}
});
base.runAfter(2000, [&]() {
report->sendMsg(util::format("%d connected: %ld retry: %ld send: %ld recved: %ld",
getpid(), connected, retry, send, recved));
}, 100);
base.loop();
} else { // master process
map<int, Report> subs;
TcpServerPtr master = TcpServer::startServer(&base, "127.0.0.1", man_port);
master->onConnMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) {
auto fs = msg.split(' ');
if (fs.size() != 9) {
error("number of fields is %lu expected 7", fs.size());
return;
}
Report& c = subs[atoi(fs[0].data())];
c.connected = atoi(fs[2].data());
c.retry= atoi(fs[4].data());
c.sended = atoi(fs[6].data());
c.recved = atoi(fs[8].data());
});
base.runAfter(3000, [&](){
for(auto& s: subs) {
Report& r = s.second;
printf("pid: %6ld connected %6ld retry %6ld sended %6ld recved %6ld\n", (long)s.first, r.connected, r.retry, r.sended, r.recved);
}
printf("\n");
}, 3000);
Signal::signal(SIGCHLD, []{
int status = 0;
wait(&status);
error("wait result: status: %d is signaled: %d signal: %d", status, WIFSIGNALED(status), WTERMSIG(status));
});
base.loop();
}
info("program exited");
}
<commit_msg>heartbeat interval 100ms<commit_after>#include <handy/handy.h>
#include <sys/wait.h>
using namespace std;
using namespace handy;
struct Report {
long connected;
long retry;
long sended;
long recved;
Report() { memset(this, 0, sizeof(*this)); }
};
int main(int argc, const char* argv[]) {
if (argc < 9) {
printf("usage %s <host> <begin port> <end port> <conn count> <create seconds> <subprocesses> <hearbeat interval> <send size> <management port>\n", argv[0]);
return 1;
}
int c = 1;
string host = argv[c++];
int begin_port = atoi(argv[c++]);
int end_port = atoi(argv[c++]);
int conn_count = atoi(argv[c++]);
int create_seconds = atoi(argv[c++]);
int processes = atoi(argv[c++]);
conn_count = conn_count / processes;
int heartbeat_interval = atoi(argv[c++]);
int bsz = atoi(argv[c++]);
int man_port = atoi(argv[c++]);
int pid = 1;
for (int i = 0; i < processes; i ++) {
pid = fork();
if (pid == 0) { // a child process, break
sleep(1);
break;
}
}
Signal::signal(SIGPIPE, []{});
EventBase base;
if (pid == 0) { //child process
char *buf = new char[bsz];
ExitCaller ec1([=] {delete[] buf; });
Slice msg(buf, bsz);
char heartbeat[] = "heartbeat";
int send = 0;
int connected = 0;
int retry = 0;
int recved = 0;
vector<TcpConnPtr> allConns;
info("creating %d connections", conn_count);
for (int k = 0; k < create_seconds * 10; k ++) {
base.runAfter(100*k, [&]{
int c = conn_count / create_seconds / 10;
for (int i = 0; i < c; i++) {
short port = begin_port + (i % (end_port - begin_port));
auto con = TcpConn::createConnection(&base, host, port, 20*1000);
allConns.push_back(con);
con->setReconnectInterval(20*1000);
con->onMsg(new LengthCodec, [&](const TcpConnPtr& con, const Slice& msg) {
if (heartbeat_interval == 0) { // echo the msg if no interval
con->sendMsg(msg);
send++;
}
recved ++;
});
con->onState([&, i](const TcpConnPtr &con) {
TcpConn::State st = con->getState();
if (st == TcpConn::Connected) {
connected++;
// send ++;
// con->sendMsg(msg);
} else if (st == TcpConn::Failed || st == TcpConn::Closed) { //连接出错
if (st == TcpConn::Closed) { connected--; }
retry++;
}
});
}
});
}
if (heartbeat_interval) {
base.runAfter(heartbeat_interval * 1000, [&] {
for (int i = 0; i < heartbeat_interval*10; i ++) {
base.runAfter(i*100, [&,i]{
size_t block = allConns.size() / heartbeat_interval / 10;
for (size_t j=i*block; j<(i+1)*block && j<allConns.size(); j++) {
if (allConns[j]->getState() == TcpConn::Connected) {
allConns[j]->sendMsg(msg);
send++;
}
}
});
}
}, heartbeat_interval * 100);
}
TcpConnPtr report = TcpConn::createConnection(&base, "127.0.0.1", man_port, 3000);
report->onMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) {
if (msg == "exit") {
info("recv exit msg from master, so exit");
base.exit();
}
});
report->onState([&](const TcpConnPtr& con) {
if (con->getState() == TcpConn::Closed) {
base.exit();
}
});
base.runAfter(2000, [&]() {
report->sendMsg(util::format("%d connected: %ld retry: %ld send: %ld recved: %ld",
getpid(), connected, retry, send, recved));
}, 100);
base.loop();
} else { // master process
map<int, Report> subs;
TcpServerPtr master = TcpServer::startServer(&base, "127.0.0.1", man_port);
master->onConnMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) {
auto fs = msg.split(' ');
if (fs.size() != 9) {
error("number of fields is %lu expected 7", fs.size());
return;
}
Report& c = subs[atoi(fs[0].data())];
c.connected = atoi(fs[2].data());
c.retry= atoi(fs[4].data());
c.sended = atoi(fs[6].data());
c.recved = atoi(fs[8].data());
});
base.runAfter(3000, [&](){
for(auto& s: subs) {
Report& r = s.second;
printf("pid: %6ld connected %6ld retry %6ld sended %6ld recved %6ld\n", (long)s.first, r.connected, r.retry, r.sended, r.recved);
}
printf("\n");
}, 3000);
Signal::signal(SIGCHLD, []{
int status = 0;
wait(&status);
error("wait result: status: %d is signaled: %d signal: %d", status, WIFSIGNALED(status), WTERMSIG(status));
});
base.loop();
}
info("program exited");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MDriver.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2005-02-24 14:39:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_SDRIVER_HXX
#include "MDriver.hxx"
#endif
#ifndef CONNECTIVITY_SCONNECTION_HXX
#include "MConnection.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace connectivity::mozab;
namespace connectivity
{
namespace mozab
{
//------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
{
return *(new MozabDriver( _rxFactory ));
}
}
}
// --------------------------------------------------------------------------------
MozabDriver::MozabDriver(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
: ODriver_BASE(m_aMutex), m_xMSFactory( _rxFactory )
,s_hModule(NULL)
,s_pCreationFunc(NULL)
{
}
// -----------------------------------------------------------------------------
MozabDriver::~MozabDriver()
{
}
// --------------------------------------------------------------------------------
void MozabDriver::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
// when driver will be destroied so all our connections have to be destroied as well
for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_xConnections.clear();
connectivity::OWeakRefArray().swap(m_xConnections); // this really clears
ODriver_BASE::disposing();
if(s_hModule)
{
s_pCreationFunc = NULL;
osl_unloadModule(s_hModule);
s_hModule = NULL;
}
}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString MozabDriver::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii(MOZAB_DRIVER_IMPL_NAME);
// this name is referenced in the configuration and in the mozab.xml
// Please take care when changing it.
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > MozabDriver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
// which service is supported
// for more information @see com.sun.star.sdbc.Driver
Sequence< ::rtl::OUString > aSNS( 1 );
aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdbc.Driver"));
return aSNS;
}
//------------------------------------------------------------------
::rtl::OUString SAL_CALL MozabDriver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
//------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL MozabDriver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL MozabDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( ! acceptsURL(url) )
return NULL;
// create a new connection with the given properties and append it to our vector
registerClient();
Reference< XConnection > xCon;
if (s_pCreationFunc)
{
::osl::MutexGuard aGuard(m_aMutex);
//We must make sure we create an com.sun.star.mozilla.MozillaBootstrap brfore call any mozilla codes
Reference<XInterface> xInstance = m_xMSFactory->createInstance(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
OSL_ENSURE( xInstance.is(), "failed to create instance" );
OConnection* pCon = reinterpret_cast<OConnection*>((*s_pCreationFunc)(this));
xCon = pCon; // important here because otherwise the connection could be deleted inside (refcount goes -> 0)
pCon->construct(url,info); // late constructor call which can throw exception and allows a correct dtor call when so
m_xConnections.push_back(WeakReferenceHelper(*pCon));
}
else
{
::rtl::OUString sMsg = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Could not load the library "));
sMsg += ::rtl::OUString::createFromAscii(SAL_MODULENAME( "mozabdrv2" ));
::dbtools::throwGenericSQLException(sMsg,*this);
}
return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::acceptsURL( const ::rtl::OUString& url )
throw(SQLException, RuntimeException)
{
// here we have to look if we support this url format
return acceptsURL_Stat(url) != Unknown;
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL MozabDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( acceptsURL(url) )
{
::std::vector< DriverPropertyInfo > aDriverInfo;
if ( acceptsURL_Stat(url) == LDAP )
{
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BaseDN"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Base DN."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("MaxRowCount"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Records (max.)"))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("100"))
,Sequence< ::rtl::OUString >())
);
}
return Sequence< DriverPropertyInfo >(&(aDriverInfo[0]),aDriverInfo.size());
}
::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Invalid URL!")) ,*this);
// if you have somthing special to say return it here :-)
return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMajorVersion( ) throw(RuntimeException)
{
return 1; // depends on you
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMinorVersion( ) throw(RuntimeException)
{
return 0; // depends on you
}
// --------------------------------------------------------------------------------
EDriverType MozabDriver::acceptsURL_Stat( const ::rtl::OUString& url )
{
// Skip 'sdbc:mozab: part of URL
//
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aAddrbookURI(url.copy(nLen+1));
// Get Scheme
nLen = aAddrbookURI.indexOf(':');
::rtl::OUString aAddrbookScheme;
if ( nLen == -1 )
{
// There isn't any subschema: - but could be just subschema
if ( aAddrbookURI.getLength() > 0 )
aAddrbookScheme= aAddrbookURI;
else if(url == ::rtl::OUString::createFromAscii("sdbc:address:") )
return Unknown; // TODO check
else
return Unknown;
}
else
aAddrbookScheme = aAddrbookURI.copy(0, nLen);
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_MOZILLA() ) == 0 )
return Mozilla;
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_THUNDERBIRD() ) == 0 )
return ThunderBird;
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_LDAP() ) == 0 )
return LDAP;
#if defined(WNT) || defined(WIN)
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_OUTLOOK_MAPI() ) == 0 )
return Outlook;
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_OUTLOOK_EXPRESS() ) == 0 )
return OutlookExpress;
#endif
return Unknown;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_MOZILLA()
{
static sal_Char* SDBC_SCHEME_MOZILLA = MOZAB_MOZILLA_SCHEMA;
return SDBC_SCHEME_MOZILLA;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_THUNDERBIRD()
{
static sal_Char* SDBC_SCHEME_THUNDERBIRD = MOZAB_THUNDERBIRD_SCHEMA;
return SDBC_SCHEME_THUNDERBIRD;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_LDAP()
{
static sal_Char* SDBC_SCHEME_LDAP = MOZAB_LDAP_SCHEMA;
return SDBC_SCHEME_LDAP;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_OUTLOOK_MAPI()
{
static sal_Char* SDBC_SCHEME_OUTLOOK_MAPI = MOZAB_OUTLOOK_SCHEMA;
return SDBC_SCHEME_OUTLOOK_MAPI;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_OUTLOOK_EXPRESS()
{
static sal_Char* SDBC_SCHEME_OUTLOOK_EXPRESS = MOZAB_OUTLOOKEXP_SCHEMA;
return SDBC_SCHEME_OUTLOOK_EXPRESS;
}// -----------------------------------------------------------------------------
void MozabDriver::registerClient()
{
if (!s_hModule)
{
OSL_ENSURE(NULL == s_pCreationFunc, "MozabDriver::registerClient: inconsistence: already have a factory function!");
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(SAL_MODULENAME( "mozabdrv2" ));
// load the dbtools library
s_hModule = osl_loadModule(sModuleName.pData, 0);
OSL_ENSURE(NULL != s_hModule, "MozabDriver::registerClient: could not load the dbtools library!");
if (NULL != s_hModule)
{
// first, we need to announce our service factory to the lib
// see the documentation of setMozabServiceFactory for more details
const ::rtl::OUString sSetFactoryFuncName( RTL_CONSTASCII_USTRINGPARAM( "setMozabServiceFactory" ) );
// reinterpret_cast< OSetMozabServiceFactory >>> removed GNU C
OSetMozabServiceFactory pSetFactoryFunc =
( OSetMozabServiceFactory )( osl_getSymbol( s_hModule, sSetFactoryFuncName.pData ) );
OSL_ENSURE( pSetFactoryFunc, "MozabDriver::registerClient: missing an entry point!" );
if ( pSetFactoryFunc && m_xMSFactory.is() )
{
// for purpose of transfer safety, the interface needs to be acuired once
// (will be release by the callee)
m_xMSFactory->acquire();
( *pSetFactoryFunc )( m_xMSFactory.get() );
}
// get the symbol for the method creating the factory
const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("OMozabConnection_CreateInstance"));
// reinterpret_cast<OMozabConnection_CreateInstanceFunction> removed GNU C
s_pCreationFunc = (OMozabConnection_CreateInstanceFunction)(osl_getSymbol(s_hModule, sFactoryCreationFunc.pData));
if (NULL == s_pCreationFunc)
{ // did not find the symbol
OSL_ENSURE(sal_False, "MozabDriver::registerClient: could not find the symbol for creating the factory!");
osl_unloadModule(s_hModule);
s_hModule = NULL;
}
}
}
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba24 (1.10.52); FILE MERGED 2005/03/08 07:46:17 fs 1.10.52.2: RESYNC: (1.10-1.12); FILE MERGED 2005/02/04 08:43:36 oj 1.10.52.1: STLPort fix from thb<commit_after>/*************************************************************************
*
* $RCSfile: MDriver.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: vg $ $Date: 2005-03-10 15:30:32 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_SDRIVER_HXX
#include "MDriver.hxx"
#endif
#ifndef CONNECTIVITY_SCONNECTION_HXX
#include "MConnection.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace connectivity::mozab;
namespace connectivity
{
namespace mozab
{
//------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
{
return *(new MozabDriver( _rxFactory ));
}
}
}
// --------------------------------------------------------------------------------
MozabDriver::MozabDriver(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
: ODriver_BASE(m_aMutex), m_xMSFactory( _rxFactory )
,s_hModule(NULL)
,s_pCreationFunc(NULL)
{
}
// -----------------------------------------------------------------------------
MozabDriver::~MozabDriver()
{
}
// --------------------------------------------------------------------------------
void MozabDriver::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
// when driver will be destroied so all our connections have to be destroied as well
for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_xConnections.clear();
connectivity::OWeakRefArray().swap(m_xConnections); // this really clears
ODriver_BASE::disposing();
if(s_hModule)
{
s_pCreationFunc = NULL;
osl_unloadModule(s_hModule);
s_hModule = NULL;
}
}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString MozabDriver::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii(MOZAB_DRIVER_IMPL_NAME);
// this name is referenced in the configuration and in the mozab.xml
// Please take care when changing it.
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > MozabDriver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
// which service is supported
// for more information @see com.sun.star.sdbc.Driver
Sequence< ::rtl::OUString > aSNS( 1 );
aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdbc.Driver"));
return aSNS;
}
//------------------------------------------------------------------
::rtl::OUString SAL_CALL MozabDriver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
//------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL MozabDriver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL MozabDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( ! acceptsURL(url) )
return NULL;
// create a new connection with the given properties and append it to our vector
registerClient();
Reference< XConnection > xCon;
if (s_pCreationFunc)
{
::osl::MutexGuard aGuard(m_aMutex);
//We must make sure we create an com.sun.star.mozilla.MozillaBootstrap brfore call any mozilla codes
Reference<XInterface> xInstance = m_xMSFactory->createInstance(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
OSL_ENSURE( xInstance.is(), "failed to create instance" );
OConnection* pCon = reinterpret_cast<OConnection*>((*s_pCreationFunc)(this));
xCon = pCon; // important here because otherwise the connection could be deleted inside (refcount goes -> 0)
pCon->construct(url,info); // late constructor call which can throw exception and allows a correct dtor call when so
m_xConnections.push_back(WeakReferenceHelper(*pCon));
}
else
{
::rtl::OUString sMsg = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Could not load the library "));
sMsg += ::rtl::OUString::createFromAscii(SAL_MODULENAME( "mozabdrv2" ));
::dbtools::throwGenericSQLException(sMsg,*this);
}
return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL MozabDriver::acceptsURL( const ::rtl::OUString& url )
throw(SQLException, RuntimeException)
{
// here we have to look if we support this url format
return acceptsURL_Stat(url) != Unknown;
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL MozabDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( acceptsURL(url) )
{
::std::vector< DriverPropertyInfo > aDriverInfo;
if ( acceptsURL_Stat(url) == LDAP )
{
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BaseDN"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Base DN."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("MaxRowCount"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Records (max.)"))
,sal_False
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("100"))
,Sequence< ::rtl::OUString >())
);
}
return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size());
}
::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Invalid URL!")) ,*this);
// if you have somthing special to say return it here :-)
return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMajorVersion( ) throw(RuntimeException)
{
return 1; // depends on you
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL MozabDriver::getMinorVersion( ) throw(RuntimeException)
{
return 0; // depends on you
}
// --------------------------------------------------------------------------------
EDriverType MozabDriver::acceptsURL_Stat( const ::rtl::OUString& url )
{
// Skip 'sdbc:mozab: part of URL
//
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aAddrbookURI(url.copy(nLen+1));
// Get Scheme
nLen = aAddrbookURI.indexOf(':');
::rtl::OUString aAddrbookScheme;
if ( nLen == -1 )
{
// There isn't any subschema: - but could be just subschema
if ( aAddrbookURI.getLength() > 0 )
aAddrbookScheme= aAddrbookURI;
else if(url == ::rtl::OUString::createFromAscii("sdbc:address:") )
return Unknown; // TODO check
else
return Unknown;
}
else
aAddrbookScheme = aAddrbookURI.copy(0, nLen);
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_MOZILLA() ) == 0 )
return Mozilla;
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_THUNDERBIRD() ) == 0 )
return ThunderBird;
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_LDAP() ) == 0 )
return LDAP;
#if defined(WNT) || defined(WIN)
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_OUTLOOK_MAPI() ) == 0 )
return Outlook;
if ( aAddrbookScheme.compareToAscii( MozabDriver::getSDBC_SCHEME_OUTLOOK_EXPRESS() ) == 0 )
return OutlookExpress;
#endif
return Unknown;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_MOZILLA()
{
static sal_Char* SDBC_SCHEME_MOZILLA = MOZAB_MOZILLA_SCHEMA;
return SDBC_SCHEME_MOZILLA;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_THUNDERBIRD()
{
static sal_Char* SDBC_SCHEME_THUNDERBIRD = MOZAB_THUNDERBIRD_SCHEMA;
return SDBC_SCHEME_THUNDERBIRD;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_LDAP()
{
static sal_Char* SDBC_SCHEME_LDAP = MOZAB_LDAP_SCHEMA;
return SDBC_SCHEME_LDAP;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_OUTLOOK_MAPI()
{
static sal_Char* SDBC_SCHEME_OUTLOOK_MAPI = MOZAB_OUTLOOK_SCHEMA;
return SDBC_SCHEME_OUTLOOK_MAPI;
}
// -----------------------------------------------------------------------------
const sal_Char* MozabDriver::getSDBC_SCHEME_OUTLOOK_EXPRESS()
{
static sal_Char* SDBC_SCHEME_OUTLOOK_EXPRESS = MOZAB_OUTLOOKEXP_SCHEMA;
return SDBC_SCHEME_OUTLOOK_EXPRESS;
}// -----------------------------------------------------------------------------
void MozabDriver::registerClient()
{
if (!s_hModule)
{
OSL_ENSURE(NULL == s_pCreationFunc, "MozabDriver::registerClient: inconsistence: already have a factory function!");
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(SAL_MODULENAME( "mozabdrv2" ));
// load the dbtools library
s_hModule = osl_loadModule(sModuleName.pData, 0);
OSL_ENSURE(NULL != s_hModule, "MozabDriver::registerClient: could not load the dbtools library!");
if (NULL != s_hModule)
{
// first, we need to announce our service factory to the lib
// see the documentation of setMozabServiceFactory for more details
const ::rtl::OUString sSetFactoryFuncName( RTL_CONSTASCII_USTRINGPARAM( "setMozabServiceFactory" ) );
// reinterpret_cast< OSetMozabServiceFactory >>> removed GNU C
OSetMozabServiceFactory pSetFactoryFunc =
( OSetMozabServiceFactory )( osl_getSymbol( s_hModule, sSetFactoryFuncName.pData ) );
OSL_ENSURE( pSetFactoryFunc, "MozabDriver::registerClient: missing an entry point!" );
if ( pSetFactoryFunc && m_xMSFactory.is() )
{
// for purpose of transfer safety, the interface needs to be acuired once
// (will be release by the callee)
m_xMSFactory->acquire();
( *pSetFactoryFunc )( m_xMSFactory.get() );
}
// get the symbol for the method creating the factory
const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("OMozabConnection_CreateInstance"));
// reinterpret_cast<OMozabConnection_CreateInstanceFunction> removed GNU C
s_pCreationFunc = (OMozabConnection_CreateInstanceFunction)(osl_getSymbol(s_hModule, sFactoryCreationFunc.pData));
if (NULL == s_pCreationFunc)
{ // did not find the symbol
OSL_ENSURE(sal_False, "MozabDriver::registerClient: could not find the symbol for creating the factory!");
osl_unloadModule(s_hModule);
s_hModule = NULL;
}
}
}
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before><commit_msg>connectivity: fix the mozab build<commit_after><|endoftext|> |
<commit_before>#ifndef MIMOSA_REF_COUNTABLE_HH
# define MIMOSA_REF_COUNTABLE_HH
# include <cassert>
# include "ref-counted-ptr.hh"
namespace mimosa
{
class RefCountableBase
{
public:
inline RefCountableBase()
: ref_count_(0)
{
}
inline RefCountableBase(const RefCountableBase & /*other*/)
: ref_count_(0)
{
}
virtual ~RefCountableBase() {}
inline RefCountableBase & operator=(const RefCountableBase & /*other*/)
{
return *this;
}
inline int addRef() const
{
auto ret = __sync_add_and_fetch(&ref_count_, 1);
assert(ret >= 1);
return ret;
}
inline int releaseRef() const
{
auto ret = __sync_add_and_fetch(&ref_count_, -1);
assert(ret >= 0);
return ret;
}
mutable int ref_count_;
};
inline void addRef(const RefCountableBase * obj)
{
obj->addRef();
}
inline void releaseRef(const RefCountableBase * obj)
{
if (obj->releaseRef() == 0)
delete obj;
}
# define MIMOSA_DEF_PTR(T) \
typedef RefCountedPtr<T> Ptr; \
typedef RefCountedPtr<const T> ConstPtr;
template <typename T>
class RefCountable : public RefCountableBase
{
public:
MIMOSA_DEF_PTR(T);
};
}
#endif /* !MIMOSA_REF_COUNTABLE_HH */
<commit_msg>Fixed MIMOSA_DEF_PTR to support A<b, c><commit_after>#ifndef MIMOSA_REF_COUNTABLE_HH
# define MIMOSA_REF_COUNTABLE_HH
# include <cassert>
# include "ref-counted-ptr.hh"
namespace mimosa
{
class RefCountableBase
{
public:
inline RefCountableBase()
: ref_count_(0)
{
}
inline RefCountableBase(const RefCountableBase & /*other*/)
: ref_count_(0)
{
}
virtual ~RefCountableBase() {}
inline RefCountableBase & operator=(const RefCountableBase & /*other*/)
{
return *this;
}
inline int addRef() const
{
auto ret = __sync_add_and_fetch(&ref_count_, 1);
assert(ret >= 1);
return ret;
}
inline int releaseRef() const
{
auto ret = __sync_add_and_fetch(&ref_count_, -1);
assert(ret >= 0);
return ret;
}
mutable int ref_count_;
};
inline void addRef(const RefCountableBase * obj)
{
obj->addRef();
}
inline void releaseRef(const RefCountableBase * obj)
{
if (obj->releaseRef() == 0)
delete obj;
}
# define MIMOSA_DEF_PTR(T...) \
typedef RefCountedPtr<T > Ptr; \
typedef RefCountedPtr<const T > ConstPtr;
template <typename T >
class RefCountable : public RefCountableBase
{
public:
MIMOSA_DEF_PTR(T);
};
}
#endif /* !MIMOSA_REF_COUNTABLE_HH */
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* CIDImpl.cpp
* The actual implementation of a CID. The implementation changes based on
* which uuid library is installed.
* Copyright (C) 2007 Simon Newton
*/
#include "plugins/e131/e131/E131Includes.h" // NOLINT, this has to be first
#include <string.h>
#include <string>
#include "plugins/e131/e131/CIDImpl.h"
namespace ola {
namespace acn {
#ifdef USE_OSSP_UUID
CIDImpl::CIDImpl()
: m_uuid(NULL) {
}
CIDImpl::CIDImpl(uuid_t *uuid)
: m_uuid(uuid) {
}
CIDImpl::CIDImpl(const CIDImpl& other)
: m_uuid(NULL) {
if (other.m_uuid)
uuid_clone(other.m_uuid, &m_uuid);
}
CIDImpl::~CIDImpl() {
if (m_uuid)
uuid_destroy(m_uuid);
}
bool CIDImpl::IsNil() const {
if (!m_uuid)
return true;
int result;
uuid_isnil(m_uuid, &result);
return result;
}
/**
* Pack a CIDImpl into the binary representation
*/
void CIDImpl::Pack(uint8_t *buffer) const {
size_t data_length = CIDImpl_LENGTH;
// buffer may not be 4 byte aligned
char uid_data[CIDImpl_LENGTH];
void *ptr = static_cast<void*>(uid_data);
if (m_uuid) {
uuid_export(m_uuid, UUID_FMT_BIN, &ptr, &data_length);
memcpy(buffer, uid_data, CIDImpl_LENGTH);
} else {
memset(buffer, 0, CIDImpl_LENGTH);
}
}
CIDImpl& CIDImpl::operator=(const CIDImpl& other) {
if (this != &other) {
if (m_uuid)
uuid_destroy(m_uuid);
if (other.m_uuid)
uuid_clone(other.m_uuid, &m_uuid);
else
m_uuid = NULL;
}
return *this;
}
bool CIDImpl::operator==(const CIDImpl& c1) const {
int result;
uuid_compare(m_uuid, c1.m_uuid, &result);
return 0 == result;
}
bool CIDImpl::operator!=(const CIDImpl& c1) const {
return !(*this == c1);
}
std::string CIDImpl::ToString() const {
char cid[UUID_LEN_STR + 1];
void *str = static_cast<void*>(cid);
size_t length = UUID_LEN_STR + 1;
uuid_export(m_uuid, UUID_FMT_STR, &str, &length);
return std::string(cid);
}
void CIDImpl::Write(ola::io::OutputBufferInterface *output) const {
size_t data_length = CIDImpl_LENGTH;
// buffer may not be 4 byte aligned
uint8_t uid_data[CIDImpl_LENGTH];
void *ptr = static_cast<void*>(uid_data);
if (m_uuid) {
uuid_export(m_uuid, UUID_FMT_BIN, &ptr, &data_length);
} else {
memset(ptr, 0, CIDImpl_LENGTH);
}
output->Write(uid_data, CIDImpl_LENGTH);
}
CIDImpl* CIDImpl::Generate() {
uuid_t *uuid;
uuid_create(&uuid);
uuid_make(uuid, UUID_MAKE_V4);
return CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromData(const uint8_t *data) {
uuid_t *uuid;
uuid_create(&uuid);
uuid_import(uuid, UUID_FMT_BIN, data, CIDImpl_LENGTH);
return CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromString(const std::string &cid) {
uuid_t *uuid;
uuid_create(&uuid);
uuid_import(uuid, UUID_FMT_STR, cid.data(), cid.length());
return CIDImpl(uuid);
}
#else
// We're using the e2fs utils uuid library
CIDImpl::CIDImpl() {
uuid_clear(m_uuid);
}
CIDImpl::CIDImpl(uuid_t uuid) {
uuid_copy(m_uuid, uuid);
}
CIDImpl::CIDImpl(const CIDImpl& other) {
uuid_copy(m_uuid, other.m_uuid);
}
CIDImpl::~CIDImpl() {
}
bool CIDImpl::IsNil() const {
return uuid_is_null(m_uuid);
}
void CIDImpl::Pack(uint8_t *buf) const {
memcpy(buf, m_uuid, CIDImpl_LENGTH);
}
void CIDImpl::Write(ola::io::OutputBufferInterface *output) const {
output->Write(m_uuid, CIDImpl_LENGTH);
}
CIDImpl& CIDImpl::operator=(const CIDImpl& other) {
if (this != &other) {
uuid_copy(m_uuid, other.m_uuid);
}
return *this;
}
bool CIDImpl::operator==(const CIDImpl& c1) const {
return !uuid_compare(m_uuid, c1.m_uuid);
}
bool CIDImpl::operator!=(const CIDImpl& c1) const {
return uuid_compare(m_uuid, c1.m_uuid);
}
std::string CIDImpl::ToString() const {
char str[37];
uuid_unparse(m_uuid, str);
return std::string(str);
}
CIDImpl* CIDImpl::Generate() {
uuid_t uuid;
uuid_generate(uuid);
return new CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromData(const uint8_t *data) {
uuid_t uuid;
uuid_copy(uuid, data);
return new CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromString(const std::string &cid) {
uuid_t uuid;
int ret = uuid_parse(cid.data(), uuid);
if (ret == -1)
uuid_clear(uuid);
return new CIDImpl(uuid);
}
#endif // end the e2fs progs uuid implementation
} // acn
} // ola
<commit_msg>*Fix the CIDImpl again<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* CIDImpl.cpp
* The actual implementation of a CID. The implementation changes based on
* which uuid library is installed.
* Copyright (C) 2007 Simon Newton
*/
#include "plugins/e131/e131/E131Includes.h" // NOLINT, this has to be first
#include <string.h>
#include <string>
#include "plugins/e131/e131/CIDImpl.h"
namespace ola {
namespace acn {
#ifdef USE_OSSP_UUID
CIDImpl::CIDImpl()
: m_uuid(NULL) {
}
CIDImpl::CIDImpl(uuid_t *uuid)
: m_uuid(uuid) {
}
CIDImpl::CIDImpl(const CIDImpl& other)
: m_uuid(NULL) {
if (other.m_uuid)
uuid_clone(other.m_uuid, &m_uuid);
}
CIDImpl::~CIDImpl() {
if (m_uuid)
uuid_destroy(m_uuid);
}
bool CIDImpl::IsNil() const {
if (!m_uuid)
return true;
int result;
uuid_isnil(m_uuid, &result);
return result;
}
/**
* Pack a CIDImpl into the binary representation
*/
void CIDImpl::Pack(uint8_t *buffer) const {
size_t data_length = CIDImpl_LENGTH;
// buffer may not be 4 byte aligned
char uid_data[CIDImpl_LENGTH];
void *ptr = static_cast<void*>(uid_data);
if (m_uuid) {
uuid_export(m_uuid, UUID_FMT_BIN, &ptr, &data_length);
memcpy(buffer, uid_data, CIDImpl_LENGTH);
} else {
memset(buffer, 0, CIDImpl_LENGTH);
}
}
CIDImpl& CIDImpl::operator=(const CIDImpl& other) {
if (this != &other) {
if (m_uuid)
uuid_destroy(m_uuid);
if (other.m_uuid)
uuid_clone(other.m_uuid, &m_uuid);
else
m_uuid = NULL;
}
return *this;
}
bool CIDImpl::operator==(const CIDImpl& c1) const {
int result;
uuid_compare(m_uuid, c1.m_uuid, &result);
return 0 == result;
}
bool CIDImpl::operator!=(const CIDImpl& c1) const {
return !(*this == c1);
}
std::string CIDImpl::ToString() const {
char cid[UUID_LEN_STR + 1];
void *str = static_cast<void*>(cid);
size_t length = UUID_LEN_STR + 1;
uuid_export(m_uuid, UUID_FMT_STR, &str, &length);
return std::string(cid);
}
void CIDImpl::Write(ola::io::OutputBufferInterface *output) const {
size_t data_length = CIDImpl_LENGTH;
// buffer may not be 4 byte aligned
uint8_t uid_data[CIDImpl_LENGTH];
void *ptr = static_cast<void*>(uid_data);
if (m_uuid) {
uuid_export(m_uuid, UUID_FMT_BIN, &ptr, &data_length);
} else {
memset(ptr, 0, CIDImpl_LENGTH);
}
output->Write(uid_data, CIDImpl_LENGTH);
}
CIDImpl* CIDImpl::Generate() {
uuid_t *uuid;
uuid_create(&uuid);
uuid_make(uuid, UUID_MAKE_V4);
return new CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromData(const uint8_t *data) {
uuid_t *uuid;
uuid_create(&uuid);
uuid_import(uuid, UUID_FMT_BIN, data, CIDImpl_LENGTH);
return new CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromString(const std::string &cid) {
uuid_t *uuid;
uuid_create(&uuid);
uuid_import(uuid, UUID_FMT_STR, cid.data(), cid.length());
return new CIDImpl(uuid);
}
#else
// We're using the e2fs utils uuid library
CIDImpl::CIDImpl() {
uuid_clear(m_uuid);
}
CIDImpl::CIDImpl(uuid_t uuid) {
uuid_copy(m_uuid, uuid);
}
CIDImpl::CIDImpl(const CIDImpl& other) {
uuid_copy(m_uuid, other.m_uuid);
}
CIDImpl::~CIDImpl() {
}
bool CIDImpl::IsNil() const {
return uuid_is_null(m_uuid);
}
void CIDImpl::Pack(uint8_t *buf) const {
memcpy(buf, m_uuid, CIDImpl_LENGTH);
}
void CIDImpl::Write(ola::io::OutputBufferInterface *output) const {
output->Write(m_uuid, CIDImpl_LENGTH);
}
CIDImpl& CIDImpl::operator=(const CIDImpl& other) {
if (this != &other) {
uuid_copy(m_uuid, other.m_uuid);
}
return *this;
}
bool CIDImpl::operator==(const CIDImpl& c1) const {
return !uuid_compare(m_uuid, c1.m_uuid);
}
bool CIDImpl::operator!=(const CIDImpl& c1) const {
return uuid_compare(m_uuid, c1.m_uuid);
}
std::string CIDImpl::ToString() const {
char str[37];
uuid_unparse(m_uuid, str);
return std::string(str);
}
CIDImpl* CIDImpl::Generate() {
uuid_t uuid;
uuid_generate(uuid);
return new CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromData(const uint8_t *data) {
uuid_t uuid;
uuid_copy(uuid, data);
return new CIDImpl(uuid);
}
CIDImpl* CIDImpl::FromString(const std::string &cid) {
uuid_t uuid;
int ret = uuid_parse(cid.data(), uuid);
if (ret == -1)
uuid_clear(uuid);
return new CIDImpl(uuid);
}
#endif // end the e2fs progs uuid implementation
} // acn
} // ola
<|endoftext|> |
<commit_before>///
/// @file SieveOfEratosthenes.cpp
/// @brief Implementation of the segmented sieve of Eratosthenes.
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the New BSD License. See the
/// LICENSE file in the top level directory.
///
#include "config.h"
#include "SieveOfEratosthenes.h"
#include "PreSieve.h"
#include "EratSmall.h"
#include "EratMedium.h"
#include "EratBig.h"
#include "imath.h"
#include "primesieve_error.h"
#include <stdint.h>
#include <exception>
#include <string>
#include <cstdlib>
namespace soe {
const uint_t SieveOfEratosthenes::bitValues_[8] = { 7, 11, 13, 17, 19, 23, 29, 31 };
/// De Bruijn bitscan table
const uint_t SieveOfEratosthenes::bruijnBitValues_[64] =
{
7, 47, 11, 49, 67, 113, 13, 53,
89, 71, 161, 101, 119, 187, 17, 233,
59, 79, 91, 73, 133, 139, 163, 103,
149, 121, 203, 169, 191, 217, 19, 239,
43, 61, 109, 83, 157, 97, 181, 229,
77, 131, 137, 143, 199, 167, 211, 41,
107, 151, 179, 227, 127, 197, 209, 37,
173, 223, 193, 31, 221, 29, 23, 241
};
/// @param start Sieve primes >= start.
/// @param stop Sieve primes <= stop.
/// @param sieveSize A sieve size in kilobytes.
/// @param preSieve Pre-sieve multiples of small primes <= preSieve
/// to speed up the sieve of Eratosthenes.
/// @pre start >= 7
/// @pre stop <= 2^64 - 2^32 * 10
/// @pre sieveSize >= 1 && <= 4096
/// @pre preSieve >= 13 && <= 23
///
SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start,
uint64_t stop,
uint_t sieveSize,
uint_t preSieve) :
start_(start),
stop_(stop),
limitPreSieve_(preSieve),
sieve_(NULL),
preSieve_(NULL),
eratSmall_(NULL),
eratMedium_(NULL),
eratBig_(NULL)
{
if (start_ < 7)
throw primesieve_error("SieveOfEratosthenes: start must be >= 7");
if (start_ > stop_)
throw primesieve_error("SieveOfEratosthenes: start must be <= stop");
sqrtStop_ = static_cast<uint_t>(isqrt(stop_));
// sieveSize_ must be a power of 2
sieveSize_ = getInBetween(1u, floorPowerOf2(sieveSize), 4096u);
sieveSize_ *= 1024; // convert to bytes
segmentLow_ = start_ - getByteRemainder(start_);
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
// allocate the sieve of Eratosthenes array
sieve_ = new byte_t[sieveSize_];
init();
}
SieveOfEratosthenes::~SieveOfEratosthenes()
{
cleanUp();
}
void SieveOfEratosthenes::cleanUp()
{
delete[] sieve_;
delete preSieve_;
delete eratSmall_;
delete eratMedium_;
delete eratBig_;
}
void SieveOfEratosthenes::init()
{
limitEratSmall_ = static_cast<uint_t>(sieveSize_ * config::FACTOR_ERATSMALL);
limitEratMedium_ = static_cast<uint_t>(sieveSize_ * config::FACTOR_ERATMEDIUM);
try {
preSieve_ = new PreSieve(limitPreSieve_);
if (sqrtStop_ > limitPreSieve_) eratSmall_ = new EratSmall (stop_, sieveSize_, limitEratSmall_);
if (sqrtStop_ > limitEratSmall_) eratMedium_ = new EratMedium(stop_, sieveSize_, limitEratMedium_);
if (sqrtStop_ > limitEratMedium_) eratBig_ = new EratBig (stop_, sieveSize_, sqrtStop_);
}
catch (const std::exception& e) {
cleanUp();
throw e;
}
}
uint_t SieveOfEratosthenes::getSqrtStop() const
{
return sqrtStop_;
}
uint_t SieveOfEratosthenes::getPreSieve() const
{
return limitPreSieve_;
}
std::string SieveOfEratosthenes::getMaxStopString()
{
return EratBig::getMaxStopString();
}
uint64_t SieveOfEratosthenes::getMaxStop()
{
return EratBig::getMaxStop();
}
uint64_t SieveOfEratosthenes::getByteRemainder(uint64_t n)
{
uint64_t r = n % NUMBERS_PER_BYTE;
if (r <= 1)
r += NUMBERS_PER_BYTE;
return r;
}
void SieveOfEratosthenes::sieveSegment()
{
preSieve();
crossOffMultiples();
segmentProcessed(sieve_, sieveSize_);
}
void SieveOfEratosthenes::crossOffMultiples()
{
if (eratSmall_) eratSmall_->crossOff(sieve_, &sieve_[sieveSize_]);
if (eratMedium_) eratMedium_->crossOff(sieve_, sieveSize_);
if (eratBig_) eratBig_->crossOff(sieve_);
}
/// Pre-sieve multiples of small primes e.g. <= 19
/// to speed up the sieve of Eratosthenes.
///
void SieveOfEratosthenes::preSieve()
{
preSieve_->doIt(sieve_, sieveSize_, segmentLow_);
// unset bits (numbers) < start_
if (segmentLow_ <= start_) {
if (start_ <= limitPreSieve_)
sieve_[0] = 0xff;
for (int i = 0; bitValues_[i] < getByteRemainder(start_); i++)
sieve_[0] &= 0xfe << i;
}
}
/// Sieve the last segments remaining after that sieve(uint_t)
/// has been called for all primes up to sqrt(stop).
///
void SieveOfEratosthenes::finish()
{
// sieve all segments left except the last one
while (segmentHigh_ < stop_) {
sieveSegment();
segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE;
segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE;
}
// sieve the last segment
uint64_t remainder = getByteRemainder(stop_);
sieveSize_ = static_cast<uint_t>((stop_ - remainder) - segmentLow_) / NUMBERS_PER_BYTE + 1;
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
preSieve();
crossOffMultiples();
int i;
// unset bits (numbers) > stop_
for (i = 0; i < 8; i++)
if (bitValues_[i] > remainder)
break;
int unsetBits = ~(0xff << i);
sieve_[sieveSize_ - 1] &= unsetBits;
for (uint_t j = sieveSize_; j % 8 != 0; j++)
sieve_[j] = 0;
segmentProcessed(sieve_, sieveSize_);
}
} // namespace soe
<commit_msg>silenced cppcheck warning<commit_after>///
/// @file SieveOfEratosthenes.cpp
/// @brief Implementation of the segmented sieve of Eratosthenes.
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the New BSD License. See the
/// LICENSE file in the top level directory.
///
#include "config.h"
#include "SieveOfEratosthenes.h"
#include "PreSieve.h"
#include "EratSmall.h"
#include "EratMedium.h"
#include "EratBig.h"
#include "imath.h"
#include "primesieve_error.h"
#include <stdint.h>
#include <exception>
#include <string>
#include <cstdlib>
namespace soe {
const uint_t SieveOfEratosthenes::bitValues_[8] = { 7, 11, 13, 17, 19, 23, 29, 31 };
/// De Bruijn bitscan table
const uint_t SieveOfEratosthenes::bruijnBitValues_[64] =
{
7, 47, 11, 49, 67, 113, 13, 53,
89, 71, 161, 101, 119, 187, 17, 233,
59, 79, 91, 73, 133, 139, 163, 103,
149, 121, 203, 169, 191, 217, 19, 239,
43, 61, 109, 83, 157, 97, 181, 229,
77, 131, 137, 143, 199, 167, 211, 41,
107, 151, 179, 227, 127, 197, 209, 37,
173, 223, 193, 31, 221, 29, 23, 241
};
/// @param start Sieve primes >= start.
/// @param stop Sieve primes <= stop.
/// @param sieveSize A sieve size in kilobytes.
/// @param preSieve Pre-sieve multiples of small primes <= preSieve
/// to speed up the sieve of Eratosthenes.
/// @pre start >= 7
/// @pre stop <= 2^64 - 2^32 * 10
/// @pre sieveSize >= 1 && <= 4096
/// @pre preSieve >= 13 && <= 23
///
SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start,
uint64_t stop,
uint_t sieveSize,
uint_t preSieve) :
start_(start),
stop_(stop),
limitPreSieve_(preSieve),
sieve_(NULL),
preSieve_(NULL),
eratSmall_(NULL),
eratMedium_(NULL),
eratBig_(NULL)
{
if (start_ < 7)
throw primesieve_error("SieveOfEratosthenes: start must be >= 7");
if (start_ > stop_)
throw primesieve_error("SieveOfEratosthenes: start must be <= stop");
sqrtStop_ = static_cast<uint_t>(isqrt(stop_));
// sieveSize_ must be a power of 2
sieveSize_ = getInBetween(1u, floorPowerOf2(sieveSize), 4096u);
sieveSize_ *= 1024; // convert to bytes
segmentLow_ = start_ - getByteRemainder(start_);
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
// allocate the sieve of Eratosthenes array
sieve_ = new byte_t[sieveSize_];
init();
}
SieveOfEratosthenes::~SieveOfEratosthenes()
{
cleanUp();
}
void SieveOfEratosthenes::cleanUp()
{
delete[] sieve_;
delete preSieve_;
delete eratSmall_;
delete eratMedium_;
delete eratBig_;
}
void SieveOfEratosthenes::init()
{
limitEratSmall_ = static_cast<uint_t>(sieveSize_ * config::FACTOR_ERATSMALL);
limitEratMedium_ = static_cast<uint_t>(sieveSize_ * config::FACTOR_ERATMEDIUM);
try {
preSieve_ = new PreSieve(limitPreSieve_);
if (sqrtStop_ > limitPreSieve_) eratSmall_ = new EratSmall (stop_, sieveSize_, limitEratSmall_);
if (sqrtStop_ > limitEratSmall_) eratMedium_ = new EratMedium(stop_, sieveSize_, limitEratMedium_);
if (sqrtStop_ > limitEratMedium_) eratBig_ = new EratBig (stop_, sieveSize_, sqrtStop_);
}
catch (const std::exception&) {
cleanUp();
throw;
}
}
uint_t SieveOfEratosthenes::getSqrtStop() const
{
return sqrtStop_;
}
uint_t SieveOfEratosthenes::getPreSieve() const
{
return limitPreSieve_;
}
std::string SieveOfEratosthenes::getMaxStopString()
{
return EratBig::getMaxStopString();
}
uint64_t SieveOfEratosthenes::getMaxStop()
{
return EratBig::getMaxStop();
}
uint64_t SieveOfEratosthenes::getByteRemainder(uint64_t n)
{
uint64_t r = n % NUMBERS_PER_BYTE;
if (r <= 1)
r += NUMBERS_PER_BYTE;
return r;
}
void SieveOfEratosthenes::sieveSegment()
{
preSieve();
crossOffMultiples();
segmentProcessed(sieve_, sieveSize_);
}
void SieveOfEratosthenes::crossOffMultiples()
{
if (eratSmall_) eratSmall_->crossOff(sieve_, &sieve_[sieveSize_]);
if (eratMedium_) eratMedium_->crossOff(sieve_, sieveSize_);
if (eratBig_) eratBig_->crossOff(sieve_);
}
/// Pre-sieve multiples of small primes e.g. <= 19
/// to speed up the sieve of Eratosthenes.
///
void SieveOfEratosthenes::preSieve()
{
preSieve_->doIt(sieve_, sieveSize_, segmentLow_);
// unset bits (numbers) < start_
if (segmentLow_ <= start_) {
if (start_ <= limitPreSieve_)
sieve_[0] = 0xff;
for (int i = 0; bitValues_[i] < getByteRemainder(start_); i++)
sieve_[0] &= 0xfe << i;
}
}
/// Sieve the last segments remaining after that sieve(uint_t)
/// has been called for all primes up to sqrt(stop).
///
void SieveOfEratosthenes::finish()
{
// sieve all segments left except the last one
while (segmentHigh_ < stop_) {
sieveSegment();
segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE;
segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE;
}
// sieve the last segment
uint64_t remainder = getByteRemainder(stop_);
sieveSize_ = static_cast<uint_t>((stop_ - remainder) - segmentLow_) / NUMBERS_PER_BYTE + 1;
segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1;
preSieve();
crossOffMultiples();
int i;
// unset bits (numbers) > stop_
for (i = 0; i < 8; i++)
if (bitValues_[i] > remainder)
break;
int unsetBits = ~(0xff << i);
sieve_[sieveSize_ - 1] &= unsetBits;
for (uint_t j = sieveSize_; j % 8 != 0; j++)
sieve_[j] = 0;
segmentProcessed(sieve_, sieveSize_);
}
} // namespace soe
<|endoftext|> |
<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RenderTargetOGL.h"
#include "TextureOGL.h"
#include "Engine.h"
#include "RendererOGL.h"
namespace ouzel
{
namespace graphics
{
RenderTargetOGL::RenderTargetOGL()
{
}
RenderTargetOGL::~RenderTargetOGL()
{
destroy();
}
void RenderTargetOGL::destroy()
{
if (depthBufferId)
{
glDeleteRenderbuffers(1, &depthBufferId);
depthBufferId = 0;
}
if (frameBufferId)
{
glDeleteFramebuffers(1, &frameBufferId);
frameBufferId = 0;
}
}
bool RenderTargetOGL::init(const Size2& newSize, bool depthBuffer)
{
if (!RenderTarget::init(newSize, depthBuffer))
{
return false;
}
destroy();
viewport = Rectangle(0.0f, 0.0f, newSize.width, newSize.height);
GLuint oldFrameBufferId;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&oldFrameBufferId));
glGenFramebuffers(1, &frameBufferId);
RendererOGL::bindFrameBuffer(frameBufferId);
std::shared_ptr<TextureOGL> textureOGL(new TextureOGL());
if (!textureOGL->init(size, false, false, true))
{
return false;
}
textureOGL->setFlipped(true);
texture = textureOGL;
RendererOGL::bindTexture(textureOGL->getTextureId(), 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
static_cast<GLsizei>(size.width),
static_cast<GLsizei>(size.height),
0, GL_RGB, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
if (depthBuffer)
{
glGenRenderbuffers(1, &depthBufferId);
glBindRenderbuffer(GL_RENDERBUFFER, depthBufferId);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,
static_cast<GLsizei>(size.width),
static_cast<GLsizei>(size.height));
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBufferId);
}
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureOGL->getTextureId(), 0);
#ifdef OUZEL_SUPPORTS_OPENGL // TODO: fix this
//GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
//glDrawBuffers(1, drawBuffers);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
#endif
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
return false;
}
return true;
}
} // namespace graphics
} // namespace ouzel
<commit_msg>Fix OpenGL render textuer pixel format<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RenderTargetOGL.h"
#include "TextureOGL.h"
#include "Engine.h"
#include "RendererOGL.h"
namespace ouzel
{
namespace graphics
{
RenderTargetOGL::RenderTargetOGL()
{
}
RenderTargetOGL::~RenderTargetOGL()
{
destroy();
}
void RenderTargetOGL::destroy()
{
if (depthBufferId)
{
glDeleteRenderbuffers(1, &depthBufferId);
depthBufferId = 0;
}
if (frameBufferId)
{
glDeleteFramebuffers(1, &frameBufferId);
frameBufferId = 0;
}
}
bool RenderTargetOGL::init(const Size2& newSize, bool depthBuffer)
{
if (!RenderTarget::init(newSize, depthBuffer))
{
return false;
}
destroy();
viewport = Rectangle(0.0f, 0.0f, newSize.width, newSize.height);
GLuint oldFrameBufferId;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&oldFrameBufferId));
glGenFramebuffers(1, &frameBufferId);
RendererOGL::bindFrameBuffer(frameBufferId);
std::shared_ptr<TextureOGL> textureOGL(new TextureOGL());
if (!textureOGL->init(size, false, false, true))
{
return false;
}
textureOGL->setFlipped(true);
texture = textureOGL;
RendererOGL::bindTexture(textureOGL->getTextureId(), 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
static_cast<GLsizei>(size.width),
static_cast<GLsizei>(size.height),
0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
if (depthBuffer)
{
glGenRenderbuffers(1, &depthBufferId);
glBindRenderbuffer(GL_RENDERBUFFER, depthBufferId);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,
static_cast<GLsizei>(size.width),
static_cast<GLsizei>(size.height));
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBufferId);
}
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureOGL->getTextureId(), 0);
#ifdef OUZEL_SUPPORTS_OPENGL // TODO: fix this
//GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
//glDrawBuffers(1, drawBuffers);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
#endif
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
return false;
}
return true;
}
} // namespace graphics
} // namespace ouzel
<|endoftext|> |
<commit_before>/**
* This software is released under the terms of the MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @copyright 2009-2012 Roberto Perpuly
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
#include <pelet/LexicalAnalyzerClass.h>
#include <pelet/Php53LexicalAnalyzer.h>
#include <pelet/Php54LexicalAnalyzer.h>
#include <unicode/uchar.h>
#include <unicode/ustring.h>
#include <unicode/ucnv.h>
pelet::LexicalAnalyzerClass::LexicalAnalyzerClass(const std::string& fileName)
: ParserError()
, Buffer(NULL)
, FileName()
, Condition(yycINLINE_HTML)
, Version(PHP_53) {
OpenFile(fileName);
}
pelet::LexicalAnalyzerClass::LexicalAnalyzerClass()
: ParserError()
, Buffer(NULL)
, FileName()
, Condition(yycINLINE_HTML)
, Version(PHP_53) {
}
pelet::LexicalAnalyzerClass::~LexicalAnalyzerClass() {
Close();
}
void pelet::LexicalAnalyzerClass::Close() {
if (Buffer) {
Buffer->Close();
delete Buffer;
Buffer = NULL;
}
}
bool pelet::LexicalAnalyzerClass::OpenFile(const std::string& newFile) {
Close();
UCharBufferedFileClass* bufferFile = new UCharBufferedFileClass();
Buffer = bufferFile;
FileName = newFile;
Condition = yycINLINE_HTML;
return bufferFile->OpenFile(newFile.c_str());
}
bool pelet::LexicalAnalyzerClass::OpenFile(FILE* file) {
Close();
UCharBufferedFileClass* bufferFile = new UCharBufferedFileClass();
Buffer = bufferFile;
FileName = "";
Condition = yycINLINE_HTML;
return bufferFile->OpenFile(file);
}
bool pelet::LexicalAnalyzerClass::OpenString(const UnicodeString& code) {
Close();
FileName = "";
Condition = yycSCRIPT;
pelet::UCharBufferClass* memBuffer = new UCharBufferClass();
Buffer = memBuffer;
return memBuffer->OpenString(code);
}
void pelet::LexicalAnalyzerClass::SetVersion(Versions version) {
Version = version;
}
int pelet::LexicalAnalyzerClass::NextToken() {
if (PHP_53 == Version) {
return Buffer ? pelet::Next53Token(Buffer, Condition) : T_END;
}
else {
return Buffer ? pelet::Next54Token(Buffer, Condition) : T_END;
}
}
bool pelet::LexicalAnalyzerClass::GetLexeme(UnicodeString& lexeme) {
if (!Buffer) {
return false;
}
lexeme.remove();
const UChar *start = Buffer->TokenStart;
const UChar *end = Buffer->Current;
bool ret = false;
bool isSingleQuoteString = false;
bool isDoubleQuoteString = false;
bool isHeredoc = false;
bool isNowdoc = false;
// be careful, take Limit into account too... we dont want to read past what is allowed
if ((end - start) > 0 && Buffer->Current <= Buffer->Limit) {
// the lexer may ask for too much when the last token is an identifier
// in this case current will point to past the null character
if (Buffer->Current > Buffer->Limit) {
end = Buffer->Limit;
}
if (start[0] == '\'') {
isSingleQuoteString = true;
start++;
end--;
}
if (start[0] == '"') {
isDoubleQuoteString = true;
start++;
end--;
}
int len = (end - start);
int added = 0;
for (int i = 0; i < len; i++) {
UChar c = start[i];
UChar next = 0;
if (i < (len - 1)) {
next = start[i + 1];
}
// for now, don't bother with escape sequences like \x41 => 'A' for double quoted strings and heredoc
if (isSingleQuoteString && c == '\\' && next == '\'') {
// a literal single quote
lexeme.append(next);
i++;
added++;
}
else if (isSingleQuoteString && c == '\\' && next == '\\') {
// a literal backslash
lexeme.append(c);
i++;
added++;
}
else if (isDoubleQuoteString && c == '\\' && next == '"') {
// a literal double quote
lexeme.append(next);
i++;
added++;
}
else if (isDoubleQuoteString && c == '\\' && next == '\\') {
// a literal backslash
lexeme.append(c);
i++;
added++;
}
else {
// any other token (identifier, keyword, symbol) just goes in as is
lexeme.append(c);
added++;
}
}
if (added > 3 && start[0] == '<' && start[1] == '<' && start[2] == '<') {
if (start[3] == '\'') {
isNowdoc = true;
}
else {
isHeredoc = true;
}
}
if (isHeredoc || isNowdoc) {
// remove the "<<<" and identifier from the heredoc start.
// and the identifier from the end. we don't need to actually check
// for the identifier here; nextToken() already makes sure that the
// beginning and ending identifiers are the same
for (int i = 0; i < lexeme.length(); i++) {
UChar c = lexeme.charAt(i);
lexeme.remove(0, 1);
i--;
if (c == '\n' || c == '\r') {
break;
}
}
// take care of the final newline
lexeme.trim();
// take care of the newline and endind identifier
for (int i = lexeme.length() - 1; i >= 0 && !lexeme.isEmpty(); i--) {
UChar c = lexeme.charAt(i);
lexeme.remove(i, 1);
if (c == '\n' || c == '\r') {
break;
}
}
}
ret = true;
}
return ret;
}
int pelet::LexicalAnalyzerClass::GetLineNumber() const {
return Buffer ? Buffer->GetLineNumber() : 0;
}
int pelet::LexicalAnalyzerClass::GetCharacterPosition() const {
return Buffer ? Buffer->GetCharacterPosition() : 0;
}
std::string pelet::LexicalAnalyzerClass::GetFileName() const {
return FileName;
}
/**
* @return TRUE if c is a character that can be in a PHP identifier
*/
static bool IsPhpIdentifierChar(UChar c) {
return u_isalnum(c) || '_' == c || (c >= 0x7f && c <= 0xff);
}
UnicodeString pelet::LexicalAnalyzerClass::LastExpression(const UnicodeString& code) const {
bool done = false;
// keep iterating backwards; if we used re2c lexer then we would have to iterate through the entire
// string
int32_t index = code.length() - 1;
// the resulting string will only keep non-space characters
// we need to keep remove spacing because expression can have whitepace
// like this "$this->\nprop->\nprop"
UnicodeString expr;
while (!done && index >= 0) {
UChar32 c = code[index];
if (IsPhpIdentifierChar(c)) {
// get the entire token
while (IsPhpIdentifierChar(c) && index > 0) {
// since we are iterating backwards, put char in the beginning
expr.insert(0, c);
index--;
c = code[index];
}
}
else if (u_isspace(c) && index > 0) {
// skip whitespace entirely
while(u_isspace(c) && index > 0) {
index--;
c = code[index];
}
// if we encounter an object operator then we can continue grabbing the expression
// otherwise it means that we are done
if (index > 1 && ':' == code[index] && ':' == code[index - 1]) {
expr.insert(0, code[index]);
expr.insert(0, code[index - 1]);
index -= 2;
}
else if (index > 1 && '>' == code[index] && '-' == code[index - 1]) {
expr.insert(0, code[index]);
expr.insert(0, code[index - 1]);
index -= 2;
}
else {
done = true;
}
}
else if ('$' == c) {
expr.insert(0, c);
index--;
// indirect variables means we are done ("$$expr")
if (index >= 0 && '$' == code[index]) {
done = true;
}
// indirect properties means we are done ("$this->$expr")
if (index >= 1 && '>' == code[index] && '-' == code[index - 1]) {
done = true;
}
}
else if (':' == c && index > 1) {
// check for a possible static object operator; if not an object operator then we are done
index--;
UChar32 n = code[index];
if (':' == n) {
index--;
expr.insert(0, c);
expr.insert(0, n);
// skip whitespace before the operator entirely
c = code[index];
while(u_isspace(c) && index > 0) {
index--;
c = code[index];
}
}
else {
done = true;
}
}
else if (')' == c) {
// skip all the way past the beginning '(', taking care to look for nested function calls
int nestCount = 1;
expr.insert(0, c);
while (index > 0 && nestCount > 0) {
index--;
c = code[index];
if (')' == c) {
nestCount++;
}
else if ('(' == c) {
nestCount--;
}
expr.insert(0, c);
}
index--;
}
else if (']' == c) {
// skip all the way past the beginning '[', taking care to look for 2-D arrays
int nestCount = 1;
expr.insert(0, c);
while (index > 0 && nestCount > 0) {
index--;
c = code[index];
if (']' == c) {
nestCount++;
}
else if ('[' == c) {
nestCount--;
}
expr.insert(0, c);
}
index--;
}
else if ('>' == c && index > 1) {
// check for a possible object operator; if not an object operator then we are done
index--;
UChar32 n = code[index];
if ('-' == n) {
index--;
expr.insert(0, c);
expr.insert(0, n);
// skip whitespace before the operator entirely
c = code[index];
while(u_isspace(c) && index > 0) {
index--;
c = code[index];
}
}
else {
done = true;
}
}
else if ('\\' == c) {
// namespace operator; keep it
// since we are iterating backwards, put char in the beginning
expr.insert(0, c);
index--;
}
else {
// anything else ignore
// like semicolons or commas or other operators; these signal a new expression
done = true;
}
}
return expr;
}
<commit_msg>clear out parser error string before opening each file<commit_after>/**
* This software is released under the terms of the MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @copyright 2009-2012 Roberto Perpuly
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
#include <pelet/LexicalAnalyzerClass.h>
#include <pelet/Php53LexicalAnalyzer.h>
#include <pelet/Php54LexicalAnalyzer.h>
#include <unicode/uchar.h>
#include <unicode/ustring.h>
#include <unicode/ucnv.h>
pelet::LexicalAnalyzerClass::LexicalAnalyzerClass(const std::string& fileName)
: ParserError()
, Buffer(NULL)
, FileName()
, Condition(yycINLINE_HTML)
, Version(PHP_53) {
OpenFile(fileName);
}
pelet::LexicalAnalyzerClass::LexicalAnalyzerClass()
: ParserError()
, Buffer(NULL)
, FileName()
, Condition(yycINLINE_HTML)
, Version(PHP_53) {
}
pelet::LexicalAnalyzerClass::~LexicalAnalyzerClass() {
Close();
}
void pelet::LexicalAnalyzerClass::Close() {
if (Buffer) {
Buffer->Close();
delete Buffer;
Buffer = NULL;
}
}
bool pelet::LexicalAnalyzerClass::OpenFile(const std::string& newFile) {
Close();
ParserError = UNICODE_STRING_SIMPLE("");
UCharBufferedFileClass* bufferFile = new UCharBufferedFileClass();
Buffer = bufferFile;
FileName = newFile;
Condition = yycINLINE_HTML;
return bufferFile->OpenFile(newFile.c_str());
}
bool pelet::LexicalAnalyzerClass::OpenFile(FILE* file) {
Close();
FileName = "";
ParserError = UNICODE_STRING_SIMPLE("");
UCharBufferedFileClass* bufferFile = new UCharBufferedFileClass();
Buffer = bufferFile;
Condition = yycINLINE_HTML;
return bufferFile->OpenFile(file);
}
bool pelet::LexicalAnalyzerClass::OpenString(const UnicodeString& code) {
Close();
FileName = "";
ParserError = UNICODE_STRING_SIMPLE("");
Condition = yycSCRIPT;
pelet::UCharBufferClass* memBuffer = new UCharBufferClass();
Buffer = memBuffer;
return memBuffer->OpenString(code);
}
void pelet::LexicalAnalyzerClass::SetVersion(Versions version) {
Version = version;
}
int pelet::LexicalAnalyzerClass::NextToken() {
if (PHP_53 == Version) {
return Buffer ? pelet::Next53Token(Buffer, Condition) : T_END;
}
else {
return Buffer ? pelet::Next54Token(Buffer, Condition) : T_END;
}
}
bool pelet::LexicalAnalyzerClass::GetLexeme(UnicodeString& lexeme) {
if (!Buffer) {
return false;
}
lexeme.remove();
const UChar *start = Buffer->TokenStart;
const UChar *end = Buffer->Current;
bool ret = false;
bool isSingleQuoteString = false;
bool isDoubleQuoteString = false;
bool isHeredoc = false;
bool isNowdoc = false;
// be careful, take Limit into account too... we dont want to read past what is allowed
if ((end - start) > 0 && Buffer->Current <= Buffer->Limit) {
// the lexer may ask for too much when the last token is an identifier
// in this case current will point to past the null character
if (Buffer->Current > Buffer->Limit) {
end = Buffer->Limit;
}
if (start[0] == '\'') {
isSingleQuoteString = true;
start++;
end--;
}
if (start[0] == '"') {
isDoubleQuoteString = true;
start++;
end--;
}
int len = (end - start);
int added = 0;
for (int i = 0; i < len; i++) {
UChar c = start[i];
UChar next = 0;
if (i < (len - 1)) {
next = start[i + 1];
}
// for now, don't bother with escape sequences like \x41 => 'A' for double quoted strings and heredoc
if (isSingleQuoteString && c == '\\' && next == '\'') {
// a literal single quote
lexeme.append(next);
i++;
added++;
}
else if (isSingleQuoteString && c == '\\' && next == '\\') {
// a literal backslash
lexeme.append(c);
i++;
added++;
}
else if (isDoubleQuoteString && c == '\\' && next == '"') {
// a literal double quote
lexeme.append(next);
i++;
added++;
}
else if (isDoubleQuoteString && c == '\\' && next == '\\') {
// a literal backslash
lexeme.append(c);
i++;
added++;
}
else {
// any other token (identifier, keyword, symbol) just goes in as is
lexeme.append(c);
added++;
}
}
if (added > 3 && start[0] == '<' && start[1] == '<' && start[2] == '<') {
if (start[3] == '\'') {
isNowdoc = true;
}
else {
isHeredoc = true;
}
}
if (isHeredoc || isNowdoc) {
// remove the "<<<" and identifier from the heredoc start.
// and the identifier from the end. we don't need to actually check
// for the identifier here; nextToken() already makes sure that the
// beginning and ending identifiers are the same
for (int i = 0; i < lexeme.length(); i++) {
UChar c = lexeme.charAt(i);
lexeme.remove(0, 1);
i--;
if (c == '\n' || c == '\r') {
break;
}
}
// take care of the final newline
lexeme.trim();
// take care of the newline and endind identifier
for (int i = lexeme.length() - 1; i >= 0 && !lexeme.isEmpty(); i--) {
UChar c = lexeme.charAt(i);
lexeme.remove(i, 1);
if (c == '\n' || c == '\r') {
break;
}
}
}
ret = true;
}
return ret;
}
int pelet::LexicalAnalyzerClass::GetLineNumber() const {
return Buffer ? Buffer->GetLineNumber() : 0;
}
int pelet::LexicalAnalyzerClass::GetCharacterPosition() const {
return Buffer ? Buffer->GetCharacterPosition() : 0;
}
std::string pelet::LexicalAnalyzerClass::GetFileName() const {
return FileName;
}
/**
* @return TRUE if c is a character that can be in a PHP identifier
*/
static bool IsPhpIdentifierChar(UChar c) {
return u_isalnum(c) || '_' == c || (c >= 0x7f && c <= 0xff);
}
UnicodeString pelet::LexicalAnalyzerClass::LastExpression(const UnicodeString& code) const {
bool done = false;
// keep iterating backwards; if we used re2c lexer then we would have to iterate through the entire
// string
int32_t index = code.length() - 1;
// the resulting string will only keep non-space characters
// we need to keep remove spacing because expression can have whitepace
// like this "$this->\nprop->\nprop"
UnicodeString expr;
while (!done && index >= 0) {
UChar32 c = code[index];
if (IsPhpIdentifierChar(c)) {
// get the entire token
while (IsPhpIdentifierChar(c) && index > 0) {
// since we are iterating backwards, put char in the beginning
expr.insert(0, c);
index--;
c = code[index];
}
}
else if (u_isspace(c) && index > 0) {
// skip whitespace entirely
while(u_isspace(c) && index > 0) {
index--;
c = code[index];
}
// if we encounter an object operator then we can continue grabbing the expression
// otherwise it means that we are done
if (index > 1 && ':' == code[index] && ':' == code[index - 1]) {
expr.insert(0, code[index]);
expr.insert(0, code[index - 1]);
index -= 2;
}
else if (index > 1 && '>' == code[index] && '-' == code[index - 1]) {
expr.insert(0, code[index]);
expr.insert(0, code[index - 1]);
index -= 2;
}
else {
done = true;
}
}
else if ('$' == c) {
expr.insert(0, c);
index--;
// indirect variables means we are done ("$$expr")
if (index >= 0 && '$' == code[index]) {
done = true;
}
// indirect properties means we are done ("$this->$expr")
if (index >= 1 && '>' == code[index] && '-' == code[index - 1]) {
done = true;
}
}
else if (':' == c && index > 1) {
// check for a possible static object operator; if not an object operator then we are done
index--;
UChar32 n = code[index];
if (':' == n) {
index--;
expr.insert(0, c);
expr.insert(0, n);
// skip whitespace before the operator entirely
c = code[index];
while(u_isspace(c) && index > 0) {
index--;
c = code[index];
}
}
else {
done = true;
}
}
else if (')' == c) {
// skip all the way past the beginning '(', taking care to look for nested function calls
int nestCount = 1;
expr.insert(0, c);
while (index > 0 && nestCount > 0) {
index--;
c = code[index];
if (')' == c) {
nestCount++;
}
else if ('(' == c) {
nestCount--;
}
expr.insert(0, c);
}
index--;
}
else if (']' == c) {
// skip all the way past the beginning '[', taking care to look for 2-D arrays
int nestCount = 1;
expr.insert(0, c);
while (index > 0 && nestCount > 0) {
index--;
c = code[index];
if (']' == c) {
nestCount++;
}
else if ('[' == c) {
nestCount--;
}
expr.insert(0, c);
}
index--;
}
else if ('>' == c && index > 1) {
// check for a possible object operator; if not an object operator then we are done
index--;
UChar32 n = code[index];
if ('-' == n) {
index--;
expr.insert(0, c);
expr.insert(0, n);
// skip whitespace before the operator entirely
c = code[index];
while(u_isspace(c) && index > 0) {
index--;
c = code[index];
}
}
else {
done = true;
}
}
else if ('\\' == c) {
// namespace operator; keep it
// since we are iterating backwards, put char in the beginning
expr.insert(0, c);
index--;
}
else {
// anything else ignore
// like semicolons or commas or other operators; these signal a new expression
done = true;
}
}
return expr;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "menuinterface.h"
#ifdef _WIN32
#include <windows.h>
#endif
using namespace std;
/*
bool systemCheck
{
#ifdef _APPLE_
return 0;
#elif _WIN32
return 1;
#else
return 2;
#endif
}
*/
MenuInterface::MenuInterface()
{
_firstTimeBooting = 0;
}
void MenuInterface::invalidInput()
{
cout << endl;
cout << "Your input was invalid, please try again." << endl;
cout << endl;
}
void MenuInterface::banner()
{
//if program is run on Windows then the banner is displayed in color
#ifdef _WIN32
//sets color of font to pink
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 13);
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
}
//if program is run on Apple the banner displays white as normal
#else
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
}
#endif
}
void MenuInterface::DisplayMenu()
{
string choice;
while(choice != "Q" || choice != "q")
{
cout << "| 1 | Display either a computer or a scientist" << endl;
cout << "| 2 | Search the list" << endl;
cout << "| 3 | Add to the list" << endl;
cout << "| 4 | Remove from the list" << endl;
cout << "| Q | Exit the program" << endl;
cout << "Enter your choice here: ";
cin >> choice;
cout << endl;
if(choice == constants::DISPLAY_LIST || choice == constants::ADD || choice == constants::SEARCH || choice == constants::REMOVE)
{
processChoice(choice);
}
else if(choice == "Q" || choice == "q")
{
char choice;
cout << "Are you sure you want to quit the program?" << endl;
cout << "Enter y for yes, and n for no: ";
cin >> choice;
if(choice != 'y' && choice != 'Y')
{
cout << endl;
DisplayMenu();
}
else
{
cout << endl;
return;
}
}
else
{
invalidInput();
banner();
DisplayMenu();
}
}
}
void MenuInterface::processChoice(const string choice)
{
string subMenuChoice = "";
while(subMenuChoice != "1" || subMenuChoice != "2")
{
cout << endl;
cout << "Choose either:" << endl;
cout << "| 1 | Computer " << endl;
cout << "| 2 | Scientist " << endl;
cin >> subMenuChoice;
if(subMenuChoice != "1" || subMenuChoice != "2")
{
invalidInput();
}
else
{
cout << "HALLO FROM OKOKOK";
}
}
int subMenuInt = stoi(subMenuChoice);
int choiceInt = stoi(choice);
banner();
// Computer operations
if(subMenuInt == constants::INT_COMPUTER)
{
switch (choiceInt)
{
case 1:
displayComputers();
break;
case 2:
_userLayer.searchForAComputer();
break;
case 3:
// banner();
// here could be the choice to add type of computer?
_userLayer.addComputer();
break;
case 4:
_userLayer.removeComputerFromList();
break;
default:
invalidInput();
break;
}
}
// Scientist operations
else if(subMenuInt == constants::INT_SCIENTIST)
{
switch (choiceInt)
{
case 1:
displayScientists();
break;
case 2:
_userLayer.searchForAPerson();
break;
case 3:
_userLayer.addPerson();
break;
case 4:
_userLayer.removePersonFromList();
break;
default:
// This should never run
invalidInput();
break;
}
}
else
{
// This should never run
cout << "Something went wrong" << endl;
}
}
void MenuInterface::displayComputers()
{
string sortOption;
_userLayer.printCompleteListOfComputers();
cout << "| 1 | Sort computers by alphabetical order" << endl;
cout << "| 2 | Sort computers by descending alphabetical order" << endl;
cout << "| 3 | Sort by year of build" << endl;
cout << "| 4 | Sort by year of design" << endl;
cout << "| 5 | Sort by type of computer" << endl;
cout << "| 6 | To view more info on a computer" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
// banner();
_userLayer.sortComputerListAlphabetically();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
// banner();
_userLayer.sortComputerListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_BUILDYEAR)
{
// banner();
_userLayer.sortComputerListByBuildYear();
}
else if(sortOption == constants::SORT_BY_DESIGNYEAR)
{
// banner();
_userLayer.sortComputerListByDesignYear();
}
else if(sortOption == constants::SORT_BY_TYPE)
{
// banner();
_userLayer.sortComputerListByType();
}
else if(sortOption == constants::MORE_INFO)
{
_userLayer.printListMoreInfoComputer();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
void MenuInterface::displayScientists()
{
string sortOption;
_userLayer.printCompleteList();
cout << "| 1 | Sort computer scientists by alphabetical order" << endl;
cout << "| 2 | Sort computer scientists by descending alphabetical order" << endl;
cout << "| 3 | Sort computer scientists by year of birth" << endl;
cout << "| 4 | Sort computer scientists by ascending year of birth" << endl;
cout << "| 5 | Sort computer scientists by year of death" << endl;
cout << "| 6 | Sort computer scientists by age" << endl;
cout << "| 7 | Sort computer scientists by gender" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabetically();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYear();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_DEATH)
{
banner();
_userLayer.sortScientistListByDeathYear();
}
else if(sortOption == constants::SORT_BY_AGE)
{
banner();
_userLayer.sortScientistListByAge();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_ASCENDING_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYearASC();
}
else if(sortOption == constants::SORT_BY_GENDER)
{
banner();
_userLayer.sortScientistListByGender();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
<commit_msg>minor fix for menuinterface<commit_after>#include <iostream>
#include "menuinterface.h"
#ifdef _WIN32
#include <windows.h>
#endif
using namespace std;
/*
bool systemCheck
{
#ifdef _APPLE_
return 0;
#elif _WIN32
return 1;
#else
return 2;
#endif
}
*/
MenuInterface::MenuInterface()
{
_firstTimeBooting = 0;
}
void MenuInterface::invalidInput()
{
cout << endl;
cout << "Your input was invalid, please try again." << endl;
cout << endl;
}
void MenuInterface::banner()
{
//if program is run on Windows then the banner is displayed in color
#ifdef _WIN32
//sets color of font to pink
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 13);
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
}
//if program is run on Apple the banner displays white as normal
#else
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
}
#endif
}
void MenuInterface::DisplayMenu()
{
string choice;
while(choice != "Q" || choice != "q")
{
cout << "| 1 | Display either a computer or a scientist" << endl;
cout << "| 2 | Search the list" << endl;
cout << "| 3 | Add to the list" << endl;
cout << "| 4 | Remove from the list" << endl;
cout << "| Q | Exit the program" << endl;
cout << "Enter your choice here: ";
cin >> choice;
cout << endl;
if(choice == constants::DISPLAY_LIST || choice == constants::ADD || choice == constants::SEARCH || choice == constants::REMOVE)
{
processChoice(choice);
}
else if(choice == "Q" || choice == "q")
{
char choice;
cout << "Are you sure you want to quit the program?" << endl;
cout << "Enter y for yes, and n for no: ";
cin >> choice;
if(choice != 'y' && choice != 'Y')
{
cout << endl;
DisplayMenu();
}
else
{
cout << endl;
return;
}
}
else
{
invalidInput();
banner();
DisplayMenu();
}
}
}
void MenuInterface::processChoice(const string choice)
{
string subMenuChoice = "";
while(subMenuChoice != "1" || subMenuChoice != "2")
{
cout << endl;
cout << "Choose either:" << endl;
cout << "| 1 | Computer " << endl;
cout << "| 2 | Scientist " << endl;
cin >> subMenuChoice;
if(subMenuChoice == "1")
cout << "hommz" << endl;
if(subMenuChoice != "1" || subMenuChoice != "2")
{
invalidInput();
}
}
cout << "out of the loop"<< endl;
int subMenuInt = stoi(subMenuChoice);
int choiceInt = stoi(choice);
banner();
// Computer operations
if(subMenuInt == constants::INT_COMPUTER)
{
switch (choiceInt)
{
case 1:
displayComputers();
break;
case 2:
_userLayer.searchForAComputer();
break;
case 3:
// banner();
// here could be the choice to add type of computer?
_userLayer.addComputer();
break;
case 4:
_userLayer.removeComputerFromList();
break;
default:
invalidInput();
break;
}
}
// Scientist operations
else if(subMenuInt == constants::INT_SCIENTIST)
{
switch (choiceInt)
{
case 1:
displayScientists();
break;
case 2:
_userLayer.searchForAPerson();
break;
case 3:
_userLayer.addPerson();
break;
case 4:
_userLayer.removePersonFromList();
break;
default:
// This should never run
invalidInput();
break;
}
}
else
{
// This should never run
cout << "Something went wrong" << endl;
}
}
void MenuInterface::displayComputers()
{
string sortOption;
_userLayer.printCompleteListOfComputers();
cout << "| 1 | Sort computers by alphabetical order" << endl;
cout << "| 2 | Sort computers by descending alphabetical order" << endl;
cout << "| 3 | Sort by year of build" << endl;
cout << "| 4 | Sort by year of design" << endl;
cout << "| 5 | Sort by type of computer" << endl;
cout << "| 6 | To view more info on a computer" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
// banner();
_userLayer.sortComputerListAlphabetically();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
// banner();
_userLayer.sortComputerListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_BUILDYEAR)
{
// banner();
_userLayer.sortComputerListByBuildYear();
}
else if(sortOption == constants::SORT_BY_DESIGNYEAR)
{
// banner();
_userLayer.sortComputerListByDesignYear();
}
else if(sortOption == constants::SORT_BY_TYPE)
{
// banner();
_userLayer.sortComputerListByType();
}
else if(sortOption == constants::MORE_INFO)
{
_userLayer.printListMoreInfoComputer();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
void MenuInterface::displayScientists()
{
string sortOption;
_userLayer.printCompleteList();
cout << "| 1 | Sort computer scientists by alphabetical order" << endl;
cout << "| 2 | Sort computer scientists by descending alphabetical order" << endl;
cout << "| 3 | Sort computer scientists by year of birth" << endl;
cout << "| 4 | Sort computer scientists by ascending year of birth" << endl;
cout << "| 5 | Sort computer scientists by year of death" << endl;
cout << "| 6 | Sort computer scientists by age" << endl;
cout << "| 7 | Sort computer scientists by gender" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabetically();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYear();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_DEATH)
{
banner();
_userLayer.sortScientistListByDeathYear();
}
else if(sortOption == constants::SORT_BY_AGE)
{
banner();
_userLayer.sortScientistListByAge();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_ASCENDING_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYearASC();
}
else if(sortOption == constants::SORT_BY_GENDER)
{
banner();
_userLayer.sortScientistListByGender();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 augmented-go team
// See the file LICENSE for full license and copying terms.
#pragma once
#include <QMainWindow>
#include <QFileDialog>
#include <QDebug>
#include <QTimer>
#include "Game.hpp"
#include "ui_GUI.h"
#include "ui_NewGameDialog.h"
#include "AugmentedView.hpp"
#include "VirtualView.hpp"
namespace Go_GUI {
class GUI : public QMainWindow
{
Q_OBJECT
private:
Ui::MainWindow ui_main;
VirtualView* virtual_view;
AugmentedView* augmented_view;
QPixmap whitebasket_pixmap, blackbasket_pixmap, closedbasket_pixmap, gotable_pixmap;
QImage augmented_logo;
QIcon switchbutton_icon, switchbuttonpressed_icon;
QString game_name, texture_path;
// Pointer to the game board, will be set & cached in the slot "slot_newGameData".
// This pointer will be valid until the GUI exits the application or the backend sends a new one.
const GoBackend::Game* go_game;
/**
* @brief Sets initial settings like the content of views, texts and windows
*/
void init();
/**
* @brief sets labels and variables for player names.
* @param QString name of black player (default: "Black"
* @param QString name of white player (default: "White"
*/
void setPlayerLabels(QString blackplayer_name, QString whiteplayer_name);
/**
* @brief overridden SLOT QCloseEvent "resizeEvent"
* @param QResizeEvent* resize event
*/
void resizeEvent(QResizeEvent* event){
QMainWindow::resizeEvent(event);
virtual_view->resizeEvent(event);
}
/**
* @brief overridden SLOT QCloseEvent "closeEvent"
* When trying to close the application a window appears and asks if user is sure.
* If answered "yes" the a signal to the backend thread is sent to stop it.
* If answered "no" the close event is ignored.
* @param QCloseEvent close event that shall or shall not be executed afterwards.
*/
void closeEvent(QCloseEvent *event);
public:
/**
* @brief Checks for gui elements and fonts.
* Connects signals and slots.
* @param QWidget/QMainWindow parent widget that creates this
*/
GUI(QWidget *parent = 0);
~GUI(){};
signals:
/**
* @brief signals that the user wants to save a game.
* @param QString filename name of file
* @param QString blackplayer_label name of black player
* @param QString whiteplayer_label name of white player
* @param QString game_name name of game
*/
void signal_saveGame(QString fileName, QString blackplayer_label, QString whiteplayer_label, QString game_name);
/**
* @brief signals that the user wants to open a game.
* @param QString filename name of file
*/
void signal_openGame(QString fileName);
/** @brief signals that the user wants to pass. */
void signal_pass();
/** @brief signals that the user wants to resign. */
void signal_resign();
/** @brief signals that the user wants to use manual board detection. */
void signal_boardDetectionManually();
/** @brief signals that the user wants to use automatic board detection. */
void signal_boardDetectionAutomatically();
/** @brief signals that the user wants to use virtual game mode. */
void signal_setVirtualGameMode(bool checked);
/** @brief signals that backend thread should stop. */
void stop_backend_thread();
/**
* @brief signals that the user wants to start a new game.
* @param GoRules rules rules of the new game
*/
void signal_newGame(GoRules rules);
/**
* @brief signals that the user wants to play a move.
* Coordinates on board start with 1,1 !
* @param int x x-Coordinate on board
* @param int y y-Coordinate on board
*/
void signal_playMove(const int x, const int y);
void signal_setScannerDebugImage(bool debug);
private slots:
/**
* @brief SLOT "NewGame/Reset"
* Opens a Dialog that asks for game rules and names.
*/
void slot_ButtonNewGame();
/**
* @brief SLOT "Resign"
* Opens a Dialog that asks for confirmation.
* If answered yes, a signal is sent to backend that the current player surrenders.
*/
void slot_ButtonResign();
/**
* @brief SLOT "Pass"
* Opens a Dialog that asks for confirmation.
* If answered yes, a signal is sent to backend that the current player passes.
*/
void slot_ButtonPass();
/**
* @brief SLOT QAction "MenuOpen"
* opens a filedialog that lets the user choose an sgf-file.
* sends via "signal_openGame" filename to backend
*/
void slot_MenuOpen();
/**
* @brief SLOT QAction "MenuSave"
* opens a filedialog that lets the user choose an sgf-file.
* sends via "signal_saveGame" filename, gamename and playernames to backend
*/
void slot_MenuSave();
/**
* @brief SLOT QAction "MenuInfo"
* opens a window with information about the application.
*/
void slot_MenuInfo();
/**
* @brief SLOT "ViewSwitch"
* Switches big view with small view.
* To assign a view to something a QWidget has to be created.
*/
void slot_ViewSwitch();
void slot_ViewSwitch_released();
/**
* @brief SLOT BoardDetectionManually
* Repeates a signal from the QAction "manually_action"
* to notify to manually detect gameboard
*/
void slot_BoardDetectionManually();
/**
* @brief SLOT BoardDetectionManually
* Repeates a signal from the QAction "manually_action"
* to notify to automatically detect gameboard
*/
void slot_BoardDetectionAutomatically();
/**
* @brief SLOT ToggleVirtualGameMode
* Sends a signal which determines the game mode the user chose
*/
void slot_ToggleVirtualGameMode();
/**
* @brief SLOT passOnVirtualViewPlayMove
* Repeates a signal from Virtual View to backend.
* The signal has the position of the board the player wants to
* place a stone to.
*/
void slot_passOnVirtualViewPlayMove(const int x, const int y);
/**
* @brief SLOT toggleScannerDebugImage
* Sends a signal which determines the scanner image mode the user chose
*/
void slot_toggleScannerDebugImage();
public slots:
/**
* @brief SLOT "new image"
* If a new image is sent to GUI, refresh and rescale picture.
* @param QImage new image from scanner
*/
void slot_newImage(QImage image);
/**
* @brief SLOT "new game data"
* If new game data is sent to GUI, refresh display of current player and captured stones.
* @param game new game representation
*/
void slot_newGameData(const GoBackend::Game* game);
/**
* @brief SLOT "Show finished game results"
* If a game ended, the BackendThread sends a signal with the results.
* Here the results are shown to the user.
*/
void slot_showFinishedGameResults(QString result);
/**
* @brief SLOT "setup new game"
* When a new game has been started, setup game name and player names on gui.
* @param QString game name
* @param QString black player name
* @param QString white player name
*/
void slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi);
};
} // namespace Go_GUI<commit_msg>closes #90 added comments<commit_after>// Copyright (c) 2013 augmented-go team
// See the file LICENSE for full license and copying terms.
#pragma once
#include <QMainWindow>
#include <QFileDialog>
#include <QDebug>
#include <QTimer>
#include "Game.hpp"
#include "ui_GUI.h"
#include "ui_NewGameDialog.h"
#include "AugmentedView.hpp"
#include "VirtualView.hpp"
namespace Go_GUI {
class GUI : public QMainWindow
{
Q_OBJECT
private:
Ui::MainWindow ui_main;
VirtualView* virtual_view;
AugmentedView* augmented_view;
QPixmap whitebasket_pixmap, blackbasket_pixmap, closedbasket_pixmap, gotable_pixmap;
QImage augmented_logo;
QIcon switchbutton_icon, switchbuttonpressed_icon;
QString game_name, texture_path;
// Pointer to the game board, will be set & cached in the slot "slot_newGameData".
// This pointer will be valid until the GUI exits the application or the backend sends a new one.
const GoBackend::Game* go_game;
/**
* @brief Sets initial settings like the content of views, texts and windows
*/
void init();
/**
* @brief sets labels and variables for player names.
* @param QString name of black player (default: "Black"
* @param QString name of white player (default: "White"
*/
void setPlayerLabels(QString blackplayer_name, QString whiteplayer_name);
/**
* @brief overridden SLOT QCloseEvent "resizeEvent"
* @param QResizeEvent* resize event
*/
void resizeEvent(QResizeEvent* event){
QMainWindow::resizeEvent(event);
virtual_view->resizeEvent(event);
}
/**
* @brief overridden SLOT QCloseEvent "closeEvent"
* When trying to close the application a window appears and asks if user is sure.
* If answered "yes" the a signal to the backend thread is sent to stop it.
* If answered "no" the close event is ignored.
* @param QCloseEvent close event that shall or shall not be executed afterwards.
*/
void closeEvent(QCloseEvent *event);
public:
/**
* @brief Checks for gui elements and fonts.
* Connects signals and slots.
* @param QWidget/QMainWindow parent widget that creates this
*/
GUI(QWidget *parent = 0);
~GUI(){};
signals:
/**
* @brief signals that the user wants to save a game.
* @param QString filename name of file
* @param QString blackplayer_label name of black player
* @param QString whiteplayer_label name of white player
* @param QString game_name name of game
*/
void signal_saveGame(QString fileName, QString blackplayer_label, QString whiteplayer_label, QString game_name);
/**
* @brief signals that the user wants to open a game.
* @param QString filename name of file
*/
void signal_openGame(QString fileName);
/** @brief signals that the user wants to pass. */
void signal_pass();
/** @brief signals that the user wants to resign. */
void signal_resign();
/** @brief signals that the user wants to use manual board detection. */
void signal_boardDetectionManually();
/** @brief signals that the user wants to use automatic board detection. */
void signal_boardDetectionAutomatically();
/** @brief signals that the user wants to use virtual game mode. */
void signal_setVirtualGameMode(bool checked);
/** @brief signals that backend thread should stop. */
void stop_backend_thread();
/**
* @brief signals that the user wants to start a new game.
* @param GoRules rules rules of the new game
*/
void signal_newGame(GoRules rules);
/**
* @brief signals that the user wants to play a move.
* Coordinates on board start with 1,1 !
* @param int x x-Coordinate on board
* @param int y y-Coordinate on board
*/
void signal_playMove(const int x, const int y);
void signal_setScannerDebugImage(bool debug);
private slots:
/**
* @brief SLOT "NewGame/Reset"
* Opens a Dialog that asks for game rules and names.
*/
void slot_ButtonNewGame();
/**
* @brief SLOT "Resign"
* Opens a Dialog that asks for confirmation.
* If answered yes, a signal is sent to backend that the current player surrenders.
*/
void slot_ButtonResign();
/**
* @brief SLOT "Pass"
* Opens a Dialog that asks for confirmation.
* If answered yes, a signal is sent to backend that the current player passes.
*/
void slot_ButtonPass();
/**
* @brief SLOT QAction "MenuOpen"
* opens a filedialog that lets the user choose an sgf-file.
* sends via "signal_openGame" filename to backend
*/
void slot_MenuOpen();
/**
* @brief SLOT QAction "MenuSave"
* opens a filedialog that lets the user choose an sgf-file.
* sends via "signal_saveGame" filename, gamename and playernames to backend
*/
void slot_MenuSave();
/**
* @brief SLOT QAction "MenuInfo"
* opens a window with information about the application.
*/
void slot_MenuInfo();
/**
* @brief SLOT "ViewSwitch"
* Switches big view with small view.
* To assign a view to something a QWidget has to be created.
* Changes the appereance of button to "pressed"
*/
void slot_ViewSwitch();
/**
* @brief SLOT "ViewSwitch_released"
* changes the appereance of button back to normal/"unpressed"
*/
void slot_ViewSwitch_released();
/**
* @brief SLOT BoardDetectionManually
* Repeates a signal from the QAction "manually_action"
* to notify to manually detect gameboard
*/
void slot_BoardDetectionManually();
/**
* @brief SLOT BoardDetectionManually
* Repeates a signal from the QAction "manually_action"
* to notify to automatically detect gameboard
*/
void slot_BoardDetectionAutomatically();
/**
* @brief SLOT ToggleVirtualGameMode
* Sends a signal which determines the game mode the user chose
*/
void slot_ToggleVirtualGameMode();
/**
* @brief SLOT passOnVirtualViewPlayMove
* Repeates a signal from Virtual View to backend.
* The signal has the position of the board the player wants to
* place a stone to.
*/
void slot_passOnVirtualViewPlayMove(const int x, const int y);
/**
* @brief SLOT toggleScannerDebugImage
* Sends a signal which determines the scanner image mode the user chose
*/
void slot_toggleScannerDebugImage();
public slots:
/**
* @brief SLOT "new image"
* If a new image is sent to GUI, refresh and rescale picture.
* @param QImage new image from scanner
*/
void slot_newImage(QImage image);
/**
* @brief SLOT "new game data"
* If new game data is sent to GUI, refresh display of current player and captured stones.
* @param game new game representation
*/
void slot_newGameData(const GoBackend::Game* game);
/**
* @brief SLOT "Show finished game results"
* If a game ended, the BackendThread sends a signal with the results.
* Here the results are shown to the user.
*/
void slot_showFinishedGameResults(QString result);
/**
* @brief SLOT "setup new game"
* When a new game has been started, setup game name and player names on gui.
* @param QString game name
* @param QString black player name
* @param QString white player name
*/
void slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi);
};
} // namespace Go_GUI<|endoftext|> |
<commit_before>#include <numeric>
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtx/compatibility.hpp"
#include "glm/gtx/epsilon.hpp"
#include "glm/gtx/quaternion.hpp"
#include "wx/dir.h"
#include "MainFrame.hpp"
void MainFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch(event.GetId())
{
case ID_RECONSTRUCT: event.Enable(m_has_images); break;
case ID_EXPORT_MATCHES: event.Enable(m_matches_loaded); break;
case ID_EXPORT_TRACKS: event.Enable(m_matches_loaded); break;
case ID_EXPORT_CMVS: event.Enable(m_sfm_done); break;
case ID_EXPORT_BUNDLE_FILE: event.Enable(m_sfm_done); break;
case ID_EXPORT_PLY_FILE: event.Enable(m_sfm_done); break;
case ID_EXPORT_MESHLAB_FILE: event.Enable(m_sfm_done); break;
case ID_EXPORT_MAYA_FILE: event.Enable(m_sfm_done); break;
case ID_TOGGLE_FRUSTRUM_VISIBILITY: event.Enable(m_sfm_done); break;
case ID_TOGGLE_POINTS_VISIBILITY: event.Enable(m_sfm_done); break;
case ID_TOGGLE_CAMERAS_VISIBILITY: event.Enable(m_sfm_done); break;
case ID_PANE_MATCHES: event.Enable(m_sfm_done); break;
default: event.Skip();
}
}
void MainFrame::OnMenuExit(wxCommandEvent& event)
{
this->Close();
}
void MainFrame::OnClose(wxCloseEvent& event)
{
m_turntable_timer->Stop();
m_reset_viewport_timer->Stop();
this->Destroy();
}
void MainFrame::OnViewWindows(wxCommandEvent& event)
{
switch(event.GetId())
{
case ID_VIEW_IMAGE_BROWSER:
m_mgr.GetPane("Image browser").Show();
m_mgr.Update();
break;
case ID_VIEW_IMAGE_PREVIEW:
m_mgr.GetPane("Image preview").Show();
m_mgr.Update();
break;
case ID_VIEW_OPTIONS:
m_mgr.GetPane("Options").Show();
m_mgr.Update();
break;
case ID_VIEW_LOG:
m_mgr.GetPane("Log").Show();
m_mgr.Update();
break;
case ID_VIEW_ABOUT:
m_mgr.GetPane("About").Show();
m_mgr.Update();
break;
default: event.Skip();
}
}
void MainFrame::OnResetOptions(wxCommandEvent& event)
{
ResetOptions();
}
void MainFrame::OnReset3dViewport(wxCommandEvent& event)
{
if (m_reset_viewport_timer->IsRunning()) m_reset_viewport_timer->Stop();
else
{
m_counter = 0.0f;
m_reset_viewport_timer->Start(10);
}
}
void MainFrame::OnToggleTurntableAnimation(wxCommandEvent& event)
{
if (!m_turntable_timer->IsRunning()) m_turntable_timer->Start(10);
else m_turntable_timer->Stop();
m_gl_canvas->Refresh(false);
}
void MainFrame::OnToggleVisibility(wxCommandEvent& event)
{
switch(event.GetId())
{
case ID_TOGGLE_TRACKBALL_VISIBILITY:
if (m_scene->GetNode("Trackball X")->IsVisibleMesh() &&
m_scene->GetNode("Trackball Y")->IsVisibleMesh() &&
m_scene->GetNode("Trackball Z")->IsVisibleMesh())
{
m_scene->GetNode("Trackball X")->SetVisibilityMesh(false);
m_scene->GetNode("Trackball Y")->SetVisibilityMesh(false);
m_scene->GetNode("Trackball Z")->SetVisibilityMesh(false);
} else
{
m_scene->GetNode("Trackball X")->SetVisibilityMesh(true);
m_scene->GetNode("Trackball Y")->SetVisibilityMesh(true);
m_scene->GetNode("Trackball Z")->SetVisibilityMesh(true);
}
break;
case ID_TOGGLE_GRID_VISIBILITY:
{
auto grid = m_scene->GetNode("Grid");
if (grid->IsVisibleMesh()) grid->SetVisibilityMesh(false);
else grid->SetVisibilityMesh(true);
break;
}
case ID_TOGGLE_CAMERAS_VISIBILITY:
{
for (const auto &image : m_images)
{
if (!image.m_camera.m_adjusted) continue;
if (image.m_camera_mesh->IsVisibleMesh()) image.m_camera_mesh->SetVisibilityMesh(false);
else image.m_camera_mesh->SetVisibilityMesh(true);
}
break;
}
case ID_TOGGLE_POINTS_VISIBILITY:
{
auto points = m_scene->GetNode("Points");
if (points->IsVisibleMesh()) points->SetVisibilityMesh(false);
else points->SetVisibilityMesh(true);
break;
}
default: return;
}
m_gl_canvas->Refresh(false);
}
void MainFrame::OnTimerUpdate(wxTimerEvent& event)
{
switch (event.GetId())
{
case ID_TIMER_TURNTABLE:
{
auto camera = m_scene->GetCamera();
const auto rotation = camera->GetTrackballOrientation();
camera->RotateTrackball(glm::vec2{0.0f, 0.0f}, glm::vec2{-0.0002f * m_tb_turntable_speed_slider->GetValue(), 0.0f});
m_scene->GetNode("Trackball X")->GetTransform().SetOrientation(rotation * glm::angleAxis(90.0f, glm::vec3{0.0f, 1.0f, 0.0f}));
m_scene->GetNode("Trackball Y")->GetTransform().SetOrientation(rotation * glm::angleAxis(90.0f, glm::vec3{1.0f, 0.0f, 0.0f}));
m_scene->GetNode("Trackball Z")->GetTransform().SetOrientation(rotation);
break;
}
case ID_TIMER_RESET_VIEWPORT:
{
m_counter += 0.02f;
if (m_counter >= 1.0f) m_reset_viewport_timer->Stop();
auto camera = m_scene->GetCamera();
const auto quat_x = glm::angleAxis(15.0f, glm::vec3{1, 0, 0});
const auto quat_y = glm::angleAxis(45.0f, glm::vec3{0, 1, 0});
const auto quat_z = glm::angleAxis(0.0f, glm::vec3{0, 0, 1});
const auto orientation_start = camera->GetTrackballOrientation();
const auto orientation_target = quat_x * quat_y * quat_z;
const auto position_start = camera->GetTrackballPosition();
const auto position_target = glm::vec3{0.0f, 0.0f, 0.0f};
const auto zoom_start = camera->GetTrackballZoom();
const auto zoom_target = 1.0f;
const auto zoom_mix = glm::lerp(zoom_start, zoom_target, m_counter);
const auto position_mix = glm::lerp(position_start, position_target, m_counter);
const auto orientation_mix = glm::shortMix(orientation_start, orientation_target, m_counter);
camera->SetTrackballZoom(zoom_mix);
camera->SetTrackballPosition(position_mix);
camera->SetTrackballOrientation(orientation_mix);
const auto rotation = camera->GetTrackballOrientation();
m_scene->GetNode("Trackball X")->GetTransform().SetOrientation(orientation_mix * glm::angleAxis(90.0f, glm::vec3{0.0f, 1.0f, 0.0f}));
m_scene->GetNode("Trackball Y")->GetTransform().SetOrientation(orientation_mix * glm::angleAxis(90.0f, glm::vec3{1.0f, 0.0f, 0.0f}));
m_scene->GetNode("Trackball Z")->GetTransform().SetOrientation(orientation_mix);
m_beginx = m_beginy = 0.0f;
break;
}
default: event.Skip();
}
m_gl_canvas->Refresh(false);
}
void MainFrame::OnExport(wxCommandEvent& event)
{
switch(event.GetId())
{
case ID_EXPORT_TRACKS:
{
SaveTrackFile();
break;
}
case ID_EXPORT_MATCHES:
{
SaveMatchFile();
break;
}
case ID_EXPORT_CMVS:
{
ExportToCMVS(m_path);
break;
}
case ID_EXPORT_BUNDLE_FILE:
{
SaveBundleFile(m_path);
break;
}
case ID_EXPORT_PLY_FILE:
{
SavePlyFile();
break;
}
case ID_EXPORT_MESHLAB_FILE:
{
SaveMeshLabFile();
break;
}
case ID_EXPORT_MAYA_FILE:
{
SaveMayaFile();
break;
}
default: event.Skip();
}
}
void MainFrame::OnSaveLog(wxCommandEvent& event)
{
const auto target = m_path + R"(\Log.txt)";
if (m_tc_log->SaveFile(target)) wxLogMessage("Log saved to %s", target);
}
void MainFrame::OnClearLog(wxCommandEvent& event)
{
m_tc_log->Clear();
}
void MainFrame::OnSelectDirectory(wxFileDirPickerEvent& event)
{
wxString filename, focalPx, res, path;
path = m_dir_picker->GetPath();
m_path = (path).ToStdString();
wxDir dir{path};
m_images.clear();
m_profile_manager.Reset();
m_cb_matches_left->Clear();
m_cb_matches_right->Clear();
m_window_image_preview->Refresh(true);
m_pane_matches_view->Refresh(true);
m_img_ctrl->ClearAll();
m_img_ctrl->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 60);
m_img_ctrl->InsertColumn(1, "Resolution", wxLIST_FORMAT_LEFT, 75);
m_img_ctrl->InsertColumn(2, "Focal", wxLIST_FORMAT_LEFT, 50);
m_img_ctrl->InsertColumn(3, "Features", wxLIST_FORMAT_LEFT, 60);
m_img_ctrl->InsertColumn(4, "k1", wxLIST_FORMAT_LEFT, 40);
m_img_ctrl->InsertColumn(5, "k2", wxLIST_FORMAT_LEFT, 40);
// Parse directory and process jpg images
bool found = dir.GetFirst(&filename, "*.jpg", wxDIR_FILES);
int index = 0;
while (found)
{
// Get focal from EXIF tags, convert to px-coordinates and add image if successful
if(AddImage(dir.FindFirst(path, filename).ToStdString(), filename.ToStdString()))
{
m_img_ctrl->InsertItem(index, filename);
m_cb_matches_left->Append(filename);
m_cb_matches_right->Append(filename);
}
// Get the next jpg in the directory
found = dir.GetNext(&filename);
index++;
}
// Display findings
if(m_images.size() > 0)
{
for (int i = 0; i < (int)m_images.size(); i++)
{
res.Printf("%i x %i", GetImageWidth(i), GetImageHeight(i));
focalPx.Printf("%.2f", GetFocalLength(i));
m_img_ctrl->SetItem(i, 1, res, -1);
m_img_ctrl->SetItem(i, 2, focalPx, -1);
}
m_has_images = true;
wxLogMessage("%s: %i images ready for reconstruction", path, m_images.size());
} else
{
wxLogMessage("No suitable images found in %s", path);
}
}
void MainFrame::OnReconstruct(wxCommandEvent& event)
{
// Detect features
DetectFeaturesAll();
// Match features
if (m_options.feature_type != 2) MatchAll();
else MatchAllAkaze();
// Compute structure from motion in another thread
if (CreateThread(wxTHREAD_DETACHED) != wxTHREAD_NO_ERROR)
{
wxLogError("Error: Could not create the worker thread!");
return;
}
if (GetThread()->Run() != wxTHREAD_NO_ERROR)
{
wxLogError("Error: Could not run the worker thread!");
return;
}
}
<commit_msg>proper closing on close event<commit_after>#include <numeric>
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtx/compatibility.hpp"
#include "glm/gtx/epsilon.hpp"
#include "glm/gtx/quaternion.hpp"
#include "wx/dir.h"
#include "MainFrame.hpp"
void MainFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch(event.GetId())
{
case ID_RECONSTRUCT: event.Enable(m_has_images); break;
case ID_EXPORT_MATCHES: event.Enable(m_matches_loaded); break;
case ID_EXPORT_TRACKS: event.Enable(m_matches_loaded); break;
case ID_EXPORT_CMVS: event.Enable(m_sfm_done); break;
case ID_EXPORT_BUNDLE_FILE: event.Enable(m_sfm_done); break;
case ID_EXPORT_PLY_FILE: event.Enable(m_sfm_done); break;
case ID_EXPORT_MESHLAB_FILE: event.Enable(m_sfm_done); break;
case ID_EXPORT_MAYA_FILE: event.Enable(m_sfm_done); break;
case ID_TOGGLE_FRUSTRUM_VISIBILITY: event.Enable(m_sfm_done); break;
case ID_TOGGLE_POINTS_VISIBILITY: event.Enable(m_sfm_done); break;
case ID_TOGGLE_CAMERAS_VISIBILITY: event.Enable(m_sfm_done); break;
case ID_PANE_MATCHES: event.Enable(m_sfm_done); break;
default: event.Skip();
}
}
void MainFrame::OnMenuExit(wxCommandEvent& event)
{
this->Close();
}
void MainFrame::OnClose(wxCloseEvent& event)
{
m_turntable_timer->Stop();
m_reset_viewport_timer->Stop();
}
void MainFrame::OnViewWindows(wxCommandEvent& event)
{
switch(event.GetId())
{
case ID_VIEW_IMAGE_BROWSER:
m_mgr.GetPane("Image browser").Show();
m_mgr.Update();
break;
case ID_VIEW_IMAGE_PREVIEW:
m_mgr.GetPane("Image preview").Show();
m_mgr.Update();
break;
case ID_VIEW_OPTIONS:
m_mgr.GetPane("Options").Show();
m_mgr.Update();
break;
case ID_VIEW_LOG:
m_mgr.GetPane("Log").Show();
m_mgr.Update();
break;
case ID_VIEW_ABOUT:
m_mgr.GetPane("About").Show();
m_mgr.Update();
break;
default: event.Skip();
}
}
void MainFrame::OnResetOptions(wxCommandEvent& event)
{
ResetOptions();
}
void MainFrame::OnReset3dViewport(wxCommandEvent& event)
{
if (m_reset_viewport_timer->IsRunning()) m_reset_viewport_timer->Stop();
else
{
m_counter = 0.0f;
m_reset_viewport_timer->Start(10);
}
}
void MainFrame::OnToggleTurntableAnimation(wxCommandEvent& event)
{
if (!m_turntable_timer->IsRunning()) m_turntable_timer->Start(10);
else m_turntable_timer->Stop();
m_gl_canvas->Refresh(false);
}
void MainFrame::OnToggleVisibility(wxCommandEvent& event)
{
switch(event.GetId())
{
case ID_TOGGLE_TRACKBALL_VISIBILITY:
if (m_scene->GetNode("Trackball X")->IsVisibleMesh() &&
m_scene->GetNode("Trackball Y")->IsVisibleMesh() &&
m_scene->GetNode("Trackball Z")->IsVisibleMesh())
{
m_scene->GetNode("Trackball X")->SetVisibilityMesh(false);
m_scene->GetNode("Trackball Y")->SetVisibilityMesh(false);
m_scene->GetNode("Trackball Z")->SetVisibilityMesh(false);
} else
{
m_scene->GetNode("Trackball X")->SetVisibilityMesh(true);
m_scene->GetNode("Trackball Y")->SetVisibilityMesh(true);
m_scene->GetNode("Trackball Z")->SetVisibilityMesh(true);
}
break;
case ID_TOGGLE_GRID_VISIBILITY:
{
auto grid = m_scene->GetNode("Grid");
if (grid->IsVisibleMesh()) grid->SetVisibilityMesh(false);
else grid->SetVisibilityMesh(true);
break;
}
case ID_TOGGLE_CAMERAS_VISIBILITY:
{
for (const auto &image : m_images)
{
if (!image.m_camera.m_adjusted) continue;
if (image.m_camera_mesh->IsVisibleMesh()) image.m_camera_mesh->SetVisibilityMesh(false);
else image.m_camera_mesh->SetVisibilityMesh(true);
}
break;
}
case ID_TOGGLE_POINTS_VISIBILITY:
{
auto points = m_scene->GetNode("Points");
if (points->IsVisibleMesh()) points->SetVisibilityMesh(false);
else points->SetVisibilityMesh(true);
break;
}
default: return;
}
m_gl_canvas->Refresh(false);
}
void MainFrame::OnTimerUpdate(wxTimerEvent& event)
{
switch (event.GetId())
{
case ID_TIMER_TURNTABLE:
{
auto camera = m_scene->GetCamera();
const auto rotation = camera->GetTrackballOrientation();
camera->RotateTrackball(glm::vec2{0.0f, 0.0f}, glm::vec2{-0.0002f * m_tb_turntable_speed_slider->GetValue(), 0.0f});
m_scene->GetNode("Trackball X")->GetTransform().SetOrientation(rotation * glm::angleAxis(90.0f, glm::vec3{0.0f, 1.0f, 0.0f}));
m_scene->GetNode("Trackball Y")->GetTransform().SetOrientation(rotation * glm::angleAxis(90.0f, glm::vec3{1.0f, 0.0f, 0.0f}));
m_scene->GetNode("Trackball Z")->GetTransform().SetOrientation(rotation);
break;
}
case ID_TIMER_RESET_VIEWPORT:
{
m_counter += 0.02f;
if (m_counter >= 1.0f) m_reset_viewport_timer->Stop();
auto camera = m_scene->GetCamera();
const auto quat_x = glm::angleAxis(15.0f, glm::vec3{1, 0, 0});
const auto quat_y = glm::angleAxis(45.0f, glm::vec3{0, 1, 0});
const auto quat_z = glm::angleAxis(0.0f, glm::vec3{0, 0, 1});
const auto orientation_start = camera->GetTrackballOrientation();
const auto orientation_target = quat_x * quat_y * quat_z;
const auto position_start = camera->GetTrackballPosition();
const auto position_target = glm::vec3{0.0f, 0.0f, 0.0f};
const auto zoom_start = camera->GetTrackballZoom();
const auto zoom_target = 1.0f;
const auto zoom_mix = glm::lerp(zoom_start, zoom_target, m_counter);
const auto position_mix = glm::lerp(position_start, position_target, m_counter);
const auto orientation_mix = glm::shortMix(orientation_start, orientation_target, m_counter);
camera->SetTrackballZoom(zoom_mix);
camera->SetTrackballPosition(position_mix);
camera->SetTrackballOrientation(orientation_mix);
const auto rotation = camera->GetTrackballOrientation();
m_scene->GetNode("Trackball X")->GetTransform().SetOrientation(orientation_mix * glm::angleAxis(90.0f, glm::vec3{0.0f, 1.0f, 0.0f}));
m_scene->GetNode("Trackball Y")->GetTransform().SetOrientation(orientation_mix * glm::angleAxis(90.0f, glm::vec3{1.0f, 0.0f, 0.0f}));
m_scene->GetNode("Trackball Z")->GetTransform().SetOrientation(orientation_mix);
m_beginx = m_beginy = 0.0f;
break;
}
default: event.Skip();
}
m_gl_canvas->Refresh(false);
}
void MainFrame::OnExport(wxCommandEvent& event)
{
switch(event.GetId())
{
case ID_EXPORT_TRACKS:
{
SaveTrackFile();
break;
}
case ID_EXPORT_MATCHES:
{
SaveMatchFile();
break;
}
case ID_EXPORT_CMVS:
{
ExportToCMVS(m_path);
break;
}
case ID_EXPORT_BUNDLE_FILE:
{
SaveBundleFile(m_path);
break;
}
case ID_EXPORT_PLY_FILE:
{
SavePlyFile();
break;
}
case ID_EXPORT_MESHLAB_FILE:
{
SaveMeshLabFile();
break;
}
case ID_EXPORT_MAYA_FILE:
{
SaveMayaFile();
break;
}
default: event.Skip();
}
}
void MainFrame::OnSaveLog(wxCommandEvent& event)
{
const auto target = m_path + R"(\Log.txt)";
if (m_tc_log->SaveFile(target)) wxLogMessage("Log saved to %s", target);
}
void MainFrame::OnClearLog(wxCommandEvent& event)
{
m_tc_log->Clear();
}
void MainFrame::OnSelectDirectory(wxFileDirPickerEvent& event)
{
wxString filename, focalPx, res, path;
path = m_dir_picker->GetPath();
m_path = (path).ToStdString();
wxDir dir{path};
m_images.clear();
m_profile_manager.Reset();
m_cb_matches_left->Clear();
m_cb_matches_right->Clear();
m_window_image_preview->Refresh(true);
m_pane_matches_view->Refresh(true);
m_img_ctrl->ClearAll();
m_img_ctrl->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 60);
m_img_ctrl->InsertColumn(1, "Resolution", wxLIST_FORMAT_LEFT, 75);
m_img_ctrl->InsertColumn(2, "Focal", wxLIST_FORMAT_LEFT, 50);
m_img_ctrl->InsertColumn(3, "Features", wxLIST_FORMAT_LEFT, 60);
m_img_ctrl->InsertColumn(4, "k1", wxLIST_FORMAT_LEFT, 40);
m_img_ctrl->InsertColumn(5, "k2", wxLIST_FORMAT_LEFT, 40);
// Parse directory and process jpg images
bool found = dir.GetFirst(&filename, "*.jpg", wxDIR_FILES);
int index = 0;
while (found)
{
// Get focal from EXIF tags, convert to px-coordinates and add image if successful
if(AddImage(dir.FindFirst(path, filename).ToStdString(), filename.ToStdString()))
{
m_img_ctrl->InsertItem(index, filename);
m_cb_matches_left->Append(filename);
m_cb_matches_right->Append(filename);
}
// Get the next jpg in the directory
found = dir.GetNext(&filename);
index++;
}
// Display findings
if(m_images.size() > 0)
{
for (int i = 0; i < (int)m_images.size(); i++)
{
res.Printf("%i x %i", GetImageWidth(i), GetImageHeight(i));
focalPx.Printf("%.2f", GetFocalLength(i));
m_img_ctrl->SetItem(i, 1, res, -1);
m_img_ctrl->SetItem(i, 2, focalPx, -1);
}
m_has_images = true;
wxLogMessage("%s: %i images ready for reconstruction", path, m_images.size());
} else
{
wxLogMessage("No suitable images found in %s", path);
}
}
void MainFrame::OnReconstruct(wxCommandEvent& event)
{
// Detect features
DetectFeaturesAll();
// Match features
if (m_options.feature_type != 2) MatchAll();
else MatchAllAkaze();
// Compute structure from motion in another thread
if (CreateThread(wxTHREAD_DETACHED) != wxTHREAD_NO_ERROR)
{
wxLogError("Error: Could not create the worker thread!");
return;
}
if (GetThread()->Run() != wxTHREAD_NO_ERROR)
{
wxLogError("Error: Could not run the worker thread!");
return;
}
}
<|endoftext|> |
<commit_before>#include <StdAfx.h>
#include <Interpret/SmartView/AdditionalRenEntryIDs.h>
#include <Interpret/InterpretProp.h>
#include <Interpret/ExtraPropTags.h>
namespace smartview
{
#define PERISIST_SENTINEL 0
#define ELEMENT_SENTINEL 0
void AdditionalRenEntryIDs::Parse()
{
WORD wPersistDataCount = 0;
// Run through the parser once to count the number of PersistData structs
for (;;)
{
if (m_Parser.RemainingBytes() < 2 * sizeof(WORD)) break;
const auto wPersistID = m_Parser.GetBlock<WORD>();
const auto wDataElementSize = m_Parser.GetBlock<WORD>();
// Must have at least wDataElementSize bytes left to be a valid data element
if (m_Parser.RemainingBytes() < wDataElementSize.getData()) break;
m_Parser.Advance(wDataElementSize.getData());
wPersistDataCount++;
if (wPersistID.getData() == PERISIST_SENTINEL) break;
}
// Now we parse for real
m_Parser.Rewind();
if (wPersistDataCount && wPersistDataCount < _MaxEntriesSmall)
{
for (WORD iPersistElement = 0; iPersistElement < wPersistDataCount; iPersistElement++)
{
m_ppdPersistData.push_back(BinToPersistData());
}
}
ParseBlocks();
}
PersistData AdditionalRenEntryIDs::BinToPersistData()
{
PersistData persistData;
WORD wDataElementCount = 0;
persistData.wPersistID = m_Parser.GetBlock<WORD>();
persistData.wDataElementsSize = m_Parser.GetBlock<WORD>();
if (persistData.wPersistID.getData() != PERISIST_SENTINEL &&
m_Parser.RemainingBytes() >= persistData.wDataElementsSize.getData())
{
// Build a new m_Parser to preread and count our elements
// This new m_Parser will only contain as much space as suggested in wDataElementsSize
CBinaryParser DataElementParser(persistData.wDataElementsSize.getData(), m_Parser.GetCurrentAddress());
for (;;)
{
if (DataElementParser.RemainingBytes() < 2 * sizeof(WORD)) break;
const auto wElementID = DataElementParser.GetBlock<WORD>();
const auto wElementDataSize = DataElementParser.GetBlock<WORD>();
// Must have at least wElementDataSize bytes left to be a valid element data
if (DataElementParser.RemainingBytes() < wElementDataSize.getData()) break;
DataElementParser.Advance(wElementDataSize.getData());
wDataElementCount++;
if (wElementID.getData() == ELEMENT_SENTINEL) break;
}
}
if (wDataElementCount && wDataElementCount < _MaxEntriesSmall)
{
for (WORD iDataElement = 0; iDataElement < wDataElementCount; iDataElement++)
{
PersistElement persistElement;
persistElement.wElementID = m_Parser.GetBlock<WORD>();
persistElement.wElementDataSize = m_Parser.GetBlock<WORD>();
if (persistElement.wElementID.getData() == ELEMENT_SENTINEL) break;
// Since this is a word, the size will never be too large
persistElement.lpbElementData = m_Parser.GetBlockBYTES(persistElement.wElementDataSize.getData());
persistData.ppeDataElement.push_back(persistElement);
}
}
// We'll trust wDataElementsSize to dictate our record size.
// Count the 2 WORD size header fields too.
const auto cbRecordSize = persistData.wDataElementsSize.getData() + sizeof(WORD) * 2;
// Junk data remains - can't use GetRemainingData here since it would eat the whole buffer
if (m_Parser.GetCurrentOffset() < cbRecordSize)
{
persistData.JunkData = m_Parser.GetBlockBYTES(cbRecordSize - m_Parser.GetCurrentOffset());
}
return persistData;
}
void AdditionalRenEntryIDs::ParseBlocks()
{
addHeader(L"Additional Ren Entry IDs\r\n");
addHeader(strings::formatmessage(L"PersistDataCount = %1!d!", m_ppdPersistData.size()));
if (m_ppdPersistData.size())
{
for (WORD iPersistElement = 0; iPersistElement < m_ppdPersistData.size(); iPersistElement++)
{
addHeader(strings::formatmessage(L"\r\n\r\n"));
addHeader(strings::formatmessage(L"Persist Element %1!d!:\r\n", iPersistElement));
addBlock(
m_ppdPersistData[iPersistElement].wPersistID,
strings::formatmessage(
L"PersistID = 0x%1!04X! = %2!ws!\r\n",
m_ppdPersistData[iPersistElement].wPersistID.getData(),
interpretprop::InterpretFlags(
flagPersistID, m_ppdPersistData[iPersistElement].wPersistID.getData())
.c_str()));
addBlock(
m_ppdPersistData[iPersistElement].wDataElementsSize,
strings::formatmessage(
L"DataElementsSize = 0x%1!04X!",
m_ppdPersistData[iPersistElement].wDataElementsSize.getData()));
if (m_ppdPersistData[iPersistElement].ppeDataElement.size())
{
for (WORD iDataElement = 0; iDataElement < m_ppdPersistData[iPersistElement].ppeDataElement.size();
iDataElement++)
{
addHeader(strings::formatmessage(L"\r\nDataElement: %1!d!\r\n", iDataElement));
addBlock(
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementID,
strings::formatmessage(
L"\tElementID = 0x%1!04X! = %2!ws!\r\n",
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementID.getData(),
interpretprop::InterpretFlags(
flagElementID,
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementID.getData())
.c_str()));
addBlock(
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementDataSize,
strings::formatmessage(
L"\tElementDataSize = 0x%1!04X!\r\n",
m_ppdPersistData[iPersistElement]
.ppeDataElement[iDataElement]
.wElementDataSize.getData()));
addHeader(strings::formatmessage(L"\tElementData = "));
addBlockBytes(m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].lpbElementData);
}
}
addHeader(JunkDataToString(m_ppdPersistData[iPersistElement].JunkData.getData()));
}
}
}
}<commit_msg>add comment<commit_after>#include <StdAfx.h>
#include <Interpret/SmartView/AdditionalRenEntryIDs.h>
#include <Interpret/InterpretProp.h>
#include <Interpret/ExtraPropTags.h>
namespace smartview
{
#define PERISIST_SENTINEL 0
#define ELEMENT_SENTINEL 0
void AdditionalRenEntryIDs::Parse()
{
WORD wPersistDataCount = 0;
// Run through the parser once to count the number of PersistData structs
for (;;)
{
if (m_Parser.RemainingBytes() < 2 * sizeof(WORD)) break;
const auto wPersistID = m_Parser.GetBlock<WORD>();
const auto wDataElementSize = m_Parser.GetBlock<WORD>();
// Must have at least wDataElementSize bytes left to be a valid data element
if (m_Parser.RemainingBytes() < wDataElementSize.getData()) break;
m_Parser.Advance(wDataElementSize.getData());
wPersistDataCount++;
if (wPersistID.getData() == PERISIST_SENTINEL) break;
}
// Now we parse for real
m_Parser.Rewind();
if (wPersistDataCount && wPersistDataCount < _MaxEntriesSmall)
{
for (WORD iPersistElement = 0; iPersistElement < wPersistDataCount; iPersistElement++)
{
m_ppdPersistData.push_back(BinToPersistData());
}
}
ParseBlocks();
}
PersistData AdditionalRenEntryIDs::BinToPersistData()
{
PersistData persistData;
WORD wDataElementCount = 0;
persistData.wPersistID = m_Parser.GetBlock<WORD>();
persistData.wDataElementsSize = m_Parser.GetBlock<WORD>();
if (persistData.wPersistID.getData() != PERISIST_SENTINEL &&
m_Parser.RemainingBytes() >= persistData.wDataElementsSize.getData())
{
// Build a new m_Parser to preread and count our elements
// This new m_Parser will only contain as much space as suggested in wDataElementsSize
CBinaryParser DataElementParser(persistData.wDataElementsSize.getData(), m_Parser.GetCurrentAddress());
for (;;)
{
if (DataElementParser.RemainingBytes() < 2 * sizeof(WORD)) break;
const auto wElementID = DataElementParser.GetBlock<WORD>();
const auto wElementDataSize = DataElementParser.GetBlock<WORD>();
// Must have at least wElementDataSize bytes left to be a valid element data
if (DataElementParser.RemainingBytes() < wElementDataSize.getData()) break;
DataElementParser.Advance(wElementDataSize.getData());
wDataElementCount++;
if (wElementID.getData() == ELEMENT_SENTINEL) break;
}
}
if (wDataElementCount && wDataElementCount < _MaxEntriesSmall)
{
for (WORD iDataElement = 0; iDataElement < wDataElementCount; iDataElement++)
{
PersistElement persistElement;
persistElement.wElementID = m_Parser.GetBlock<WORD>();
persistElement.wElementDataSize = m_Parser.GetBlock<WORD>();
if (persistElement.wElementID.getData() == ELEMENT_SENTINEL) break;
// Since this is a word, the size will never be too large
persistElement.lpbElementData = m_Parser.GetBlockBYTES(persistElement.wElementDataSize.getData());
persistData.ppeDataElement.push_back(persistElement);
}
}
// We'll trust wDataElementsSize to dictate our record size.
// Count the 2 WORD size header fields too.
const auto cbRecordSize = persistData.wDataElementsSize.getData() + sizeof(WORD) * 2;
// Junk data remains - can't use GetRemainingData here since it would eat the whole buffer
if (m_Parser.GetCurrentOffset() < cbRecordSize)
{
persistData.JunkData = m_Parser.GetBlockBYTES(cbRecordSize - m_Parser.GetCurrentOffset());
}
return persistData;
}
void AdditionalRenEntryIDs::ParseBlocks()
{
addHeader(L"Additional Ren Entry IDs\r\n");
addHeader(strings::formatmessage(L"PersistDataCount = %1!d!", m_ppdPersistData.size()));
if (m_ppdPersistData.size())
{
for (WORD iPersistElement = 0; iPersistElement < m_ppdPersistData.size(); iPersistElement++)
{
addHeader(strings::formatmessage(L"\r\n\r\n"));
addHeader(strings::formatmessage(L"Persist Element %1!d!:\r\n", iPersistElement));
addBlock(
m_ppdPersistData[iPersistElement].wPersistID,
strings::formatmessage(
L"PersistID = 0x%1!04X! = %2!ws!\r\n",
m_ppdPersistData[iPersistElement].wPersistID.getData(),
interpretprop::InterpretFlags(
flagPersistID, m_ppdPersistData[iPersistElement].wPersistID.getData())
.c_str()));
addBlock(
m_ppdPersistData[iPersistElement].wDataElementsSize,
strings::formatmessage(
L"DataElementsSize = 0x%1!04X!",
m_ppdPersistData[iPersistElement].wDataElementsSize.getData()));
if (m_ppdPersistData[iPersistElement].ppeDataElement.size())
{
for (WORD iDataElement = 0; iDataElement < m_ppdPersistData[iPersistElement].ppeDataElement.size();
iDataElement++)
{
addHeader(strings::formatmessage(L"\r\nDataElement: %1!d!\r\n", iDataElement));
addBlock(
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementID,
strings::formatmessage(
L"\tElementID = 0x%1!04X! = %2!ws!\r\n",
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementID.getData(),
interpretprop::InterpretFlags(
flagElementID,
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementID.getData())
.c_str()));
addBlock(
m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].wElementDataSize,
strings::formatmessage(
L"\tElementDataSize = 0x%1!04X!\r\n",
m_ppdPersistData[iPersistElement]
.ppeDataElement[iDataElement]
.wElementDataSize.getData()));
addHeader(strings::formatmessage(L"\tElementData = "));
addBlockBytes(m_ppdPersistData[iPersistElement].ppeDataElement[iDataElement].lpbElementData);
}
}
// TODO: This should be a proper block
addHeader(JunkDataToString(m_ppdPersistData[iPersistElement].JunkData.getData()));
}
}
}
}<|endoftext|> |
<commit_before>/*
* libjingle
* Copyright 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/p2p/base/transportdescription.h"
#include "talk/p2p/base/constants.h"
namespace cricket {
bool StringToConnectionRole(const std::string& role_str, ConnectionRole* role) {
const char* const roles[] = {
CONNECTIONROLE_ACTIVE_STR,
CONNECTIONROLE_PASSIVE_STR,
CONNECTIONROLE_ACTPASS_STR,
CONNECTIONROLE_HOLDCONN_STR
};
for (size_t i = 0; i < ARRAY_SIZE(roles); ++i) {
if (stricmp(roles[i], role_str.c_str()) == 0) {
*role = static_cast<ConnectionRole>(CONNECTIONROLE_ACTIVE + i);
return true;
}
}
return false;
}
bool ConnectionRoleToString(const ConnectionRole& role, std::string* role_str) {
switch (role) {
case cricket::CONNECTIONROLE_ACTIVE:
*role_str = cricket::CONNECTIONROLE_ACTIVE_STR;
break;
case cricket::CONNECTIONROLE_ACTPASS:
*role_str = cricket::CONNECTIONROLE_ACTPASS_STR;
break;
case cricket::CONNECTIONROLE_PASSIVE:
*role_str = cricket::CONNECTIONROLE_PASSIVE_STR;
break;
case cricket::CONNECTIONROLE_HOLDCONN:
*role_str = cricket::CONNECTIONROLE_HOLDCONN_STR;
break;
default:
return false;
}
return true;
}
} // namespace cricket
<commit_msg>libjingle: use _stricmp instead of deprecated stricmp.<commit_after>/*
* libjingle
* Copyright 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/p2p/base/transportdescription.h"
#include "talk/p2p/base/constants.h"
#include "webrtc/base/stringutils.h"
namespace cricket {
bool StringToConnectionRole(const std::string& role_str, ConnectionRole* role) {
const char* const roles[] = {
CONNECTIONROLE_ACTIVE_STR,
CONNECTIONROLE_PASSIVE_STR,
CONNECTIONROLE_ACTPASS_STR,
CONNECTIONROLE_HOLDCONN_STR
};
for (size_t i = 0; i < ARRAY_SIZE(roles); ++i) {
if (_stricmp(roles[i], role_str.c_str()) == 0) {
*role = static_cast<ConnectionRole>(CONNECTIONROLE_ACTIVE + i);
return true;
}
}
return false;
}
bool ConnectionRoleToString(const ConnectionRole& role, std::string* role_str) {
switch (role) {
case cricket::CONNECTIONROLE_ACTIVE:
*role_str = cricket::CONNECTIONROLE_ACTIVE_STR;
break;
case cricket::CONNECTIONROLE_ACTPASS:
*role_str = cricket::CONNECTIONROLE_ACTPASS_STR;
break;
case cricket::CONNECTIONROLE_PASSIVE:
*role_str = cricket::CONNECTIONROLE_PASSIVE_STR;
break;
case cricket::CONNECTIONROLE_HOLDCONN:
*role_str = cricket::CONNECTIONROLE_HOLDCONN_STR;
break;
default:
return false;
}
return true;
}
} // namespace cricket
<|endoftext|> |
<commit_before>
// StackTrace.cpp
// Implements the functions to print current stack traces
#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
#include "../StackWalker.h"
#else
#include <execinfo.h>
#endif
void PrintStackTrace(void)
{
#ifdef _WIN32
// Reuse the StackWalker from the LeakFinder project already bound to MCS
// Define a subclass of the StackWalker that outputs everything to stdout
class PrintingStackWalker :
public StackWalker
{
virtual void OnOutput(LPCSTR szText) override
{
puts(szText);
}
} sw;
sw.ShowCallstack();
#else
// Use the backtrace() function to get and output the stackTrace:
// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
void * stackTrace[30];
size_t numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
#endif
}
<commit_msg>Fixed compiling on linux.<commit_after>
// StackTrace.cpp
// Implements the functions to print current stack traces
#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
#include "../StackWalker.h"
#else
#include <execinfo.h>
#include <unistd.h>
#endif
void PrintStackTrace(void)
{
#ifdef _WIN32
// Reuse the StackWalker from the LeakFinder project already bound to MCS
// Define a subclass of the StackWalker that outputs everything to stdout
class PrintingStackWalker :
public StackWalker
{
virtual void OnOutput(LPCSTR szText) override
{
puts(szText);
}
} sw;
sw.ShowCallstack();
#else
// Use the backtrace() function to get and output the stackTrace:
// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
void * stackTrace[30];
size_t numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
#endif
}
<|endoftext|> |
<commit_before>/* Twofold-Qt
* (C) Copyright 2014 HicknHack Software GmbH
*
* The original code can be found at:
* https://github.com/hicknhack-software/Twofold-Qt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Engine.h"
#include "Twofold/intern/QtScriptTargetBuilderApi.h"
#include "Twofold/intern/QStringHelper.h"
#include "Twofold/intern/find_last.h"
#include <QScriptEngine>
#include <vector>
namespace Twofold {
using namespace intern;
namespace {
BacktraceFilePositionList generateExceptionCallerStack(const PreparedTemplate &preparedTemplate, const QStringList &backtrace)
{
BacktraceFilePositionList callerStack;
for (const auto& traceLine : backtrace) {
// traceline format: "<function>() at <line>"
auto lineBegin = traceLine.begin();
const auto end = traceLine.end();
lineBegin = find_last(lineBegin, end, QChar(' '));
const auto lineString = toQString(lineBegin, end);
auto functionEnd = std::find(traceLine.begin(), end, QChar('('));
const auto functionString = toQString(traceLine.begin(), functionEnd);
bool convertSuccesful = false;
const int line = lineString.toInt(&convertSuccesful);
const int column = 1;
if (convertSuccesful && (line > 0)) {
const auto position = SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column});
if (callerStack.empty() || (callerStack.back() != position)) {
callerStack.push_back({functionString, position});
}
}
}
return callerStack;
}
} // namespace
class Engine::Private
{
public:
Private(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader)
: m_messageHandler(messageHandler)
, m_textLoader(textLoader)
{
}
Target execPrepared(const PreparedTemplate &preparedTemplate, const QVariantHash &inputs)
{
QtScriptTargetBuilderApi scriptTargetBuilder(preparedTemplate.originPositions);
defineInputs(inputs);
defineTemplateApi(scriptTargetBuilder);
auto resultValue = m_scriptEngine.evaluate(preparedTemplate.javascript);
if (m_scriptEngine.hasUncaughtException()) {
showException(resultValue, preparedTemplate);
}
undefineTemplateApi();
undefineInputs(inputs);
const auto sourceMapText = scriptTargetBuilder.build();
return { sourceMapText.sourceMap, sourceMapText.text };
}
void showSyntaxError(QScriptSyntaxCheckResult checkResult, const PreparedTemplate &preparedTemplate)
{
const int line = checkResult.errorLineNumber();
const int column = checkResult.errorColumnNumber();
BacktraceFilePositionList position {{ QString(), SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}) }};
const QString text = "Syntax Error: " + checkResult.errorMessage();
m_messageHandler->javaScriptMessage(MessageType::Error, position, text);
}
PreparedTemplateBuilder createPreparedBuilder() {
return { m_messageHandler, m_textLoader };
}
private:
void showException(QScriptValue resultValue, const PreparedTemplate &preparedTemplate)
{
const QStringList backtrace = m_scriptEngine.uncaughtExceptionBacktrace();
auto positionStack = generateExceptionCallerStack(preparedTemplate, backtrace);
const int line = m_scriptEngine.uncaughtExceptionLineNumber();
const int column = 1; // TODO: use agent and stack!
positionStack.insert(positionStack.begin(), {QString(), SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column})});
const QString text = "Uncaught Exception: " + resultValue.toString();
m_messageHandler->javaScriptMessage(MessageType::Error, positionStack, text);
}
void defineTemplateApi(QtScriptTargetBuilderApi &templateApi)
{
QScriptValue global = m_scriptEngine.globalObject();
global.setProperty("_template", m_scriptEngine.newQObject(&templateApi));
}
void undefineTemplateApi()
{
QScriptValue global = m_scriptEngine.globalObject();
global.setProperty("_template", m_scriptEngine.undefinedValue());
}
void defineInputs(const QVariantHash &inputs)
{
QScriptValue global = m_scriptEngine.globalObject();
for (auto key : inputs.keys()) {
global.setProperty( key, m_scriptEngine.toScriptValue(inputs[key]) );
}
}
void undefineInputs(const QVariantHash &inputs)
{
QScriptValue global = m_scriptEngine.globalObject();
for (auto key : inputs.keys()) {
global.setProperty(key, m_scriptEngine.undefinedValue());
}
}
MessageHandlerPtr m_messageHandler;
TextLoaderPtr m_textLoader;
QScriptEngine m_scriptEngine;
};
Engine::Engine(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader)
: m_private(new Private(messageHandler, textLoader))
{
}
Engine::Engine(TextLoaderPtr textLoader, MessageHandlerPtr messageHandler)
: Engine(messageHandler, textLoader)
{
}
void Engine::showTemplateSyntaxErrors(const PreparedTemplate &preparedTemplate) const
{
auto checkResult = QScriptEngine::checkSyntax(preparedTemplate.javascript);
if (checkResult.state() == QScriptSyntaxCheckResult::Error)
m_private->showSyntaxError(checkResult, preparedTemplate);
}
Target Engine::exec(const PreparedTemplate &preparedTemplate, const QVariantHash &inputs)
{
return m_private->execPrepared(preparedTemplate, inputs);
}
PreparedTemplate Engine::prepare(const QString &templateName) const
{
auto prepared = m_private->createPreparedBuilder().build(templateName);
this->showTemplateSyntaxErrors(prepared);
return prepared;
}
Target Engine::execTemplateName(const QString &templateName, const QVariantHash &inputs)
{
auto prepared = this->prepare(templateName);
return this->exec(prepared, inputs);
}
void Engine::PrivateDeleter::operator()(Engine::Private *p) const
{
delete p;
}
} // namespace Twofold
<commit_msg>* minor refactoring: moved variable definitions to correct place<commit_after>/* Twofold-Qt
* (C) Copyright 2014 HicknHack Software GmbH
*
* The original code can be found at:
* https://github.com/hicknhack-software/Twofold-Qt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Engine.h"
#include "Twofold/intern/QtScriptTargetBuilderApi.h"
#include "Twofold/intern/QStringHelper.h"
#include "Twofold/intern/find_last.h"
#include <QScriptEngine>
#include <vector>
namespace Twofold {
using namespace intern;
namespace {
BacktraceFilePositionList generateExceptionCallerStack(const PreparedTemplate &preparedTemplate, const QStringList &backtrace)
{
BacktraceFilePositionList callerStack;
for (const auto& traceLine : backtrace) {
// traceline format: "<function>() at <line>"
auto lineBegin = traceLine.begin();
const auto end = traceLine.end();
lineBegin = find_last(lineBegin, end, QChar(' '));
const auto lineString = toQString(lineBegin, end);
bool convertSuccesful = false;
const int line = lineString.toInt(&convertSuccesful);
const int column = 1;
if (convertSuccesful && (line > 0)) {
const auto position = SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column});
if (callerStack.empty() || (callerStack.back() != position)) {
const auto functionEnd = std::find(traceLine.begin(), end, QChar('('));
const auto functionString = toQString(traceLine.begin(), functionEnd);
callerStack.push_back({functionString, position});
}
}
}
return callerStack;
}
} // namespace
class Engine::Private
{
public:
Private(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader)
: m_messageHandler(messageHandler)
, m_textLoader(textLoader)
{
}
Target execPrepared(const PreparedTemplate &preparedTemplate, const QVariantHash &inputs)
{
QtScriptTargetBuilderApi scriptTargetBuilder(preparedTemplate.originPositions);
defineInputs(inputs);
defineTemplateApi(scriptTargetBuilder);
auto resultValue = m_scriptEngine.evaluate(preparedTemplate.javascript);
if (m_scriptEngine.hasUncaughtException()) {
showException(resultValue, preparedTemplate);
}
undefineTemplateApi();
undefineInputs(inputs);
const auto sourceMapText = scriptTargetBuilder.build();
return { sourceMapText.sourceMap, sourceMapText.text };
}
void showSyntaxError(QScriptSyntaxCheckResult checkResult, const PreparedTemplate &preparedTemplate)
{
const int line = checkResult.errorLineNumber();
const int column = checkResult.errorColumnNumber();
BacktraceFilePositionList position {{ QString(), SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column}) }};
const QString text = "Syntax Error: " + checkResult.errorMessage();
m_messageHandler->javaScriptMessage(MessageType::Error, position, text);
}
PreparedTemplateBuilder createPreparedBuilder() {
return { m_messageHandler, m_textLoader };
}
private:
void showException(QScriptValue resultValue, const PreparedTemplate &preparedTemplate)
{
const QStringList backtrace = m_scriptEngine.uncaughtExceptionBacktrace();
auto positionStack = generateExceptionCallerStack(preparedTemplate, backtrace);
const int line = m_scriptEngine.uncaughtExceptionLineNumber();
const int column = 1; // TODO: use agent and stack!
positionStack.insert(positionStack.begin(), {QString(), SourceMap::getOriginalPositionFromGenerated(preparedTemplate.sourceMap, {line, column})});
const QString text = "Uncaught Exception: " + resultValue.toString();
m_messageHandler->javaScriptMessage(MessageType::Error, positionStack, text);
}
void defineTemplateApi(QtScriptTargetBuilderApi &templateApi)
{
QScriptValue global = m_scriptEngine.globalObject();
global.setProperty("_template", m_scriptEngine.newQObject(&templateApi));
}
void undefineTemplateApi()
{
QScriptValue global = m_scriptEngine.globalObject();
global.setProperty("_template", m_scriptEngine.undefinedValue());
}
void defineInputs(const QVariantHash &inputs)
{
QScriptValue global = m_scriptEngine.globalObject();
for (auto key : inputs.keys()) {
global.setProperty( key, m_scriptEngine.toScriptValue(inputs[key]) );
}
}
void undefineInputs(const QVariantHash &inputs)
{
QScriptValue global = m_scriptEngine.globalObject();
for (auto key : inputs.keys()) {
global.setProperty(key, m_scriptEngine.undefinedValue());
}
}
MessageHandlerPtr m_messageHandler;
TextLoaderPtr m_textLoader;
QScriptEngine m_scriptEngine;
};
Engine::Engine(MessageHandlerPtr messageHandler, TextLoaderPtr textLoader)
: m_private(new Private(messageHandler, textLoader))
{
}
Engine::Engine(TextLoaderPtr textLoader, MessageHandlerPtr messageHandler)
: Engine(messageHandler, textLoader)
{
}
void Engine::showTemplateSyntaxErrors(const PreparedTemplate &preparedTemplate) const
{
auto checkResult = QScriptEngine::checkSyntax(preparedTemplate.javascript);
if (checkResult.state() == QScriptSyntaxCheckResult::Error)
m_private->showSyntaxError(checkResult, preparedTemplate);
}
Target Engine::exec(const PreparedTemplate &preparedTemplate, const QVariantHash &inputs)
{
return m_private->execPrepared(preparedTemplate, inputs);
}
PreparedTemplate Engine::prepare(const QString &templateName) const
{
auto prepared = m_private->createPreparedBuilder().build(templateName);
this->showTemplateSyntaxErrors(prepared);
return prepared;
}
Target Engine::execTemplateName(const QString &templateName, const QVariantHash &inputs)
{
auto prepared = this->prepare(templateName);
return this->exec(prepared, inputs);
}
void Engine::PrivateDeleter::operator()(Engine::Private *p) const
{
delete p;
}
} // namespace Twofold
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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.
**
***********************************************************************************************************************/
#include "CompositeNode.h"
#include "../../ModelException.h"
#include "../../commands/CompositeNodeChangeChild.h"
#include "../../persistence/PersistentStore.h"
namespace Model {
DEFINE_TYPE_ID_DERIVED(CompositeNode, "CompositeNode", )
CompositeIndex CompositeNode::commentIndex =
addAttributeToInitialRegistrationList_(commentIndex, "comment", "Node", false, true, true);
int CompositeNode::nextExtensionId_ = 0;
void CompositeNode::initType()
{
Node::registerNodeType("CompositeNode",
[](Node* parent) -> Node* { return CompositeNode::createDefaultInstance(parent);},
[](Node *parent, PersistentStore &store, bool partialLoadHint) -> Node*
{ return new CompositeNode{parent, store, partialLoadHint};});
for (int i = 0; i<attributesToRegisterAtInitialization_().size(); ++i)
attributesToRegisterAtInitialization_().at(i).first =
registerNewAttribute(attributesToRegisterAtInitialization_().at(i).second);
}
CompositeNode* CompositeNode::createDefaultInstance( Node* parent)
{
return new CompositeNode{parent};
}
AttributeChain& CompositeNode::topLevelMeta()
{
return meta_;
}
CompositeNode::CompositeNode(Node *parent) :
Super{parent}, meta_{CompositeNode::getMetaData()}
{
throw ModelException{"Constructing an CompositeNode class directly, without specifying meta data"};
}
CompositeNode::CompositeNode(Node *parent, PersistentStore &, bool) :
Super{parent}, meta_{CompositeNode::getMetaData()}
{
throw ModelException{"Constructing an CompositeNode class directly, without specifying meta data"};
}
CompositeNode::CompositeNode(const CompositeNode& other)
: Super{other}, meta_{other.meta_}, subnodes_{meta_.numLevels()}
{
Q_ASSERT(subnodes_.size() == other.subnodes_.size());
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
subnodes_[level] = QVector<Node*>{currentLevel->size(), nullptr};
for (int i = 0; i < currentLevel->size(); ++i)
if ( auto node = other.subnodes_[level][i] )
{
auto cloned = node->clone();
subnodes_[level][i] = cloned;
cloned->setParent(this);
}
}
}
CompositeNode* CompositeNode::clone() const { return new CompositeNode{*this}; }
CompositeNode::CompositeNode(Node *parent, AttributeChain& metaData) :
Super{parent}, meta_{metaData}, subnodes_{meta_.numLevels()}
{
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
subnodes_[level] = QVector<Node*>{currentLevel->size(), nullptr};
for (int i = 0; i < currentLevel->size(); ++i)
if ( !(*currentLevel)[i].optional() )
subnodes_[level][i] = Node::createNewNode((*currentLevel)[i].type(), this);
}
}
CompositeNode::CompositeNode(Node *parent, PersistentStore &store, bool, AttributeChain& metaData) :
Super{parent}, meta_{metaData}, subnodes_{meta_.numLevels()}
{
QSet<QString> partial;
for (int level = 0; level < meta_.numLevels(); ++level)
{
subnodes_[level] = QVector<Node*>{meta_.level(level)->size(), nullptr};
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( (*currentLevel)[i].partial() ) partial.insert( (*currentLevel)[i].name() );
}
QList<LoadedNode> children = store.loadAllSubNodes(this, partial);
for (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)
{
CompositeIndex index = meta_.indexForAttribute(ln->name);
if ( !index.isValid() ) throw ModelException{"Node has attribute "
+ ln->name + " in persistent store, but this attribute is not registered"};
auto attribute = meta_.attribute(index);
Q_ASSERT(ln->node->isSubtypeOf(attribute.type()));
// Skip loading partial optional children.
if (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())
{
subnodes_[index.level()][index.index()] = ln->node;
ln->node->setParent(this);
}
}
checkOrCreateMandatoryAttributes(false);
}
CompositeNode::~CompositeNode()
{
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if ( subnodes_[level][i] ) SAFE_DELETE( subnodes_[level][i] );
}
AttributeChain& CompositeNode::getMetaData()
{
static AttributeChain descriptions{"CompositeNode"};
return descriptions;
}
CompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const QString &attributeName,
const QString &attributeType, bool canBePartiallyLoaded, bool isOptional, bool isPersistent)
{
return registerNewAttribute(metaData, Attribute{attributeName, attributeType,
isOptional, canBePartiallyLoaded, isPersistent});
}
CompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const Attribute& attribute)
{
if ( metaData.hasAttribute(attribute.name()) )
throw ModelException{"Trying to register new attribute " + attribute.name() + " but this name already exists"};
metaData.append(attribute);
return CompositeIndex{metaData.numLevels() - 1, metaData.size() - 1};
}
CompositeIndex CompositeNode::registerNewAttribute(const Attribute& attribute)
{
return registerNewAttribute(getMetaData(), attribute);
}
CompositeIndex CompositeNode::addAttributeToInitialRegistrationList_ (CompositeIndex& index,
const QString &attributeName, const QString &attributeType, bool canBePartiallyLoaded, bool isOptional,
bool isPersistent)
{
attributesToRegisterAtInitialization_().append(QPair< CompositeIndex&, Attribute>{index,
Attribute{attributeName, attributeType, isOptional, canBePartiallyLoaded, isPersistent}});
return CompositeIndex{};
}
QList<QPair< CompositeIndex&, Attribute> >& CompositeNode::attributesToRegisterAtInitialization_()
{
static QList<QPair< CompositeIndex&, Attribute> > a;
return a;
}
void CompositeNode::set(const CompositeIndex &attributeIndex, Node* node)
{
Q_ASSERT( attributeIndex.isValid() );
Q_ASSERT( attributeIndex.level() < subnodes_.size());
Q_ASSERT( attributeIndex.index() < subnodes_[attributeIndex.level()].size());
auto attribute = meta_.attribute(attributeIndex);
Q_ASSERT( node || attribute.optional());
Q_ASSERT( !node || node->isSubtypeOf(attribute.type()));
execute(new CompositeNodeChangeChild{this, node, attributeIndex, &subnodes_});
}
Node* CompositeNode::get(const QString &attributeName) const
{
CompositeIndex index = meta_.indexForAttribute(attributeName);
if ( index.isValid() ) return subnodes_[index.level()][index.index()];
return nullptr;
}
CompositeIndex CompositeNode::indexOf(Node* node) const
{
if (node)
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if (subnodes_[level][i] == node)
return CompositeIndex{level, i};
return CompositeIndex{};
}
CompositeIndex CompositeNode::indexOf(const QString& nodeName) const
{
return meta_.indexForAttribute(nodeName);
}
QList<Node*> CompositeNode::children() const
{
QList<Node*> result;
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if (subnodes_[level][i]) result << subnodes_[level][i];
return result;
}
bool CompositeNode::replaceChild(Node* child, Node* replacement)
{
if (!child || !replacement) return false;
CompositeIndex index = indexOf(child);
Q_ASSERT(index.isValid());
Q_ASSERT( !replacement || replacement->isSubtypeOf(meta_.attribute(index).type()));
execute(new CompositeNodeChangeChild{this, replacement, index, &subnodes_});
return true;
}
bool CompositeNode::hasAttribute(const QString& attributeName)
{
return meta_.hasAttribute(attributeName);
}
QList< QPair<QString, Node*> > CompositeNode::getAllAttributes(bool includeNullValues)
{
QList< QPair<QString, Node*> > result;
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( subnodes_[level][i] || includeNullValues )
result.append(QPair<QString, Node*>{(*currentLevel)[i].name(), subnodes_[level][i]});
}
return result;
}
void CompositeNode::save(PersistentStore &store) const
{
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( subnodes_[level][i] != nullptr && currentLevel->at(i).persistent() )
store.saveNode(subnodes_[level][i], currentLevel->at(i).name());
}
}
void CompositeNode::load(PersistentStore &store)
{
if (store.currentNodeType() != typeName())
throw ModelException{"Trying to load a CompositeNode from an incompatible node type "
+ store.currentNodeType()};
removeAllNodes();
QSet<QString> partial;
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( currentLevel->at(i).partial() )
partial.insert(currentLevel->at(i).name());
}
QList<LoadedNode> children = store.loadAllSubNodes(this, partial);
for (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)
{
CompositeIndex index = meta_.indexForAttribute(ln->name);
if ( !index.isValid() )
throw ModelException{"Node has attribute "
+ ln->name + " in persistent store, but this attribute is not registered"};
auto attribute = meta_.attribute(index);
Q_ASSERT(ln->node->isSubtypeOf(attribute.type()));
// Skip loading partial optional children.
if (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())
execute(new CompositeNodeChangeChild{this, ln->node, {index.level(), index.index()}, &subnodes_});
}
checkOrCreateMandatoryAttributes(true);
}
void CompositeNode::removeAllNodes()
{
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if ( subnodes_[level][i] )
execute(new CompositeNodeChangeChild{this, nullptr, CompositeIndex{level, i}, &subnodes_});
}
void CompositeNode::checkOrCreateMandatoryAttributes(bool useUndoableAction)
{
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( subnodes_[level][i] == nullptr && (*currentLevel)[i].optional() == false )
{
auto nodeType = (*currentLevel)[i].type();
if (nodeType.startsWith("TypedListOf") || nodeType.endsWith("List"))
{
auto newNode = Node::createNewNode(nodeType);
if (useUndoableAction)
execute(new CompositeNodeChangeChild{this, newNode, {level, i}, &subnodes_});
else {
subnodes_[level][i] = newNode;
newNode->setParent(this);
}
}
else
throw ModelException{"An CompositeNode of type '" + meta_.typeName()
+ "' has an uninitialized mandatory attribute '"
+ (*currentLevel)[i].name() +"'"};
}
}
}
void CompositeNode::remove(const CompositeIndex &attributeIndex)
{
Q_ASSERT(attributeIndex.isValid());
if ( meta_.attribute(attributeIndex).optional() )
execute(new CompositeNodeChangeChild{ this, nullptr, attributeIndex, &subnodes_});
else
execute(new CompositeNodeChangeChild{ this, Node::createNewNode(meta_.attribute(attributeIndex).type(), nullptr),
attributeIndex, &subnodes_});
}
void CompositeNode::remove(Node* childNode)
{
Q_ASSERT(childNode);
remove(indexOf(childNode));
}
void CompositeNode::remove(QString childNodeName)
{
remove(indexOf(childNodeName));
}
Node* CompositeNode::setDefault(QString nodeName)
{
auto attributeIndex = indexOf(nodeName);
auto newNode = Node::createNewNode(meta_.attribute(attributeIndex).type());
set(attributeIndex, newNode);
return newNode;
}
}
<commit_msg>Assert that all children of CompositeNode have unique names<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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.
**
***********************************************************************************************************************/
#include "CompositeNode.h"
#include "../../ModelException.h"
#include "../../commands/CompositeNodeChangeChild.h"
#include "../../persistence/PersistentStore.h"
namespace Model {
DEFINE_TYPE_ID_DERIVED(CompositeNode, "CompositeNode", )
CompositeIndex CompositeNode::commentIndex =
addAttributeToInitialRegistrationList_(commentIndex, "comment", "Node", false, true, true);
int CompositeNode::nextExtensionId_ = 0;
void CompositeNode::initType()
{
Node::registerNodeType("CompositeNode",
[](Node* parent) -> Node* { return CompositeNode::createDefaultInstance(parent);},
[](Node *parent, PersistentStore &store, bool partialLoadHint) -> Node*
{ return new CompositeNode{parent, store, partialLoadHint};});
for (int i = 0; i<attributesToRegisterAtInitialization_().size(); ++i)
attributesToRegisterAtInitialization_().at(i).first =
registerNewAttribute(attributesToRegisterAtInitialization_().at(i).second);
}
CompositeNode* CompositeNode::createDefaultInstance( Node* parent)
{
return new CompositeNode{parent};
}
AttributeChain& CompositeNode::topLevelMeta()
{
return meta_;
}
CompositeNode::CompositeNode(Node *parent) :
Super{parent}, meta_{CompositeNode::getMetaData()}
{
throw ModelException{"Constructing an CompositeNode class directly, without specifying meta data"};
}
CompositeNode::CompositeNode(Node *parent, PersistentStore &, bool) :
Super{parent}, meta_{CompositeNode::getMetaData()}
{
throw ModelException{"Constructing an CompositeNode class directly, without specifying meta data"};
}
CompositeNode::CompositeNode(const CompositeNode& other)
: Super{other}, meta_{other.meta_}, subnodes_{meta_.numLevels()}
{
Q_ASSERT(subnodes_.size() == other.subnodes_.size());
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
subnodes_[level] = QVector<Node*>{currentLevel->size(), nullptr};
for (int i = 0; i < currentLevel->size(); ++i)
if ( auto node = other.subnodes_[level][i] )
{
auto cloned = node->clone();
subnodes_[level][i] = cloned;
cloned->setParent(this);
}
}
}
CompositeNode* CompositeNode::clone() const { return new CompositeNode{*this}; }
CompositeNode::CompositeNode(Node *parent, AttributeChain& metaData) :
Super{parent}, meta_{metaData}, subnodes_{meta_.numLevels()}
{
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
subnodes_[level] = QVector<Node*>{currentLevel->size(), nullptr};
for (int i = 0; i < currentLevel->size(); ++i)
if ( !(*currentLevel)[i].optional() )
subnodes_[level][i] = Node::createNewNode((*currentLevel)[i].type(), this);
}
}
CompositeNode::CompositeNode(Node *parent, PersistentStore &store, bool, AttributeChain& metaData) :
Super{parent}, meta_{metaData}, subnodes_{meta_.numLevels()}
{
QSet<QString> partial;
for (int level = 0; level < meta_.numLevels(); ++level)
{
subnodes_[level] = QVector<Node*>{meta_.level(level)->size(), nullptr};
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( (*currentLevel)[i].partial() ) partial.insert( (*currentLevel)[i].name() );
}
QList<LoadedNode> children = store.loadAllSubNodes(this, partial);
for (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)
{
CompositeIndex index = meta_.indexForAttribute(ln->name);
if ( !index.isValid() ) throw ModelException{"Node has attribute "
+ ln->name + " in persistent store, but this attribute is not registered"};
auto attribute = meta_.attribute(index);
Q_ASSERT(ln->node->isSubtypeOf(attribute.type()));
// Skip loading partial optional children.
if (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())
{
// No two child attributes may have the same name.
Q_ASSERT(subnodes_[index.level()][index.index()] == nullptr);
subnodes_[index.level()][index.index()] = ln->node;
ln->node->setParent(this);
}
}
checkOrCreateMandatoryAttributes(false);
}
CompositeNode::~CompositeNode()
{
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if ( subnodes_[level][i] ) SAFE_DELETE( subnodes_[level][i] );
}
AttributeChain& CompositeNode::getMetaData()
{
static AttributeChain descriptions{"CompositeNode"};
return descriptions;
}
CompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const QString &attributeName,
const QString &attributeType, bool canBePartiallyLoaded, bool isOptional, bool isPersistent)
{
return registerNewAttribute(metaData, Attribute{attributeName, attributeType,
isOptional, canBePartiallyLoaded, isPersistent});
}
CompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const Attribute& attribute)
{
if ( metaData.hasAttribute(attribute.name()) )
throw ModelException{"Trying to register new attribute " + attribute.name() + " but this name already exists"};
metaData.append(attribute);
return CompositeIndex{metaData.numLevels() - 1, metaData.size() - 1};
}
CompositeIndex CompositeNode::registerNewAttribute(const Attribute& attribute)
{
return registerNewAttribute(getMetaData(), attribute);
}
CompositeIndex CompositeNode::addAttributeToInitialRegistrationList_ (CompositeIndex& index,
const QString &attributeName, const QString &attributeType, bool canBePartiallyLoaded, bool isOptional,
bool isPersistent)
{
attributesToRegisterAtInitialization_().append(QPair< CompositeIndex&, Attribute>{index,
Attribute{attributeName, attributeType, isOptional, canBePartiallyLoaded, isPersistent}});
return CompositeIndex{};
}
QList<QPair< CompositeIndex&, Attribute> >& CompositeNode::attributesToRegisterAtInitialization_()
{
static QList<QPair< CompositeIndex&, Attribute> > a;
return a;
}
void CompositeNode::set(const CompositeIndex &attributeIndex, Node* node)
{
Q_ASSERT( attributeIndex.isValid() );
Q_ASSERT( attributeIndex.level() < subnodes_.size());
Q_ASSERT( attributeIndex.index() < subnodes_[attributeIndex.level()].size());
auto attribute = meta_.attribute(attributeIndex);
Q_ASSERT( node || attribute.optional());
Q_ASSERT( !node || node->isSubtypeOf(attribute.type()));
execute(new CompositeNodeChangeChild{this, node, attributeIndex, &subnodes_});
}
Node* CompositeNode::get(const QString &attributeName) const
{
CompositeIndex index = meta_.indexForAttribute(attributeName);
if ( index.isValid() ) return subnodes_[index.level()][index.index()];
return nullptr;
}
CompositeIndex CompositeNode::indexOf(Node* node) const
{
if (node)
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if (subnodes_[level][i] == node)
return CompositeIndex{level, i};
return CompositeIndex{};
}
CompositeIndex CompositeNode::indexOf(const QString& nodeName) const
{
return meta_.indexForAttribute(nodeName);
}
QList<Node*> CompositeNode::children() const
{
QList<Node*> result;
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if (subnodes_[level][i]) result << subnodes_[level][i];
return result;
}
bool CompositeNode::replaceChild(Node* child, Node* replacement)
{
if (!child || !replacement) return false;
CompositeIndex index = indexOf(child);
Q_ASSERT(index.isValid());
Q_ASSERT( !replacement || replacement->isSubtypeOf(meta_.attribute(index).type()));
execute(new CompositeNodeChangeChild{this, replacement, index, &subnodes_});
return true;
}
bool CompositeNode::hasAttribute(const QString& attributeName)
{
return meta_.hasAttribute(attributeName);
}
QList< QPair<QString, Node*> > CompositeNode::getAllAttributes(bool includeNullValues)
{
QList< QPair<QString, Node*> > result;
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( subnodes_[level][i] || includeNullValues )
result.append(QPair<QString, Node*>{(*currentLevel)[i].name(), subnodes_[level][i]});
}
return result;
}
void CompositeNode::save(PersistentStore &store) const
{
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( subnodes_[level][i] != nullptr && currentLevel->at(i).persistent() )
store.saveNode(subnodes_[level][i], currentLevel->at(i).name());
}
}
void CompositeNode::load(PersistentStore &store)
{
if (store.currentNodeType() != typeName())
throw ModelException{"Trying to load a CompositeNode from an incompatible node type "
+ store.currentNodeType()};
removeAllNodes();
QSet<QString> partial;
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( currentLevel->at(i).partial() )
partial.insert(currentLevel->at(i).name());
}
QList<LoadedNode> children = store.loadAllSubNodes(this, partial);
for (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)
{
CompositeIndex index = meta_.indexForAttribute(ln->name);
if ( !index.isValid() )
throw ModelException{"Node has attribute "
+ ln->name + " in persistent store, but this attribute is not registered"};
auto attribute = meta_.attribute(index);
Q_ASSERT(ln->node->isSubtypeOf(attribute.type()));
// Skip loading partial optional children.
if (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())
execute(new CompositeNodeChangeChild{this, ln->node, {index.level(), index.index()}, &subnodes_});
}
checkOrCreateMandatoryAttributes(true);
}
void CompositeNode::removeAllNodes()
{
for (int level = 0; level < subnodes_.size(); ++level)
for (int i = 0; i < subnodes_[level].size(); ++i)
if ( subnodes_[level][i] )
execute(new CompositeNodeChangeChild{this, nullptr, CompositeIndex{level, i}, &subnodes_});
}
void CompositeNode::checkOrCreateMandatoryAttributes(bool useUndoableAction)
{
for (int level = 0; level < meta_.numLevels(); ++level)
{
AttributeChain* currentLevel = meta_.level(level);
for (int i = 0; i < currentLevel->size(); ++i)
if ( subnodes_[level][i] == nullptr && (*currentLevel)[i].optional() == false )
{
auto nodeType = (*currentLevel)[i].type();
if (nodeType.startsWith("TypedListOf") || nodeType.endsWith("List"))
{
auto newNode = Node::createNewNode(nodeType);
if (useUndoableAction)
execute(new CompositeNodeChangeChild{this, newNode, {level, i}, &subnodes_});
else {
subnodes_[level][i] = newNode;
newNode->setParent(this);
}
}
else
throw ModelException{"An CompositeNode of type '" + meta_.typeName()
+ "' has an uninitialized mandatory attribute '"
+ (*currentLevel)[i].name() +"'"};
}
}
}
void CompositeNode::remove(const CompositeIndex &attributeIndex)
{
Q_ASSERT(attributeIndex.isValid());
if ( meta_.attribute(attributeIndex).optional() )
execute(new CompositeNodeChangeChild{ this, nullptr, attributeIndex, &subnodes_});
else
execute(new CompositeNodeChangeChild{ this, Node::createNewNode(meta_.attribute(attributeIndex).type(), nullptr),
attributeIndex, &subnodes_});
}
void CompositeNode::remove(Node* childNode)
{
Q_ASSERT(childNode);
remove(indexOf(childNode));
}
void CompositeNode::remove(QString childNodeName)
{
remove(indexOf(childNodeName));
}
Node* CompositeNode::setDefault(QString nodeName)
{
auto attributeIndex = indexOf(nodeName);
auto newNode = Node::createNewNode(meta_.attribute(attributeIndex).type());
set(attributeIndex, newNode);
return newNode;
}
}
<|endoftext|> |
<commit_before>//
// Copyright "Renga Software" LLC, 2016. All rights reserved.
//
// "Renga Software" LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// "Renga Software" LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
#include "stdafx.h"
#include "RengaPropertyController.h"
#include "COMUtils.h"
#include <qtpropertybrowser.h>
RengaPropertyController::RengaPropertyController(
Renga::IApplicationPtr pRenga,
PropertyContainerAccess propertiesAccess)
: m_pRenga(pRenga),
m_propertiesAccess(propertiesAccess)
{
}
void RengaPropertyController::onDoublePropertyChanged(QtProperty* pQtProperty, const QString& newValue)
{
if (newValue.isEmpty())
resetPropertyValue(pQtProperty); // will reset the attribute value
else
{
bool ok = false;
double newDoubleValue = QLocale::system().toDouble(newValue, &ok);
if (ok)
changePropertyValue(pQtProperty, newDoubleValue);
}
}
void RengaPropertyController::onStringPropertyChanged(QtProperty* pQtProperty, const QString& newValue)
{
if (newValue.isEmpty())
resetPropertyValue(pQtProperty); // will reset the attribute value
else
changePropertyValue(pQtProperty, newValue);
}
void RengaPropertyController::onIntPropertyChanged(QtProperty* pQtProperty, int value)
{
changePropertyValue(pQtProperty, value);
}
void RengaPropertyController::onBoolPropertyChanged(QtProperty* pQtProperty, bool value)
{
changePropertyValue(pQtProperty, value);
}
Renga::IPropertyPtr RengaPropertyController::getProperty(QtProperty* pQtProperty)
{
auto properties = m_propertiesAccess();
if (properties == nullptr)
return nullptr;
const auto propertyId = GuidFromString(pQtProperty->data().toStdString());
return properties->Get(propertyId);
}
Renga::IOperationPtr RengaPropertyController::createOperation()
{
auto pProject = m_pRenga->GetProject();
auto pModel = pProject->GetModel();
return pModel->CreateOperation();
}
bool RengaPropertyController::tryGetEnumValueByIndex(GUID propertyId, int index, QString& result)
{
auto pProject = m_pRenga->GetProject();
if (pProject == nullptr)
return false;
auto pDesc = pProject->PropertyManager->GetPropertyDescription2(propertyId);
auto enumValueList = safeArrayToQStringList(pDesc->GetEnumerationItems());
if (index >= enumValueList.size())
return false;
result = enumValueList[index];
return true;
}
void RengaPropertyController::resetPropertyValue(QtProperty* pQtProperty)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
pProperty->ResetValue();
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, const double value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
switch (pProperty->GetType())
{
case Renga::PropertyType::PropertyType_Angle:
pProperty->SetAngleValue(value, Renga::AngleUnit::AngleUnit_Degrees);
break;
case Renga::PropertyType::PropertyType_Length:
pProperty->SetLengthValue(value, Renga::LengthUnit::LengthUnit_Millimeters);
break;
case Renga::PropertyType::PropertyType_Area:
pProperty->SetAreaValue(value, Renga::AreaUnit::AreaUnit_Meters2);
break;
case Renga::PropertyType::PropertyType_Volume:
pProperty->SetVolumeValue(value, Renga::VolumeUnit::VolumeUnit_Meters3);
break;
case Renga::PropertyType::PropertyType_Mass:
pProperty->SetMassValue(value, Renga::MassUnit::MassUnit_Kilograms);
break;
case Renga::PropertyType::PropertyType_Double:
pProperty->SetDoubleValue(value);
break;
default: break;
}
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, const QString& value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
switch (pProperty->GetType())
{
case Renga::PropertyType::PropertyType_String:
pProperty->SetStringValue(value.toStdWString().c_str());
break;
default: break;
}
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, int value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
switch (pProperty->GetType())
{
case Renga::PropertyType::PropertyType_String:
pProperty->SetIntegerValue(value);
break;
case Renga::PropertyType::PropertyType_Enumeration:
{
auto enumValue = QString();
if (tryGetEnumValueByIndex(pProperty->Id, value, enumValue))
pProperty->SetEnumerationValue(_bstr_t(enumValue.toStdWString().c_str()));
}
break;
case Renga::PropertyType::PropertyType_Logical:
{
auto logicalValue = getLogicalValueFromIndex(value);
pProperty->SetLogicalValue(logicalValue);
}
break;
default:
break;
}
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, bool value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
pProperty->SetBooleanValue(value);
pOperation->Apply();
}
<commit_msg>Bugfix #61252: fix integer property value editing<commit_after>//
// Copyright "Renga Software" LLC, 2016. All rights reserved.
//
// "Renga Software" LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// "Renga Software" LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
#include "stdafx.h"
#include "RengaPropertyController.h"
#include "COMUtils.h"
#include <qtpropertybrowser.h>
RengaPropertyController::RengaPropertyController(
Renga::IApplicationPtr pRenga,
PropertyContainerAccess propertiesAccess)
: m_pRenga(pRenga),
m_propertiesAccess(propertiesAccess)
{
}
void RengaPropertyController::onDoublePropertyChanged(QtProperty* pQtProperty, const QString& newValue)
{
if (newValue.isEmpty())
resetPropertyValue(pQtProperty); // will reset the attribute value
else
{
bool ok = false;
double newDoubleValue = QLocale::system().toDouble(newValue, &ok);
if (ok)
changePropertyValue(pQtProperty, newDoubleValue);
}
}
void RengaPropertyController::onStringPropertyChanged(QtProperty* pQtProperty, const QString& newValue)
{
if (newValue.isEmpty())
resetPropertyValue(pQtProperty); // will reset the attribute value
else
changePropertyValue(pQtProperty, newValue);
}
void RengaPropertyController::onIntPropertyChanged(QtProperty* pQtProperty, int value)
{
changePropertyValue(pQtProperty, value);
}
void RengaPropertyController::onBoolPropertyChanged(QtProperty* pQtProperty, bool value)
{
changePropertyValue(pQtProperty, value);
}
Renga::IPropertyPtr RengaPropertyController::getProperty(QtProperty* pQtProperty)
{
auto properties = m_propertiesAccess();
if (properties == nullptr)
return nullptr;
const auto propertyId = GuidFromString(pQtProperty->data().toStdString());
return properties->Get(propertyId);
}
Renga::IOperationPtr RengaPropertyController::createOperation()
{
auto pProject = m_pRenga->GetProject();
auto pModel = pProject->GetModel();
return pModel->CreateOperation();
}
bool RengaPropertyController::tryGetEnumValueByIndex(GUID propertyId, int index, QString& result)
{
auto pProject = m_pRenga->GetProject();
if (pProject == nullptr)
return false;
auto pDesc = pProject->PropertyManager->GetPropertyDescription2(propertyId);
auto enumValueList = safeArrayToQStringList(pDesc->GetEnumerationItems());
if (index >= enumValueList.size())
return false;
result = enumValueList[index];
return true;
}
void RengaPropertyController::resetPropertyValue(QtProperty* pQtProperty)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
pProperty->ResetValue();
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, const double value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
switch (pProperty->GetType())
{
case Renga::PropertyType::PropertyType_Angle:
pProperty->SetAngleValue(value, Renga::AngleUnit::AngleUnit_Degrees);
break;
case Renga::PropertyType::PropertyType_Length:
pProperty->SetLengthValue(value, Renga::LengthUnit::LengthUnit_Millimeters);
break;
case Renga::PropertyType::PropertyType_Area:
pProperty->SetAreaValue(value, Renga::AreaUnit::AreaUnit_Meters2);
break;
case Renga::PropertyType::PropertyType_Volume:
pProperty->SetVolumeValue(value, Renga::VolumeUnit::VolumeUnit_Meters3);
break;
case Renga::PropertyType::PropertyType_Mass:
pProperty->SetMassValue(value, Renga::MassUnit::MassUnit_Kilograms);
break;
case Renga::PropertyType::PropertyType_Double:
pProperty->SetDoubleValue(value);
break;
default: break;
}
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, const QString& value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
switch (pProperty->GetType())
{
case Renga::PropertyType::PropertyType_String:
pProperty->SetStringValue(value.toStdWString().c_str());
break;
default: break;
}
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, int value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
switch (pProperty->GetType())
{
case Renga::PropertyType::PropertyType_Integer:
pProperty->SetIntegerValue(value);
break;
case Renga::PropertyType::PropertyType_Enumeration:
{
auto enumValue = QString();
if (tryGetEnumValueByIndex(pProperty->Id, value, enumValue))
pProperty->SetEnumerationValue(_bstr_t(enumValue.toStdWString().c_str()));
}
break;
case Renga::PropertyType::PropertyType_Logical:
{
auto logicalValue = getLogicalValueFromIndex(value);
pProperty->SetLogicalValue(logicalValue);
}
break;
default:
break;
}
pOperation->Apply();
}
void RengaPropertyController::changePropertyValue(QtProperty* pQtProperty, bool value)
{
auto pProperty = getProperty(pQtProperty);
if (!pProperty)
return;
auto pOperation = createOperation();
pOperation->Start();
pProperty->SetBooleanValue(value);
pOperation->Apply();
}
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "QGroundControlQmlGlobal.h"
#include "QGCApplication.h"
#include <QSettings>
static const char* kQmlGlobalKeyName = "QGCQml";
QGroundControlQmlGlobal::QGroundControlQmlGlobal(QGCToolbox* toolbox, QObject* parent)
: QObject(parent)
, _homePositionManager(toolbox->homePositionManager())
, _flightMapSettings(toolbox->flightMapSettings())
{
}
void QGroundControlQmlGlobal::saveGlobalSetting (const QString& key, const QString& value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
QString QGroundControlQmlGlobal::loadGlobalSetting (const QString& key, const QString& defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toString();
}
void QGroundControlQmlGlobal::saveBoolGlobalSetting (const QString& key, bool value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
bool QGroundControlQmlGlobal::loadBoolGlobalSetting (const QString& key, bool defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toBool();
}
#ifdef QT_DEBUG
void QGroundControlQmlGlobal::_startMockLink(MockConfiguration* mockConfig)
{
MockLink* mockLink = new MockLink(mockConfig);
LinkManager* linkManager = qgcApp()->toolbox()->linkManager();
linkManager->_addLink(mockLink);
linkManager->connectLink(mockLink);
}
#endif
void QGroundControlQmlGlobal::startPX4MockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("PX4 MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_PX4);
mockConfig.setVehicleType(MAV_TYPE_QUADROTOR);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#endif
}
void QGroundControlQmlGlobal::startGenericMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("Generic MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_GENERIC);
mockConfig.setVehicleType(MAV_TYPE_QUADROTOR);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#endif
}
void QGroundControlQmlGlobal::startAPMArduCopterMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("APM ArduCopter MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_ARDUPILOTMEGA);
mockConfig.setVehicleType(MAV_TYPE_QUADROTOR);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#endif
}
void QGroundControlQmlGlobal::startAPMArduPlaneMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("APM ArduPlane MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_ARDUPILOTMEGA);
mockConfig.setVehicleType(MAV_TYPE_FIXED_WING);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#endif
}
void QGroundControlQmlGlobal::stopAllMockLinks(void)
{
#ifdef QT_DEBUG
LinkManager* linkManager = qgcApp()->toolbox()->linkManager();
QList<LinkInterface*> links = linkManager->getLinks();
for (int i=0; i<links.count(); i++) {
LinkInterface* link = links[i];
MockLink* mockLink = qobject_cast<MockLink*>(link);
if (mockLink) {
linkManager->disconnectLink(mockLink);
}
}
#endif
}
<commit_msg>Fix compiler warnings<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "QGroundControlQmlGlobal.h"
#include "QGCApplication.h"
#include <QSettings>
static const char* kQmlGlobalKeyName = "QGCQml";
QGroundControlQmlGlobal::QGroundControlQmlGlobal(QGCToolbox* toolbox, QObject* parent)
: QObject(parent)
, _homePositionManager(toolbox->homePositionManager())
, _flightMapSettings(toolbox->flightMapSettings())
{
}
void QGroundControlQmlGlobal::saveGlobalSetting (const QString& key, const QString& value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
QString QGroundControlQmlGlobal::loadGlobalSetting (const QString& key, const QString& defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toString();
}
void QGroundControlQmlGlobal::saveBoolGlobalSetting (const QString& key, bool value)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
settings.setValue(key, value);
}
bool QGroundControlQmlGlobal::loadBoolGlobalSetting (const QString& key, bool defaultValue)
{
QSettings settings;
settings.beginGroup(kQmlGlobalKeyName);
return settings.value(key, defaultValue).toBool();
}
#ifdef QT_DEBUG
void QGroundControlQmlGlobal::_startMockLink(MockConfiguration* mockConfig)
{
MockLink* mockLink = new MockLink(mockConfig);
LinkManager* linkManager = qgcApp()->toolbox()->linkManager();
linkManager->_addLink(mockLink);
linkManager->connectLink(mockLink);
}
#endif
void QGroundControlQmlGlobal::startPX4MockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("PX4 MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_PX4);
mockConfig.setVehicleType(MAV_TYPE_QUADROTOR);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startGenericMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("Generic MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_GENERIC);
mockConfig.setVehicleType(MAV_TYPE_QUADROTOR);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduCopterMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("APM ArduCopter MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_ARDUPILOTMEGA);
mockConfig.setVehicleType(MAV_TYPE_QUADROTOR);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::startAPMArduPlaneMockLink(bool sendStatusText)
{
#ifdef QT_DEBUG
MockConfiguration mockConfig("APM ArduPlane MockLink");
mockConfig.setFirmwareType(MAV_AUTOPILOT_ARDUPILOTMEGA);
mockConfig.setVehicleType(MAV_TYPE_FIXED_WING);
mockConfig.setSendStatusText(sendStatusText);
_startMockLink(&mockConfig);
#else
Q_UNUSED(sendStatusText);
#endif
}
void QGroundControlQmlGlobal::stopAllMockLinks(void)
{
#ifdef QT_DEBUG
LinkManager* linkManager = qgcApp()->toolbox()->linkManager();
QList<LinkInterface*> links = linkManager->getLinks();
for (int i=0; i<links.count(); i++) {
LinkInterface* link = links[i];
MockLink* mockLink = qobject_cast<MockLink*>(link);
if (mockLink) {
linkManager->disconnectLink(mockLink);
}
}
#endif
}
<|endoftext|> |
<commit_before>#include "module_pressuresensor.h"
#include "pressure_form.h"
#include "module_uid.h"
#define REGISTER_CALIB 00 // 8 bytes
#define REGISTER_PRESSURE_RAW 8
#define REGISTER_TEMP_RAW 10
#define REGISTER_PRESSURE 12
#define REGISTER_TEMP 14
#define REGISTER_STATUS 17
// indicates problem between i2c-spi bridge and pressure sensor
#define STATUS_MAGIC_VALUE 0x55
#define CALIB_MAGIC_VALUE 224
// pressure range. everything outside this range will be regarded as
// a meassurement error
#define PRESSURE_MIN 900
#define PRESSURE_MAX 3000
Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid)
: RobotModule(id)
{
this->uid=uid;
setDefaultValue("i2cAddress", 0x50);
setDefaultValue("frequency", 1);
connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData()));
reset();
}
Module_PressureSensor::~Module_PressureSensor()
{
}
void Module_PressureSensor::terminate()
{
timer.stop();
}
void Module_PressureSensor::reset()
{
int freq = 1000/getSettings().value("frequency").toInt();
if (freq>0)
timer.start(freq);
else
timer.stop();
}
void Module_PressureSensor::refreshData()
{
if (!getSettings().value("enabled").toBool())
return;
readPressure();
readTemperature();
}
void Module_PressureSensor::readPressure()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the pressure in mBar
uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["pressure"] = pressure;
// 100 mBar == ca. 1m wassersäule - druck an der luft
data["depth"] = ((float)pressure-getSettings().value("airPressure").toFloat())/100;
if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) {
setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense.");
}
}
void Module_PressureSensor::readTemperature()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_TEMP, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the temperature in 10/degree celsius
uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["temperature"] = ((float)temp)/10;
}
float Module_PressureSensor::getDepth()
{
float p = data["pressure"].toFloat();
if (p > 900 && p <= 2000) {
return data["depth"].toFloat();
} else {
setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense.");
return 0;
}
}
float Module_PressureSensor::getTemperature()
{
return data["temperature"].toFloat();
}
QList<RobotModule*> Module_PressureSensor::getDependencies()
{
QList<RobotModule*> ret;
ret.append(uid);
return ret;
}
QWidget* Module_PressureSensor::createView(QWidget* parent)
{
return new Pressure_Form(this, parent);
}
void Module_PressureSensor::doHealthCheck()
{
if (!getSettings().value("enabled").toBool())
return;
unsigned char readBuffer[1];
// if (!readRegister(REGISTER_CALIB, 1, readBuffer)) {
// setHealthToSick("UID reported error.");
// return;
// }
// if (readBuffer[0] != CALIB_MAGIC_VALUE) {
// setHealthToSick("First calibration byte doesn't match: is="+QString::number(readBuffer[0]));
// return;
// }
if (!readRegister(REGISTER_STATUS, 1, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
if (readBuffer[0] != STATUS_MAGIC_VALUE) {
setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0]));
return;
}
setHealthToOk();
}
bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf)
{
unsigned char address = getSettings().value("i2cAddress").toInt();
if (!uid->getUID()->I2C_Write(address, ®, 1)) {
setHealthToSick("UID reported error.");
return false;
}
if (!uid->getUID()->I2C_Read(address, size, ret_buf)) {
setHealthToSick("UID reported error.");
return false;
}
return true;
}
<commit_msg>more data logging<commit_after>#include "module_pressuresensor.h"
#include "pressure_form.h"
#include "module_uid.h"
#define REGISTER_CALIB 00 // 8 bytes
#define REGISTER_PRESSURE_RAW 8
#define REGISTER_TEMP_RAW 10
#define REGISTER_PRESSURE 12
#define REGISTER_TEMP 14
#define REGISTER_STATUS 17
// indicates problem between i2c-spi bridge and pressure sensor
#define STATUS_MAGIC_VALUE 0x55
#define CALIB_MAGIC_VALUE 224
// pressure range. everything outside this range will be regarded as
// a meassurement error
#define PRESSURE_MIN 900
#define PRESSURE_MAX 3000
Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid)
: RobotModule(id)
{
this->uid=uid;
setDefaultValue("i2cAddress", 0x50);
setDefaultValue("frequency", 1);
connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData()));
reset();
}
Module_PressureSensor::~Module_PressureSensor()
{
}
void Module_PressureSensor::terminate()
{
timer.stop();
}
void Module_PressureSensor::reset()
{
int freq = 1000/getSettings().value("frequency").toInt();
if (freq>0)
timer.start(freq);
else
timer.stop();
}
void Module_PressureSensor::refreshData()
{
if (!getSettings().value("enabled").toBool())
return;
readPressure();
readTemperature();
emit dataChanged(this);
}
void Module_PressureSensor::readPressure()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the pressure in mBar
uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["pressure"] = pressure;
// 100 mBar == ca. 1m wassersäule - druck an der luft
data["depth"] = ((float)pressure-getSettings().value("airPressure").toFloat())/100;
if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) {
setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense.");
}
}
void Module_PressureSensor::readTemperature()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_TEMP, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the temperature in 10/degree celsius
uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["temperature"] = ((float)temp)/10;
}
float Module_PressureSensor::getDepth()
{
float p = data["pressure"].toFloat();
if (p > 900 && p <= 2000) {
return data["depth"].toFloat();
} else {
setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense.");
return 0;
}
}
float Module_PressureSensor::getTemperature()
{
return data["temperature"].toFloat();
}
QList<RobotModule*> Module_PressureSensor::getDependencies()
{
QList<RobotModule*> ret;
ret.append(uid);
return ret;
}
QWidget* Module_PressureSensor::createView(QWidget* parent)
{
return new Pressure_Form(this, parent);
}
void Module_PressureSensor::doHealthCheck()
{
if (!getSettings().value("enabled").toBool())
return;
unsigned char readBuffer[1];
// if (!readRegister(REGISTER_CALIB, 1, readBuffer)) {
// setHealthToSick("UID reported error.");
// return;
// }
// if (readBuffer[0] != CALIB_MAGIC_VALUE) {
// setHealthToSick("First calibration byte doesn't match: is="+QString::number(readBuffer[0]));
// return;
// }
if (!readRegister(REGISTER_STATUS, 1, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
if (readBuffer[0] != STATUS_MAGIC_VALUE) {
setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0]));
return;
}
setHealthToOk();
}
bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf)
{
unsigned char address = getSettings().value("i2cAddress").toInt();
if (!uid->getUID()->I2C_Write(address, ®, 1)) {
setHealthToSick("UID reported error.");
return false;
}
if (!uid->getUID()->I2C_Read(address, size, ret_buf)) {
setHealthToSick("UID reported error.");
return false;
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Win32/HardwareInfoImpl.hpp>
#include <Nazara/Core/Error.hpp>
#include <windows.h>
#ifdef NAZARA_COMPILER_MSVC
#include <intrin.h>
#endif
#include <Nazara/Core/Debug.hpp>
void NzHardwareInfoImpl::Cpuid(nzUInt32 code, nzUInt32 result[4])
{
#if defined(NAZARA_COMPILER_MSVC)
__cpuid(reinterpret_cast<int*>(result), static_cast<int>(code)); // Visual propose une fonction intrinsèque pour le cpuid
#elif defined(NAZARA_COMPILER_CLANG) || defined(NAZARA_COMPILER_GCC) || defined(NAZARA_COMPILER_INTEL)
// Source: http://stackoverflow.com/questions/1666093/cpuid-implementations-in-c
asm volatile ("cpuid" // Besoin d'être volatile ?
: "=a" (result[0]), "=b" (result[1]), "=c" (result[2]), "=d" (result[3]) // output
: "a" (code), "c" (0)); // input
#else
NazaraInternalError("Cpuid has been called although it is not supported");
#endif
}
unsigned int NzHardwareInfoImpl::GetProcessorCount()
{
// Plus simple (et plus portable) que de passer par le CPUID
SYSTEM_INFO infos;
GetSystemInfo(&infos);
return infos.dwNumberOfProcessors;
}
bool NzHardwareInfoImpl::IsCpuidSupported()
{
#ifdef NAZARA_PLATFORM_x64
return true; // Toujours supporté sur un processeur 64 bits
#else
#if defined(NAZARA_COMPILER_MSVC)
int supported;
__asm
{
pushfd
pop eax
mov ecx, eax
xor eax, 0x200000
push eax
popfd
pushfd
pop eax
xor eax, ecx
mov supported, eax
push ecx
popfd
};
return supported != 0;
#elif defined(NAZARA_COMPILER_CLANG) || defined(NAZARA_COMPILER_GCC) || defined(NAZARA_COMPILER_INTEL)
int supported;
asm volatile (" pushfl\n"
" pop %%eax\n"
" mov %%eax, %%ecx\n"
" xor $0x200000, %%eax\n"
" push %%eax\n"
" popfl\n"
" pushfl\n"
" pop %%eax\n"
" xor %%ecx, %%eax\n"
" mov %%eax, %0\n"
" push %%ecx\n"
" popfl"
: "=m" (supported) // output
: // input
: "eax", "ecx", "memory"); // clobbered register
return supported != 0;
#else
return false;
#endif
#endif
}
<commit_msg>Fixed cpuid reported supported on unsupported compilers<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Win32/HardwareInfoImpl.hpp>
#include <Nazara/Core/Error.hpp>
#include <windows.h>
#ifdef NAZARA_COMPILER_MSVC
#include <intrin.h>
#endif
#include <Nazara/Core/Debug.hpp>
void NzHardwareInfoImpl::Cpuid(nzUInt32 code, nzUInt32 result[4])
{
#if defined(NAZARA_COMPILER_MSVC)
__cpuid(reinterpret_cast<int*>(result), static_cast<int>(code)); // Visual propose une fonction intrinsèque pour le cpuid
#elif defined(NAZARA_COMPILER_CLANG) || defined(NAZARA_COMPILER_GCC) || defined(NAZARA_COMPILER_INTEL)
// Source: http://stackoverflow.com/questions/1666093/cpuid-implementations-in-c
asm volatile ("cpuid" // Besoin d'être volatile ?
: "=a" (result[0]), "=b" (result[1]), "=c" (result[2]), "=d" (result[3]) // output
: "a" (code), "c" (0)); // input
#else
NazaraInternalError("Cpuid has been called although it is not supported");
#endif
}
unsigned int NzHardwareInfoImpl::GetProcessorCount()
{
// Plus simple (et plus portable) que de passer par le CPUID
SYSTEM_INFO infos;
GetSystemInfo(&infos);
return infos.dwNumberOfProcessors;
}
bool NzHardwareInfoImpl::IsCpuidSupported()
{
#if defined(NAZARA_COMPILER_MSVC)
#ifdef NAZARA_PLATFORM_x64
return true; // Toujours supporté sur un processeur 64 bits
#else
int supported;
__asm
{
pushfd
pop eax
mov ecx, eax
xor eax, 0x200000
push eax
popfd
pushfd
pop eax
xor eax, ecx
mov supported, eax
push ecx
popfd
};
return supported != 0;
#endif // NAZARA_PLATFORM_x64
#elif defined(NAZARA_COMPILER_CLANG) || defined(NAZARA_COMPILER_GCC) || defined(NAZARA_COMPILER_INTEL)
#ifdef NAZARA_PLATFORM_x64
return true; // Toujours supporté sur un processeur 64 bits
#else
int supported;
asm volatile (" pushfl\n"
" pop %%eax\n"
" mov %%eax, %%ecx\n"
" xor $0x200000, %%eax\n"
" push %%eax\n"
" popfl\n"
" pushfl\n"
" pop %%eax\n"
" xor %%ecx, %%eax\n"
" mov %%eax, %0\n"
" push %%ecx\n"
" popfl"
: "=m" (supported) // output
: // input
: "eax", "ecx", "memory"); // clobbered register
return supported != 0;
#endif // NAZARA_PLATFORM_x64
#else
return false;
#endif
}
<|endoftext|> |
<commit_before>//! \file ToJsonWriter.cpp
#include "ToJsonWriter.h"
#include <json/json.h>
#include "Article.h"
/*! Get article links in an array.
* Basically undoing the Wikipedia to article conversion...
* \param article pointer to article which links should be extracted
* \return Json::Value array with titles as string
* \todo should / could be a member function, but then I'd have to expose
* Json::Value, which is ugly and clutters up other classes...
*/
static Json::Value getArticleLinks(const Article* article)
{
Json::Value array(Json::ValueType::arrayValue);
for(auto ali = article->linkBegin(); ali != article->linkEnd(); ali++) {
std::string tit = (*ali)->getTitle();
array.append(Json::Value(tit));
}
return array;
}
std::string ToJsonWriter::convertToJson(const Article* a)
{
Json::Value val(Json::ValueType::objectValue);
Json::Value linkObj(Json::ValueType::objectValue);
linkObj["forward_links"] = getArticleLinks(a);
val[a->getTitle()] = linkObj;
Json::FastWriter jsw;
jsw.omitEndingLineFeed();
return jsw.write(val);
}
std::string ToJsonWriter::convertToJson(const ArticleCollection& ac)
{
Json::Value val(Json::ValueType::objectValue);
for(auto ar : ac) {
Json::Value linkObj(Json::ValueType::objectValue);
linkObj["forward_links"] = getArticleLinks(ar.second);
val[ar.first] = linkObj;
}
Json::FastWriter jsw;
jsw.omitEndingLineFeed();
return jsw.write(val);
}
void ToJsonWriter::output(const Article* article, std::ostream& outstream)
{
outstream << convertToJson(article);
}
void ToJsonWriter::output(const ArticleCollection& collection, std::ostream& outstream)
{
outstream << convertToJson(collection);
}
<commit_msg>Articles not analyzed have links set to null<commit_after>//! \file ToJsonWriter.cpp
#include "ToJsonWriter.h"
#include <json/json.h>
#include "Article.h"
/*! Get article links in an array.
* Basically undoing the Wikipedia to article conversion...
* \param article pointer to article which links should be extracted
* \return Json::Value array with titles as string
* \todo should / could be a member function, but then I'd have to expose
* Json::Value, which is ugly and clutters up other classes...
*/
static Json::Value getArticleLinks(const Article* article)
{
Json::Value array(Json::ValueType::arrayValue);
for(auto ali = article->linkBegin(); ali != article->linkEnd(); ali++) {
std::string tit = (*ali)->getTitle();
array.append(Json::Value(tit));
}
return array;
}
std::string ToJsonWriter::convertToJson(const Article* a)
{
Json::Value val(Json::ValueType::objectValue);
Json::Value linkObj(Json::ValueType::objectValue);
if(a->isAnalyzed()) {
linkObj["forward_links"] = getArticleLinks(a);
}
else {
linkObj["forward_links"] = Json::Value::nullSingleton();
}
val[a->getTitle()] = linkObj;
Json::FastWriter jsw;
jsw.omitEndingLineFeed();
return jsw.write(val);
}
std::string ToJsonWriter::convertToJson(const ArticleCollection& ac)
{
Json::Value val(Json::ValueType::objectValue);
for(auto ar : ac) {
Json::Value linkObj(Json::ValueType::objectValue);
if(ar.second->isAnalyzed()) {
linkObj["forward_links"] = getArticleLinks(ar.second);
}
else {
linkObj["forward_links"] = Json::Value::nullSingleton();
}
val[ar.first] = linkObj;
}
Json::FastWriter jsw;
jsw.omitEndingLineFeed();
return jsw.write(val);
}
void ToJsonWriter::output(const Article* article, std::ostream& outstream)
{
outstream << convertToJson(article);
}
void ToJsonWriter::output(const ArticleCollection& collection, std::ostream& outstream)
{
outstream << convertToJson(collection);
}
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_CORE_SYSTEM_HPP
#define MJOLNIR_CORE_SYSTEM_HPP
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/core/Particle.hpp>
#include <mjolnir/core/Topology.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <map>
#include <cassert>
namespace mjolnir
{
template<typename traitsT>
class System
{
public:
using traits_type = traitsT;
using string_type = std::string;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using matrix33_type = typename traits_type::matrix33_type;
using boundary_type = typename traits_type::boundary_type;
using topology_type = Topology;
using attribute_type = std::map<std::string, real_type>;
using rng_type = RandomNumberGenerator<traits_type>;
using real_container_type = std::vector<real_type>;
using coordinate_container_type = std::vector<coordinate_type>;
using string_container_type = std::vector<std::string>;
public:
System(const std::size_t num_particles, const boundary_type& bound)
: velocity_initialized_(false), force_initialized_(false),
boundary_(bound), attributes_(), virial_(0,0,0, 0,0,0, 0,0,0),
num_particles_(num_particles), masses_ (num_particles),
rmasses_ (num_particles), positions_(num_particles),
velocities_ (num_particles), forces_ (num_particles),
names_ (num_particles), groups_ (num_particles)
{}
~System() = default;
System(const System&) = default;
System(System&&) = default;
System& operator=(const System&) = default;
System& operator=(System&&) = default;
void initialize(rng_type& rng)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
// make all the particles inside the boundary
for(auto& p : this->positions_)
{
p = this->boundary_.adjust_position(p);
}
if(this->velocity_initialized_)
{
MJOLNIR_LOG_NOTICE(
"velocity is already given, nothing to initialize in System");
return ;
}
if(!this->has_attribute("temperature"))
{
throw std::runtime_error("[error] to generate velocity, "
"system.attributes.temperature is required.");
}
const real_type kB = physics::constants<real_type>::kB();
const real_type T_ref = this->attribute("temperature");
MJOLNIR_LOG_NOTICE("generating velocity with T = ", T_ref, "...");
// generate Maxwell-Boltzmann distribution
const real_type kBT = kB * T_ref;
for(std::size_t i=0; i<this->size(); ++i)
{
const auto vel_coef = std::sqrt(kBT / this->mass(i));
math::X(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Y(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Z(this->velocity(i)) = rng.gaussian(0, vel_coef);
}
MJOLNIR_LOG_NOTICE("done.");
return;
}
coordinate_type adjust_direction(coordinate_type from, coordinate_type to) const noexcept
{
return boundary_.adjust_direction(from, to);
}
coordinate_type adjust_position(coordinate_type dr) const noexcept
{
return boundary_.adjust_position(dr);
}
coordinate_type transpose(coordinate_type tgt, const coordinate_type& ref) const noexcept
{
return boundary_.transpose(tgt, ref);
}
std::size_t size() const noexcept {return num_particles_;}
// When parallelizing a code, forces are often calculated separately in
// several computational units, like cores, nodes, gpu devices, etc. To
// make it consistent, we may need to do something with forces calculated
// separately. Those functions are provided for such an specialized
// situation. Here, for the normal case, we do not need to do anything.
// Before calling `preprocess_forces()`, (a part of) forces may already
// be calculated. So this function should NOT break the forces that is
// already written in the `force(i)`.
// After calling `postprocess_forces()`, the result of `force(i)` always
// represents the "force" of a particle at that time point. I mean, we can
// consider the "force" is equivalent to the force that is calculated by
// single core.
void preprocess_forces() noexcept {/* do nothing */}
void postprocess_forces() noexcept {/* do nothing */}
real_type mass (std::size_t i) const noexcept {return masses_[i];}
real_type& mass (std::size_t i) noexcept {return masses_[i];}
real_type rmass(std::size_t i) const noexcept {return rmasses_[i];}
real_type& rmass(std::size_t i) noexcept {return rmasses_[i];}
coordinate_type const& position(std::size_t i) const noexcept {return positions_[i];}
coordinate_type& position(std::size_t i) noexcept {return positions_[i];}
coordinate_type const& velocity(std::size_t i) const noexcept {return velocities_[i];}
coordinate_type& velocity(std::size_t i) noexcept {return velocities_[i];}
coordinate_type const& force (std::size_t i) const noexcept {return forces_[i];}
coordinate_type& force (std::size_t i) noexcept {return forces_[i];}
string_type const& name (std::size_t i) const noexcept {return names_[i];}
string_type& name (std::size_t i) noexcept {return names_[i];}
string_type const& group(std::size_t i) const noexcept {return groups_[i];}
string_type& group(std::size_t i) noexcept {return groups_[i];}
matrix33_type& virial() noexcept {return virial_;}
matrix33_type const& virial() const noexcept {return virial_;}
boundary_type& boundary() noexcept {return boundary_;}
boundary_type const& boundary() const noexcept {return boundary_;}
// system attributes like `reference temperature`, `ionic strength`, ...
// assuming it will not be called so often.
real_type attribute(const std::string& key) const {return attributes_.at(key);}
real_type& attribute(const std::string& key) {return attributes_[key];}
bool has_attribute(const std::string& key) const {return attributes_.count(key) == 1;}
attribute_type const& attributes() const noexcept {return attributes_;}
bool velocity_initialized() const noexcept {return velocity_initialized_;}
bool& velocity_initialized() noexcept {return velocity_initialized_;}
bool force_initialized() const noexcept {return force_initialized_;}
bool& force_initialized() noexcept {return force_initialized_;}
coordinate_container_type const& forces() const noexcept {return forces_;}
coordinate_container_type& forces() noexcept {return forces_;}
private:
bool velocity_initialized_, force_initialized_;
boundary_type boundary_;
attribute_type attributes_;
matrix33_type virial_;
std::size_t num_particles_;
real_container_type masses_;
real_container_type rmasses_; // r for reciprocal
coordinate_container_type positions_;
coordinate_container_type velocities_;
coordinate_container_type forces_;
string_container_type names_;
string_container_type groups_;
#ifdef MJOLNIR_WITH_OPENMP
// OpenMP implementation uses its own System<OpenMP> to avoid data race.
// So this implementation should not be instanciated with OpenMP Traits.
static_assert(!is_openmp_simulator_traits<traits_type>::value,
"this is the default implementation, not for OpenMP");
#endif
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class System<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class System<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_SYSTEM_HPP
<commit_msg>refactor: remove needless include file<commit_after>#ifndef MJOLNIR_CORE_SYSTEM_HPP
#define MJOLNIR_CORE_SYSTEM_HPP
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/core/Topology.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <map>
#include <cassert>
namespace mjolnir
{
template<typename traitsT>
class System
{
public:
using traits_type = traitsT;
using string_type = std::string;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using matrix33_type = typename traits_type::matrix33_type;
using boundary_type = typename traits_type::boundary_type;
using topology_type = Topology;
using attribute_type = std::map<std::string, real_type>;
using rng_type = RandomNumberGenerator<traits_type>;
using real_container_type = std::vector<real_type>;
using coordinate_container_type = std::vector<coordinate_type>;
using string_container_type = std::vector<std::string>;
public:
System(const std::size_t num_particles, const boundary_type& bound)
: velocity_initialized_(false), force_initialized_(false),
boundary_(bound), attributes_(), virial_(0,0,0, 0,0,0, 0,0,0),
num_particles_(num_particles), masses_ (num_particles),
rmasses_ (num_particles), positions_(num_particles),
velocities_ (num_particles), forces_ (num_particles),
names_ (num_particles), groups_ (num_particles)
{}
~System() = default;
System(const System&) = default;
System(System&&) = default;
System& operator=(const System&) = default;
System& operator=(System&&) = default;
void initialize(rng_type& rng)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
// make all the particles inside the boundary
for(auto& p : this->positions_)
{
p = this->boundary_.adjust_position(p);
}
if(this->velocity_initialized_)
{
MJOLNIR_LOG_NOTICE(
"velocity is already given, nothing to initialize in System");
return ;
}
if(!this->has_attribute("temperature"))
{
throw std::runtime_error("[error] to generate velocity, "
"system.attributes.temperature is required.");
}
const real_type kB = physics::constants<real_type>::kB();
const real_type T_ref = this->attribute("temperature");
MJOLNIR_LOG_NOTICE("generating velocity with T = ", T_ref, "...");
// generate Maxwell-Boltzmann distribution
const real_type kBT = kB * T_ref;
for(std::size_t i=0; i<this->size(); ++i)
{
const auto vel_coef = std::sqrt(kBT / this->mass(i));
math::X(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Y(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Z(this->velocity(i)) = rng.gaussian(0, vel_coef);
}
MJOLNIR_LOG_NOTICE("done.");
return;
}
coordinate_type adjust_direction(coordinate_type from, coordinate_type to) const noexcept
{
return boundary_.adjust_direction(from, to);
}
coordinate_type adjust_position(coordinate_type dr) const noexcept
{
return boundary_.adjust_position(dr);
}
coordinate_type transpose(coordinate_type tgt, const coordinate_type& ref) const noexcept
{
return boundary_.transpose(tgt, ref);
}
std::size_t size() const noexcept {return num_particles_;}
// When parallelizing a code, forces are often calculated separately in
// several computational units, like cores, nodes, gpu devices, etc. To
// make it consistent, we may need to do something with forces calculated
// separately. Those functions are provided for such an specialized
// situation. Here, for the normal case, we do not need to do anything.
// Before calling `preprocess_forces()`, (a part of) forces may already
// be calculated. So this function should NOT break the forces that is
// already written in the `force(i)`.
// After calling `postprocess_forces()`, the result of `force(i)` always
// represents the "force" of a particle at that time point. I mean, we can
// consider the "force" is equivalent to the force that is calculated by
// single core.
void preprocess_forces() noexcept {/* do nothing */}
void postprocess_forces() noexcept {/* do nothing */}
real_type mass (std::size_t i) const noexcept {return masses_[i];}
real_type& mass (std::size_t i) noexcept {return masses_[i];}
real_type rmass(std::size_t i) const noexcept {return rmasses_[i];}
real_type& rmass(std::size_t i) noexcept {return rmasses_[i];}
coordinate_type const& position(std::size_t i) const noexcept {return positions_[i];}
coordinate_type& position(std::size_t i) noexcept {return positions_[i];}
coordinate_type const& velocity(std::size_t i) const noexcept {return velocities_[i];}
coordinate_type& velocity(std::size_t i) noexcept {return velocities_[i];}
coordinate_type const& force (std::size_t i) const noexcept {return forces_[i];}
coordinate_type& force (std::size_t i) noexcept {return forces_[i];}
string_type const& name (std::size_t i) const noexcept {return names_[i];}
string_type& name (std::size_t i) noexcept {return names_[i];}
string_type const& group(std::size_t i) const noexcept {return groups_[i];}
string_type& group(std::size_t i) noexcept {return groups_[i];}
matrix33_type& virial() noexcept {return virial_;}
matrix33_type const& virial() const noexcept {return virial_;}
boundary_type& boundary() noexcept {return boundary_;}
boundary_type const& boundary() const noexcept {return boundary_;}
// system attributes like `reference temperature`, `ionic strength`, ...
// assuming it will not be called so often.
real_type attribute(const std::string& key) const {return attributes_.at(key);}
real_type& attribute(const std::string& key) {return attributes_[key];}
bool has_attribute(const std::string& key) const {return attributes_.count(key) == 1;}
attribute_type const& attributes() const noexcept {return attributes_;}
bool velocity_initialized() const noexcept {return velocity_initialized_;}
bool& velocity_initialized() noexcept {return velocity_initialized_;}
bool force_initialized() const noexcept {return force_initialized_;}
bool& force_initialized() noexcept {return force_initialized_;}
coordinate_container_type const& forces() const noexcept {return forces_;}
coordinate_container_type& forces() noexcept {return forces_;}
private:
bool velocity_initialized_, force_initialized_;
boundary_type boundary_;
attribute_type attributes_;
matrix33_type virial_;
std::size_t num_particles_;
real_container_type masses_;
real_container_type rmasses_; // r for reciprocal
coordinate_container_type positions_;
coordinate_container_type velocities_;
coordinate_container_type forces_;
string_container_type names_;
string_container_type groups_;
#ifdef MJOLNIR_WITH_OPENMP
// OpenMP implementation uses its own System<OpenMP> to avoid data race.
// So this implementation should not be instanciated with OpenMP Traits.
static_assert(!is_openmp_simulator_traits<traits_type>::value,
"this is the default implementation, not for OpenMP");
#endif
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class System<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class System<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_SYSTEM_HPP
<|endoftext|> |
<commit_before>/* Fernando Jorge Mota (13200641) e Caique Rodrigues Marques (13204303)
* Task.cc
*
* Created on: Feb 27, 2014
*/
#include "Task.h"
#include <stdlib.h>
#include <ucontext.h>
#include <stdio.h>
namespace BOOOS
{
volatile Task * Task::__running;
Task* Task::__main;
int Task::STACK_SIZE = 32768;
int Task::__tid_counter = 1;
Task::Task(void (*entry_point)(void), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)(void)) entry_point, nargs, arg);
}
Task::Task(void (*entry_point)(void*), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)(void)) entry_point, nargs, arg);
}
Task::Task() {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
this->_tid = 0;
}
Task::~Task() {
delete this->_stack;
}
void Task::pass_to(Task *t, State s) {
this->_state = s;
Task::__running = t;
t->_state = Task::RUNNING;
swapcontext(&(this->context), &(t->context));
}
void Task::init() {
Task::__tid_counter = 1;
Task::__main = new Task();
Task::__running = Task::__main;
Task::__running->_state = Task::RUNNING;
}
void Task::exit(int code) {
this->pass_to(Task::__main, Task::FINISHING);
}
} /* namespace BOOOS */
<commit_msg>Change first line comment<commit_after>/* Caique Rodrigues Marques (13204303) e Fernando Jorge Mota (13200641)
* Task.cc
*
* Created on: Feb 27, 2014
*/
#include "Task.h"
#include <stdlib.h>
#include <ucontext.h>
#include <stdio.h>
namespace BOOOS
{
volatile Task * Task::__running;
Task* Task::__main;
int Task::STACK_SIZE = 32768;
int Task::__tid_counter = 1;
Task::Task(void (*entry_point)(void), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)(void)) entry_point, nargs, arg);
}
Task::Task(void (*entry_point)(void*), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)(void)) entry_point, nargs, arg);
}
Task::Task() {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
this->_tid = 0;
}
Task::~Task() {
delete this->_stack;
}
void Task::pass_to(Task *t, State s) {
this->_state = s;
Task::__running = t;
t->_state = Task::RUNNING;
swapcontext(&(this->context), &(t->context));
}
void Task::init() {
Task::__tid_counter = 1;
Task::__main = new Task();
Task::__running = Task::__main;
Task::__running->_state = Task::RUNNING;
}
void Task::exit(int code) {
this->pass_to(Task::__main, Task::FINISHING);
}
} /* namespace BOOOS */
<|endoftext|> |
<commit_before>/**
* \file dcs/testbed/system_identification.hpp
*
* \brief Performs system identification experiments.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dcsxx-testbed 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 dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <ctime>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/base_signal_generator.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <fstream>
#include <iterator>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unistd.h>
#include <vector>
#ifdef DCS_DEBUG
# include <boost/numeric/ublas/io.hpp>
#endif // DCS_DEBUG
namespace dcs { namespace testbed {
template <typename RealT>
class system_identification
{
public: typedef RealT real_type;
public: typedef base_virtual_machine<real_type> vm_type;
public: typedef ::boost::shared_ptr<vm_type> vm_pointer;
public: typedef base_signal_generator<real_type> signal_generator_type;
public: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;
public: typedef base_workload_driver workload_driver_type;
public: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;
private: typedef ::std::vector<vm_pointer> vm_container;
private: static const unsigned int default_sampling_time = 10;
private: static const ::std::string default_output_data_file_path;
/// Default constructor.
public: system_identification()
: ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// A constructor.
public: template <typename FwdIterT>
system_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)
: vms_(vm_first, vm_last),
p_wkl_driver_(p_wkl_driver),
p_sig_gen_(p_sig_gen),
ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// Set the path of the output data file.
public: void output_data_file(::std::string const& s)
{
// pre: s != ""
DCS_ASSERT(!s.empty(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Cannot use empty string as output data file name"));
out_dat_file_ = s;
}
/// Enabled or disable the extended format of the output data file.
public: void output_extended_format(bool val)
{
out_ext_fmt_ = val;
}
/// Set the sampling time.
public: void sampling_time(real_type t)
{
// pre: t > 0
DCS_ASSERT(t > 0,
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time must be positive"));
// pre: t <= max value
DCS_ASSERT(t <= ::std::numeric_limits<unsigned int>::max(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time too large"));
ts_ = static_cast<unsigned int>(t);
}
/**
* \brief Perform system identification by using as initial shares the
* 100% of resource.
*/
public: void run()
{
::std::vector<real_type> init_shares(vms_.size(), 1);
this->run(init_shares.begin(), init_shares.end());
}
/**
* \brief Perform system identification with the given initial shares.
*/
public: template <typename FwdIterT>
void run(FwdIterT share_first, FwdIterT share_end)
{
// distance(share_first,share_end) == size(vms_)
DCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Share container size does not match"));
typedef typename vm_container::const_iterator vm_iterator;
typedef typename signal_generator_type::vector_type share_container;
//const ::std::size_t nt(10);//FIXME: parameterize
// Open output data file
::std::ofstream ofs(out_dat_file_.c_str());
if (!ofs.good())
{
::std::ostringstream oss;
oss << "Cannot open output data file '" << out_dat_file_ << "'";
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
// Set initial shares
vm_iterator vm_end_it(vms_.end());
vm_iterator vm_beg_it(vms_.begin());
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
p_vm->cpu_share(*share_first);
++share_first;
}
// Start the workload driver
p_wkl_driver_->start();
// Set shares according to the given signal
::std::time_t t0;
::std::time_t t1;
t0 = ::std::time(&t1);
while (!p_wkl_driver_->done())
{
if (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())
{
// Stringstream used to hold common output info
::std::ostringstream oss;
// Compute the elapsed time
t0 = t1;
::std::time(&t1);
double dt = ::std::difftime(t1, t0);
DCS_DEBUG_TRACE( "-- Time " << dt );
oss << dt;
// Generate new shares
share_container share((*p_sig_gen_)());
// check: consistency
DCS_DEBUG_ASSERT( share.size() == vms_.size() );
DCS_DEBUG_TRACE( " Generated shares: " << dcs::debug::to_string(share.begin(), share.end()) );
// Set new shares to every VM
::std::size_t ix(0);
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
// check: not null
DCS_DEBUG_ASSERT( p_vm );
DCS_DEBUG_TRACE( " VM '" << p_vm->name() << "' :: Old CPU share: " << p_vm->cpu_share() << " :: New CPU share: " << share[ix] );
oss << " " << p_vm->cpu_share();
p_vm->cpu_share(share[ix]);
++ix;
}
// Get collected observations
typedef ::std::vector<real_type> obs_container;
typedef typename obs_container::const_iterator obs_iterator;
obs_container obs = p_wkl_driver_->observations();
//FIXME: parameterize the type of statistics the user want
::boost::accumulators::accumulator_set< real_type, ::boost::accumulators::stats< ::boost::accumulators::tag::mean > > acc;
obs_iterator obs_end_it(obs.end());
for (obs_iterator obs_it = obs.begin();
obs_it != obs_end_it;
++obs_it)
{
real_type val(*obs_it);
acc(val);
if (out_ext_fmt_)
{
ofs << oss << " " << val << " " << "\"[DATA]\"" << ::std::endl;
}
}
// Compute a summary statistics of collected observation
//FIXME: parameterize the type of statistics the user want
real_type summary_obs = ::boost::accumulators::mean(acc);
DCS_DEBUG_TRACE( " Current (summary) observation: " << summary_obs );
if (out_ext_fmt_)
{
ofs << oss << " " << summary_obs << " " << "\"[SUMMARY]\"" << ::std::endl;
}
else
{
ofs << oss << " " << summary_obs << ::std::endl;
}
// Wait until the next sampling time
::sleep(ts_);
}
}
// Stop the workload driver
p_wkl_driver_->stop();
// Close output data file
ofs.close();
}
private: vm_container vms_; ///< VMs container
private: workload_driver_pointer p_wkl_driver_; ///< Ptr to workload driver
private: signal_generator_pointer p_sig_gen_; ///< Ptr to signal generator used to excite VMs
private: unsigned int ts_; ///< The sampling time
private: ::std::string out_dat_file_; ///< The path to the output data file
private: bool out_ext_fmt_; ///< Flag to control whether to produce an output data file with extended format
}; // system_identification
template <typename RealT>
const ::std::string system_identification<RealT>::default_output_data_file_path("./sysid_out.dat");
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
<commit_msg>(bug-fix:minor) In code for writing output data file, the std::ostringstream object was sent to the stream instead of the string created by it.<commit_after>/**
* \file dcs/testbed/system_identification.hpp
*
* \brief Performs system identification experiments.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dcsxx-testbed 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 dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <ctime>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/base_signal_generator.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <fstream>
#include <iterator>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unistd.h>
#include <vector>
#ifdef DCS_DEBUG
# include <boost/numeric/ublas/io.hpp>
#endif // DCS_DEBUG
namespace dcs { namespace testbed {
template <typename RealT>
class system_identification
{
public: typedef RealT real_type;
public: typedef base_virtual_machine<real_type> vm_type;
public: typedef ::boost::shared_ptr<vm_type> vm_pointer;
public: typedef base_signal_generator<real_type> signal_generator_type;
public: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;
public: typedef base_workload_driver workload_driver_type;
public: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;
private: typedef ::std::vector<vm_pointer> vm_container;
private: static const unsigned int default_sampling_time = 10;
private: static const ::std::string default_output_data_file_path;
/// Default constructor.
public: system_identification()
: ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// A constructor.
public: template <typename FwdIterT>
system_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)
: vms_(vm_first, vm_last),
p_wkl_driver_(p_wkl_driver),
p_sig_gen_(p_sig_gen),
ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// Set the path of the output data file.
public: void output_data_file(::std::string const& s)
{
// pre: s != ""
DCS_ASSERT(!s.empty(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Cannot use empty string as output data file name"));
out_dat_file_ = s;
}
/// Enabled or disable the extended format of the output data file.
public: void output_extended_format(bool val)
{
out_ext_fmt_ = val;
}
/// Set the sampling time.
public: void sampling_time(real_type t)
{
// pre: t > 0
DCS_ASSERT(t > 0,
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time must be positive"));
// pre: t <= max value
DCS_ASSERT(t <= ::std::numeric_limits<unsigned int>::max(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time too large"));
ts_ = static_cast<unsigned int>(t);
}
/**
* \brief Perform system identification by using as initial shares the
* 100% of resource.
*/
public: void run()
{
::std::vector<real_type> init_shares(vms_.size(), 1);
this->run(init_shares.begin(), init_shares.end());
}
/**
* \brief Perform system identification with the given initial shares.
*/
public: template <typename FwdIterT>
void run(FwdIterT share_first, FwdIterT share_end)
{
// distance(share_first,share_end) == size(vms_)
DCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Share container size does not match"));
typedef typename vm_container::const_iterator vm_iterator;
typedef typename signal_generator_type::vector_type share_container;
//const ::std::size_t nt(10);//FIXME: parameterize
// Open output data file
::std::ofstream ofs(out_dat_file_.c_str());
if (!ofs.good())
{
::std::ostringstream oss;
oss << "Cannot open output data file '" << out_dat_file_ << "'";
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
// Set initial shares
vm_iterator vm_end_it(vms_.end());
vm_iterator vm_beg_it(vms_.begin());
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
p_vm->cpu_share(*share_first);
++share_first;
}
// Start the workload driver
p_wkl_driver_->start();
// Set shares according to the given signal
::std::time_t t0;
::std::time_t t1;
t0 = ::std::time(&t1);
while (!p_wkl_driver_->done())
{
if (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())
{
// Stringstream used to hold common output info
::std::ostringstream oss;
// Compute the elapsed time
t0 = t1;
::std::time(&t1);
double dt = ::std::difftime(t1, t0);
DCS_DEBUG_TRACE( "-- Time " << dt );
oss << dt;
// Generate new shares
share_container share((*p_sig_gen_)());
// check: consistency
DCS_DEBUG_ASSERT( share.size() == vms_.size() );
DCS_DEBUG_TRACE( " Generated shares: " << dcs::debug::to_string(share.begin(), share.end()) );
// Set new shares to every VM
::std::size_t ix(0);
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
// check: not null
DCS_DEBUG_ASSERT( p_vm );
DCS_DEBUG_TRACE( " VM '" << p_vm->name() << "' :: Old CPU share: " << p_vm->cpu_share() << " :: New CPU share: " << share[ix] );
oss << " " << p_vm->cpu_share();
p_vm->cpu_share(share[ix]);
++ix;
}
// Get collected observations
typedef ::std::vector<real_type> obs_container;
typedef typename obs_container::const_iterator obs_iterator;
obs_container obs = p_wkl_driver_->observations();
//FIXME: parameterize the type of statistics the user want
::boost::accumulators::accumulator_set< real_type, ::boost::accumulators::stats< ::boost::accumulators::tag::mean > > acc;
obs_iterator obs_end_it(obs.end());
for (obs_iterator obs_it = obs.begin();
obs_it != obs_end_it;
++obs_it)
{
real_type val(*obs_it);
acc(val);
if (out_ext_fmt_)
{
ofs << oss.str() << " " << val << " " << "\"[DATA]\"" << ::std::endl;
}
}
// Compute a summary statistics of collected observation
//FIXME: parameterize the type of statistics the user want
real_type summary_obs = ::boost::accumulators::mean(acc);
DCS_DEBUG_TRACE( " Current (summary) observation: " << summary_obs );
if (out_ext_fmt_)
{
ofs << oss.str() << " " << summary_obs << " " << "\"[SUMMARY]\"" << ::std::endl;
}
else
{
ofs << oss.str() << " " << summary_obs << ::std::endl;
}
// Wait until the next sampling time
::sleep(ts_);
}
}
// Stop the workload driver
p_wkl_driver_->stop();
// Close output data file
ofs.close();
}
private: vm_container vms_; ///< VMs container
private: workload_driver_pointer p_wkl_driver_; ///< Ptr to workload driver
private: signal_generator_pointer p_sig_gen_; ///< Ptr to signal generator used to excite VMs
private: unsigned int ts_; ///< The sampling time
private: ::std::string out_dat_file_; ///< The path to the output data file
private: bool out_ext_fmt_; ///< Flag to control whether to produce an output data file with extended format
}; // system_identification
template <typename RealT>
const ::std::string system_identification<RealT>::default_output_data_file_path("./sysid_out.dat");
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <map>
#include <sstream>
#include <string>
#include <boost/filesystem.hpp>
#include <sqlite3.h>
#include "prioritydb.h"
#define DEFAULT_MAX_SIZE 100000000LL
namespace fs = boost::filesystem;
class DBFixture : public ::testing::Test {
protected:
typedef std::map<std::string, std::string> Record;
virtual void SetUp() {
db_path_ = fs::temp_directory_path() / fs::path{"prism_test.db"};
db_string_ = db_path_.native();
table_name_ = "prism_data";
fs::remove(db_path_);
}
virtual void TearDown() {
fs::remove(db_path_);
}
sqlite3* open_db_() {
sqlite3* sqlite_db;
if (sqlite3_open(db_string_.data(), &sqlite_db) != SQLITE_OK) {
throw PriorityDBException{sqlite3_errmsg(sqlite_db)};
}
return sqlite_db;
}
int close_db_(sqlite3* db) {
return sqlite3_close(db);
}
static int callback_(void* response_ptr, int num_values, char** values, char** names) {
auto response = (std::vector<Record>*) response_ptr;
auto record = Record();
for (int i = 0; i < num_values; ++i) {
if (values[i]) {
record[names[i]] = values[i];
}
}
response->push_back(record);
return 0;
}
std::vector<Record> execute_(const std::string& sql) {
std::vector<Record> response;
auto db = open_db_();
char* error;
int rc = sqlite3_exec(db, sql.data(), &callback_, &response, &error);
if (rc != SQLITE_OK) {
auto error_string = std::string{error};
sqlite3_free(error);
throw PriorityDBException{error_string};
}
return response;
}
fs::path db_path_;
std::string db_string_;
std::string table_name_;
};
TEST_F(DBFixture, EmptyDBTest) {
EXPECT_FALSE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructDBTest) {
ASSERT_FALSE(fs::exists(db_path_));
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
EXPECT_TRUE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructDBNoDestructTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
EXPECT_TRUE(fs::exists(db_path_));
}
EXPECT_TRUE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructDBMultipleTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
}
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
EXPECT_TRUE(fs::exists(db_path_));
}
EXPECT_TRUE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructThrowTest) {
bool thrown = false;
try {
PriorityDB db{DEFAULT_MAX_SIZE, (fs::temp_directory_path() / fs::path{""}).native()};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"unable to open database file"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, ConstructCurrentThrowTest) {
bool thrown = false;
try {
PriorityDB db{DEFAULT_MAX_SIZE, (fs::temp_directory_path() / fs::path{"."}).native()};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"unable to open database file"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, ConstructParentThrowTest) {
bool thrown = false;
try {
PriorityDB db{DEFAULT_MAX_SIZE, (fs::temp_directory_path() / fs::path{".."}).native()};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"unable to open database file"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, ConstructZeroSpaceTest) {
bool thrown = false;
try {
PriorityDB db{0LL, db_string_};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"Must specify a nonzero max_size"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, InitialDBTest) {
ASSERT_FALSE(fs::exists(db_path_));
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='"
<< table_name_
<< "';";
auto response = execute_(stream.str());
ASSERT_EQ(1, response.size());
auto record = response[0];
ASSERT_EQ(1, record.size());
ASSERT_NE(record.end(), record.find("name"));
EXPECT_EQ(std::string{"prism_data"}, record["name"]);
}
TEST_F(DBFixture, InitialEmptyDBTest) {
ASSERT_FALSE(fs::exists(db_path_));
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
EXPECT_EQ(0, response.size());
}
TEST_F(DBFixture, InitialDBAfterDestructorTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
}
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='"
<< table_name_
<< "';";
auto response = execute_(stream.str());
ASSERT_EQ(1, response.size());
auto record = response[0];
ASSERT_EQ(1, record.size());
ASSERT_NE(record.end(), record.find("name"));
EXPECT_EQ(std::string{"prism_data"}, record["name"]);
}
TEST_F(DBFixture, InitialEmptyDBAfterDestructorTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
}
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
EXPECT_EQ(0, response.size());
}
TEST_F(DBFixture, InsertSingleTest) {
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
db.Insert(1, "hash", 5, false);
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
ASSERT_EQ(1, response.size());
auto record = response[0];
ASSERT_EQ(5, record.size());
EXPECT_EQ(1, std::stoi(record["id"]));
EXPECT_EQ(1, std::stoi(record["priority"]));
EXPECT_EQ(std::string{"hash"}, record["hash"]);
EXPECT_EQ(false, std::stoi(record["on_disk"]));
}
TEST_F(DBFixture, InsertCoupleTest) {
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
db.Insert(1, "hash", 5, false);
db.Insert(3, "hashbrowns", 10, true);
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
for (auto& record : response) {
for (auto item = record.begin(); item != record.end(); ++item) {
std::cout << item->first << ": " << item->second << std::endl;
}
}
ASSERT_EQ(2, response.size());
{
auto record = response[0];
ASSERT_EQ(5, record.size());
EXPECT_EQ(1, std::stoi(record["id"]));
EXPECT_EQ(1, std::stoi(record["priority"]));
EXPECT_EQ(std::string{"hash"}, record["hash"]);
EXPECT_EQ(5, std::stoi(record["size"]));
EXPECT_EQ(false, std::stoi(record["on_disk"]));
}
{
auto record = response[1];
ASSERT_EQ(5, record.size());
EXPECT_EQ(2, std::stoi(record["id"]));
EXPECT_EQ(3, std::stoi(record["priority"]));
EXPECT_EQ(std::string{"hashbrowns"}, record["hash"]);
EXPECT_EQ(10, std::stoi(record["size"]));
EXPECT_EQ(true, std::stoi(record["on_disk"]));
}
}
TEST_F(DBFixture, InsertManyTest) {
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
auto number_of_records = 100;
for (int i = 0; i < number_of_records; ++i) {
db.Insert(i, std::to_string(i * i), i * 2, i % 2);
}
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
ASSERT_EQ(number_of_records, response.size());
for (int i = 0; i < number_of_records; ++i) {
auto record = response[i];
ASSERT_EQ(5, record.size());
EXPECT_EQ(i + 1, std::stoi(record["id"]));
EXPECT_EQ(i, std::stoi(record["priority"]));
EXPECT_EQ(std::to_string(i * i), record["hash"]);
EXPECT_EQ(i * 2, std::stoi(record["size"]));
EXPECT_EQ(i % 2, std::stoi(record["on_disk"]));
}
}
<commit_msg>Add additional insert test<commit_after>#include <gtest/gtest.h>
#include <map>
#include <sstream>
#include <string>
#include <boost/filesystem.hpp>
#include <sqlite3.h>
#include "prioritydb.h"
#define DEFAULT_MAX_SIZE 100000000LL
namespace fs = boost::filesystem;
class DBFixture : public ::testing::Test {
protected:
typedef std::map<std::string, std::string> Record;
virtual void SetUp() {
db_path_ = fs::temp_directory_path() / fs::path{"prism_test.db"};
db_string_ = db_path_.native();
table_name_ = "prism_data";
fs::remove(db_path_);
}
virtual void TearDown() {
fs::remove(db_path_);
}
sqlite3* open_db_() {
sqlite3* sqlite_db;
if (sqlite3_open(db_string_.data(), &sqlite_db) != SQLITE_OK) {
throw PriorityDBException{sqlite3_errmsg(sqlite_db)};
}
return sqlite_db;
}
int close_db_(sqlite3* db) {
return sqlite3_close(db);
}
static int callback_(void* response_ptr, int num_values, char** values, char** names) {
auto response = (std::vector<Record>*) response_ptr;
auto record = Record();
for (int i = 0; i < num_values; ++i) {
if (values[i]) {
record[names[i]] = values[i];
}
}
response->push_back(record);
return 0;
}
std::vector<Record> execute_(const std::string& sql) {
std::vector<Record> response;
auto db = open_db_();
char* error;
int rc = sqlite3_exec(db, sql.data(), &callback_, &response, &error);
if (rc != SQLITE_OK) {
auto error_string = std::string{error};
sqlite3_free(error);
throw PriorityDBException{error_string};
}
return response;
}
fs::path db_path_;
std::string db_string_;
std::string table_name_;
};
TEST_F(DBFixture, EmptyDBTest) {
EXPECT_FALSE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructDBTest) {
ASSERT_FALSE(fs::exists(db_path_));
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
EXPECT_TRUE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructDBNoDestructTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
EXPECT_TRUE(fs::exists(db_path_));
}
EXPECT_TRUE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructDBMultipleTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
}
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
EXPECT_TRUE(fs::exists(db_path_));
}
EXPECT_TRUE(fs::exists(db_path_));
}
TEST_F(DBFixture, ConstructThrowTest) {
bool thrown = false;
try {
PriorityDB db{DEFAULT_MAX_SIZE, (fs::temp_directory_path() / fs::path{""}).native()};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"unable to open database file"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, ConstructCurrentThrowTest) {
bool thrown = false;
try {
PriorityDB db{DEFAULT_MAX_SIZE, (fs::temp_directory_path() / fs::path{"."}).native()};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"unable to open database file"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, ConstructParentThrowTest) {
bool thrown = false;
try {
PriorityDB db{DEFAULT_MAX_SIZE, (fs::temp_directory_path() / fs::path{".."}).native()};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"unable to open database file"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, ConstructZeroSpaceTest) {
bool thrown = false;
try {
PriorityDB db{0LL, db_string_};
} catch (const PriorityDBException& e) {
thrown = true;
EXPECT_EQ(std::string{"Must specify a nonzero max_size"},
std::string{e.what()});
}
EXPECT_TRUE(thrown);
}
TEST_F(DBFixture, InitialDBTest) {
ASSERT_FALSE(fs::exists(db_path_));
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='"
<< table_name_
<< "';";
auto response = execute_(stream.str());
ASSERT_EQ(1, response.size());
auto record = response[0];
ASSERT_EQ(1, record.size());
ASSERT_NE(record.end(), record.find("name"));
EXPECT_EQ(std::string{"prism_data"}, record["name"]);
}
TEST_F(DBFixture, InitialEmptyDBTest) {
ASSERT_FALSE(fs::exists(db_path_));
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
EXPECT_EQ(0, response.size());
}
TEST_F(DBFixture, InitialDBAfterDestructorTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
}
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT name FROM sqlite_master WHERE type='table' AND name='"
<< table_name_
<< "';";
auto response = execute_(stream.str());
ASSERT_EQ(1, response.size());
auto record = response[0];
ASSERT_EQ(1, record.size());
ASSERT_NE(record.end(), record.find("name"));
EXPECT_EQ(std::string{"prism_data"}, record["name"]);
}
TEST_F(DBFixture, InitialEmptyDBAfterDestructorTest) {
ASSERT_FALSE(fs::exists(db_path_));
{
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
ASSERT_TRUE(fs::exists(db_path_));
}
ASSERT_TRUE(fs::exists(db_path_));
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
EXPECT_EQ(0, response.size());
}
TEST_F(DBFixture, InsertEmptyHashTest) {
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
db.Insert(1, "", 5, false);
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
ASSERT_EQ(0, response.size());
}
TEST_F(DBFixture, InsertSingleTest) {
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
db.Insert(1, "hash", 5, false);
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
ASSERT_EQ(1, response.size());
auto record = response[0];
ASSERT_EQ(5, record.size());
EXPECT_EQ(1, std::stoi(record["id"]));
EXPECT_EQ(1, std::stoi(record["priority"]));
EXPECT_EQ(std::string{"hash"}, record["hash"]);
EXPECT_EQ(false, std::stoi(record["on_disk"]));
}
TEST_F(DBFixture, InsertCoupleTest) {
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
db.Insert(1, "hash", 5, false);
db.Insert(3, "hashbrowns", 10, true);
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
for (auto& record : response) {
for (auto item = record.begin(); item != record.end(); ++item) {
std::cout << item->first << ": " << item->second << std::endl;
}
}
ASSERT_EQ(2, response.size());
{
auto record = response[0];
ASSERT_EQ(5, record.size());
EXPECT_EQ(1, std::stoi(record["id"]));
EXPECT_EQ(1, std::stoi(record["priority"]));
EXPECT_EQ(std::string{"hash"}, record["hash"]);
EXPECT_EQ(5, std::stoi(record["size"]));
EXPECT_EQ(false, std::stoi(record["on_disk"]));
}
{
auto record = response[1];
ASSERT_EQ(5, record.size());
EXPECT_EQ(2, std::stoi(record["id"]));
EXPECT_EQ(3, std::stoi(record["priority"]));
EXPECT_EQ(std::string{"hashbrowns"}, record["hash"]);
EXPECT_EQ(10, std::stoi(record["size"]));
EXPECT_EQ(true, std::stoi(record["on_disk"]));
}
}
TEST_F(DBFixture, InsertManyTest) {
PriorityDB db{DEFAULT_MAX_SIZE, db_string_};
auto number_of_records = 100;
for (int i = 0; i < number_of_records; ++i) {
db.Insert(i, std::to_string(i * i), i * 2, i % 2);
}
std::stringstream stream;
stream << "SELECT * FROM "
<< table_name_
<< ";";
auto response = execute_(stream.str());
ASSERT_EQ(number_of_records, response.size());
for (int i = 0; i < number_of_records; ++i) {
auto record = response[i];
ASSERT_EQ(5, record.size());
EXPECT_EQ(i + 1, std::stoi(record["id"]));
EXPECT_EQ(i, std::stoi(record["priority"]));
EXPECT_EQ(std::to_string(i * i), record["hash"]);
EXPECT_EQ(i * 2, std::stoi(record["size"]));
EXPECT_EQ(i % 2, std::stoi(record["on_disk"]));
}
}
<|endoftext|> |
<commit_before>#ifndef __STAN__IO__STAN_CSV_READER_HPP__
#define __STAN__IO__STAN_CSV_READER_HPP__
#include <istream>
#include <iostream>
#include <sstream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <stan/math/matrix.hpp>
namespace stan {
namespace io {
// FIXME: should consolidate with the options from the command line in stan::gm
struct stan_csv_metadata {
int stan_version_major;
int stan_version_minor;
int stan_version_patch;
std::string model;
std::string data;
std::string init;
bool append_samples;
bool save_warmup;
size_t seed;
bool random_seed;
size_t chain_id;
size_t iter;
size_t warmup;
size_t thin;
bool equal_step_sizes;
bool nondiag_mass;
int leapfrog_steps;
int max_treedepth;
double epsilon;
double epsilon_pm;
double delta;
double gamma;
std::string algorithm;
};
struct stan_csv_adaptation {
double step_size;
Eigen::MatrixXd metric;
};
struct stan_csv_timing {
double warmup;
double sampling;
};
struct stan_csv {
stan_csv_metadata metadata;
Eigen::Matrix<std::string, Eigen::Dynamic, 1> header;
stan_csv_adaptation adaptation;
Eigen::MatrixXd samples;
stan_csv_timing timing;
};
/**
* Reads from a Stan output csv file.
*/
class stan_csv_reader {
public:
stan_csv_reader() {}
~stan_csv_reader() {}
static bool read_metadata(std::istream& in, stan_csv_metadata& metadata) {
std::stringstream ss;
std::string line;
if (in.peek() != '#')
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << '\n';
}
ss.seekg(std::ios_base::beg);
char comment;
std::string lhs;
// Skip first two lines
std::getline(ss, line);
std::getline(ss, line);
while (ss.good()) {
ss >> comment;
std::getline(ss, lhs, '=');
boost::trim(lhs);
if (lhs.compare("") == 0) { // no-op
} else if (lhs.compare("stan_version_major") == 0) {
ss >> metadata.stan_version_major;
} else if (lhs.compare("stan_version_minor") == 0) {
ss >> metadata.stan_version_minor;
} else if (lhs.compare("stan_version_patch") == 0) {
ss >> metadata.stan_version_patch;
} else if (lhs.compare("model") == 0) {
ss >> metadata.model;
} else if (lhs.compare("data") == 0) {
ss >> metadata.data;
} else if (lhs.compare("init") == 0) {
std::getline(ss, metadata.init);
boost::trim(metadata.init);
ss.unget();
} else if (lhs.compare("append_samples") == 0) {
ss >> metadata.append_samples;
} else if (lhs.compare("save_warmup") == 0) {
ss >> metadata.save_warmup;
} else if (lhs.compare("seed") == 0) {
ss >> metadata.seed;
metadata.random_seed = false;
} else if (lhs.compare("chain_id") == 0) {
ss >> metadata.chain_id;
} else if (lhs.compare("iter") == 0) {
ss >> metadata.iter;
} else if (lhs.compare("warmup") == 0) {
ss >> metadata.warmup;
} else if (lhs.compare("thin") == 0) {
ss >> metadata.thin;
} else if (lhs.compare("equal_step_sizes") == 0) {
ss >> metadata.equal_step_sizes;
} else if (lhs.compare("nondiag_mass") == 0) {
ss >> metadata.nondiag_mass;
} else if (lhs.compare("leapfrog_steps") == 0) {
ss >> metadata.leapfrog_steps;
} else if (lhs.compare("max_treedepth") == 0) {
ss >> metadata.max_treedepth;
} else if (lhs.compare("epsilon") == 0) {
ss >> metadata.epsilon;
} else if (lhs.compare("epsilon_pm") == 0) {
ss >> metadata.epsilon_pm;
} else if (lhs.compare("delta") == 0) {
ss >> metadata.delta;
} else if (lhs.compare("gamma") == 0) {
ss >> metadata.gamma;
} else if (lhs.compare("algorithm") == 0) {
std::getline(ss, metadata.algorithm);
boost::trim(metadata.algorithm);
ss.unget();
} else {
std::cout << "unused option: " << lhs << std::endl;
}
std::getline(ss, line);
}
if (ss.good() == true)
return false;
return true;
} // read_metadata
static bool read_header(std::istream& in, Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header) {
std::string line;
if (in.peek() != 'l')
return false;
std::getline(in, line);
std::stringstream ss(line);
header.resize(std::count(line.begin(), line.end(), ',') + 1);
int idx = 0;
while (ss.good()) {
std::string token;
std::getline(ss, token, ',');
boost::trim(token);
int pos = token.find('.');
if (pos > 0) {
token.replace(pos, 1, "[");
std::replace(token.begin(), token.end(), '.', ',');
token += "]";
}
header(idx++) = token;
}
return true;
}
static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation) {
std::stringstream ss;
std::string line;
int lines = 0;
if (in.peek() != '#' || in.good() == false)
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << std::endl;
lines++;
}
ss.seekg(std::ios_base::beg);
char comment; // Buffer for comment indicator, #
// Skip first two lines
std::getline(ss, line);
// Stepsize
std::getline(ss, line, '=');
boost::trim(line);
ss >> adaptation.step_size;
// Metric parameters
std::getline(ss, line);
std::getline(ss, line);
std::getline(ss, line);
int rows = lines - 3;
int cols = std::count(line.begin(), line.end(), ',') + 1;
adaptation.metric.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::stringstream line_ss;
line_ss.str(line);
line_ss >> comment;
for (int col = 0; col < cols; col++) {
std::string token;
std::getline(line_ss, token, ',');
boost::trim(token);
adaptation.metric(row, col) = boost::lexical_cast<double>(token);
}
std::getline(ss, line); // Read in next line
}
if (ss.good())
return false;
else
return true;
}
static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing) {
std::stringstream ss;
std::string line;
int rows = 0;
int cols = -1;
if (in.peek() == '#' || in.good() == false)
return false;
while (in.good()) {
bool comment_line = (in.peek() == '#');
bool empty_line = (in.peek() == '\n');
std::getline(in, line);
if (empty_line) continue;
if (!line.length()) break;
if (comment_line) {
if (line.find("(Warm-up)") != std::string::npos) {
int left = 16;
int right = line.find(" seconds");
timing.warmup += boost::lexical_cast<double>(line.substr(left, right - left));
} else if (line.find("(Sampling)") != std::string::npos) {
int left = 16;
int right = line.find(" seconds");
timing.sampling += boost::lexical_cast<double>(line.substr(left, right - left));
}
}
else {
ss << line << '\n';
int current_cols = std::count(line.begin(), line.end(), ',') + 1;
if (cols == -1) {
cols = current_cols;
} else if (cols != current_cols) {
std::cout << "Error: expected " << cols << " columns, but found "
<< current_cols << " instead for row " << rows + 1 << std::endl;
return false;
}
rows++;
}
in.peek();
}
ss.seekg(std::ios_base::beg);
if (rows > 0) {
samples.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::getline(ss, line);
std::stringstream ls(line);
for (int col = 0; col < cols; col++) {
std::getline(ls, line, ',');
boost::trim(line);
samples(row, col) = boost::lexical_cast<double>(line);
}
}
}
return true;
}
/**
* Parses the file.
*
*/
static stan_csv parse(std::istream& in) {
stan_csv data;
if (!read_metadata(in, data.metadata)) {
std::cout << "Warning: non-fatal error reading metadata" << std::endl;
}
if (!read_header(in, data.header)) {
std::cout << "Error: error reading header" << std::endl;
throw std::invalid_argument("Error with header of input file in parse");
}
if (!read_adaptation(in, data.adaptation)) {
std::cout << "Warning: non-fatal error reading adapation data" << std::endl;
}
data.timing.warmup = 0;
data.timing.sampling = 0;
if (!read_samples(in, data.samples, data.timing)) {
std::cout << "Warning: non-fatal error reading samples" << std::endl;
}
return data;
}
};
} // io
} // stan
#endif
<commit_msg>adding default constructor for stan_csv_timing. Windows doesn't set the members to 0<commit_after>#ifndef __STAN__IO__STAN_CSV_READER_HPP__
#define __STAN__IO__STAN_CSV_READER_HPP__
#include <istream>
#include <iostream>
#include <sstream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <stan/math/matrix.hpp>
namespace stan {
namespace io {
// FIXME: should consolidate with the options from the command line in stan::gm
struct stan_csv_metadata {
int stan_version_major;
int stan_version_minor;
int stan_version_patch;
std::string model;
std::string data;
std::string init;
bool append_samples;
bool save_warmup;
size_t seed;
bool random_seed;
size_t chain_id;
size_t iter;
size_t warmup;
size_t thin;
bool equal_step_sizes;
bool nondiag_mass;
int leapfrog_steps;
int max_treedepth;
double epsilon;
double epsilon_pm;
double delta;
double gamma;
std::string algorithm;
};
struct stan_csv_adaptation {
double step_size;
Eigen::MatrixXd metric;
};
struct stan_csv_timing {
double warmup;
double sampling;
stan_csv_timing()
: warmup(0), sampling(0) { }
};
struct stan_csv {
stan_csv_metadata metadata;
Eigen::Matrix<std::string, Eigen::Dynamic, 1> header;
stan_csv_adaptation adaptation;
Eigen::MatrixXd samples;
stan_csv_timing timing;
};
/**
* Reads from a Stan output csv file.
*/
class stan_csv_reader {
public:
stan_csv_reader() {}
~stan_csv_reader() {}
static bool read_metadata(std::istream& in, stan_csv_metadata& metadata) {
std::stringstream ss;
std::string line;
if (in.peek() != '#')
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << '\n';
}
ss.seekg(std::ios_base::beg);
char comment;
std::string lhs;
// Skip first two lines
std::getline(ss, line);
std::getline(ss, line);
while (ss.good()) {
ss >> comment;
std::getline(ss, lhs, '=');
boost::trim(lhs);
if (lhs.compare("") == 0) { // no-op
} else if (lhs.compare("stan_version_major") == 0) {
ss >> metadata.stan_version_major;
} else if (lhs.compare("stan_version_minor") == 0) {
ss >> metadata.stan_version_minor;
} else if (lhs.compare("stan_version_patch") == 0) {
ss >> metadata.stan_version_patch;
} else if (lhs.compare("model") == 0) {
ss >> metadata.model;
} else if (lhs.compare("data") == 0) {
ss >> metadata.data;
} else if (lhs.compare("init") == 0) {
std::getline(ss, metadata.init);
boost::trim(metadata.init);
ss.unget();
} else if (lhs.compare("append_samples") == 0) {
ss >> metadata.append_samples;
} else if (lhs.compare("save_warmup") == 0) {
ss >> metadata.save_warmup;
} else if (lhs.compare("seed") == 0) {
ss >> metadata.seed;
metadata.random_seed = false;
} else if (lhs.compare("chain_id") == 0) {
ss >> metadata.chain_id;
} else if (lhs.compare("iter") == 0) {
ss >> metadata.iter;
} else if (lhs.compare("warmup") == 0) {
ss >> metadata.warmup;
} else if (lhs.compare("thin") == 0) {
ss >> metadata.thin;
} else if (lhs.compare("equal_step_sizes") == 0) {
ss >> metadata.equal_step_sizes;
} else if (lhs.compare("nondiag_mass") == 0) {
ss >> metadata.nondiag_mass;
} else if (lhs.compare("leapfrog_steps") == 0) {
ss >> metadata.leapfrog_steps;
} else if (lhs.compare("max_treedepth") == 0) {
ss >> metadata.max_treedepth;
} else if (lhs.compare("epsilon") == 0) {
ss >> metadata.epsilon;
} else if (lhs.compare("epsilon_pm") == 0) {
ss >> metadata.epsilon_pm;
} else if (lhs.compare("delta") == 0) {
ss >> metadata.delta;
} else if (lhs.compare("gamma") == 0) {
ss >> metadata.gamma;
} else if (lhs.compare("algorithm") == 0) {
std::getline(ss, metadata.algorithm);
boost::trim(metadata.algorithm);
ss.unget();
} else {
std::cout << "unused option: " << lhs << std::endl;
}
std::getline(ss, line);
}
if (ss.good() == true)
return false;
return true;
} // read_metadata
static bool read_header(std::istream& in, Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header) {
std::string line;
if (in.peek() != 'l')
return false;
std::getline(in, line);
std::stringstream ss(line);
header.resize(std::count(line.begin(), line.end(), ',') + 1);
int idx = 0;
while (ss.good()) {
std::string token;
std::getline(ss, token, ',');
boost::trim(token);
int pos = token.find('.');
if (pos > 0) {
token.replace(pos, 1, "[");
std::replace(token.begin(), token.end(), '.', ',');
token += "]";
}
header(idx++) = token;
}
return true;
}
static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation) {
std::stringstream ss;
std::string line;
int lines = 0;
if (in.peek() != '#' || in.good() == false)
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << std::endl;
lines++;
}
ss.seekg(std::ios_base::beg);
char comment; // Buffer for comment indicator, #
// Skip first two lines
std::getline(ss, line);
// Stepsize
std::getline(ss, line, '=');
boost::trim(line);
ss >> adaptation.step_size;
// Metric parameters
std::getline(ss, line);
std::getline(ss, line);
std::getline(ss, line);
int rows = lines - 3;
int cols = std::count(line.begin(), line.end(), ',') + 1;
adaptation.metric.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::stringstream line_ss;
line_ss.str(line);
line_ss >> comment;
for (int col = 0; col < cols; col++) {
std::string token;
std::getline(line_ss, token, ',');
boost::trim(token);
adaptation.metric(row, col) = boost::lexical_cast<double>(token);
}
std::getline(ss, line); // Read in next line
}
if (ss.good())
return false;
else
return true;
}
static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing) {
std::stringstream ss;
std::string line;
int rows = 0;
int cols = -1;
if (in.peek() == '#' || in.good() == false)
return false;
while (in.good()) {
bool comment_line = (in.peek() == '#');
bool empty_line = (in.peek() == '\n');
std::getline(in, line);
if (empty_line) continue;
if (!line.length()) break;
if (comment_line) {
if (line.find("(Warm-up)") != std::string::npos) {
int left = 16;
int right = line.find(" seconds");
timing.warmup += boost::lexical_cast<double>(line.substr(left, right - left));
} else if (line.find("(Sampling)") != std::string::npos) {
int left = 16;
int right = line.find(" seconds");
timing.sampling += boost::lexical_cast<double>(line.substr(left, right - left));
}
}
else {
ss << line << '\n';
int current_cols = std::count(line.begin(), line.end(), ',') + 1;
if (cols == -1) {
cols = current_cols;
} else if (cols != current_cols) {
std::cout << "Error: expected " << cols << " columns, but found "
<< current_cols << " instead for row " << rows + 1 << std::endl;
return false;
}
rows++;
}
in.peek();
}
ss.seekg(std::ios_base::beg);
if (rows > 0) {
samples.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::getline(ss, line);
std::stringstream ls(line);
for (int col = 0; col < cols; col++) {
std::getline(ls, line, ',');
boost::trim(line);
//std::cout << "line: !" << line << "@" << std::endl;
samples(row, col) = boost::lexical_cast<double>(line);
//std::cout << "after" << std::endl << std::endl;
}
}
}
return true;
}
/**
* Parses the file.
*
*/
static stan_csv parse(std::istream& in) {
stan_csv data;
if (!read_metadata(in, data.metadata)) {
std::cout << "Warning: non-fatal error reading metadata" << std::endl;
}
if (!read_header(in, data.header)) {
std::cout << "Error: error reading header" << std::endl;
throw std::invalid_argument("Error with header of input file in parse");
}
if (!read_adaptation(in, data.adaptation)) {
std::cout << "Warning: non-fatal error reading adapation data" << std::endl;
}
data.timing.warmup = 0;
data.timing.sampling = 0;
if (!read_samples(in, data.samples, data.timing)) {
std::cout << "Warning: non-fatal error reading samples" << std::endl;
}
return data;
}
};
} // io
} // stan
#endif
<|endoftext|> |
<commit_before>#include "VirtualMachine.h"
VirtualMachine::VirtualMachine()
{
//ctor
stackSize = 0;
}
VirtualMachine::~VirtualMachine()
{
//dtor
}
void VirtualMachine::interpret(unsigned char bytecode[], int byteSize)
{
for(int a = 0; a < byteSize; a++)
{
int currentInstruction = bytecode[a];
switch(currentInstruction)
{
case Instruction::CONSOLE_OUT:
{
Type variable = pop();
switch(variable.type)
{
case DataType::INT:
std::cout << variable.intData;
break;
case DataType::CHAR:
std::cout << variable.charData;
break;
case DataType::BOOL:
std::cout << variable.boolData;
break;
case DataType::STRING:
std::cout << *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_OUT, Unknown data type '" + std::to_string(variable.type) + "'"));
}
}
break;
case Instruction::CREATE_INT:
push_integer(bytecode[++a]);
break;
case Instruction::CREATE_CHAR:
push_char(bytecode[++a]);
break;
case Instruction::CREATE_BOOL:
push_bool(bytecode[++a]);
break;
case Instruction::CREATE_STRING:
{
unsigned int stringSize = bytecode[++a]; //String length stored in next byte
std::string wholeString;
wholeString.resize(stringSize);
for(unsigned int cChar = 0; cChar < stringSize; cChar++) //Read in the string from the bytecode into the allocated memory
wholeString[cChar] = bytecode[++a];
push_string(wholeString); //Push the resulting char*
break;
}
case Instruction::GOTO:
a = static_cast<int>(bytecode[a+1])-1;
break;
case Instruction::CONSOLE_IN:
{
Type &variable = stack[bytecode[++a]];
switch(variable.type)
{
case DataType::INT:
std::cin >> variable.intData;
break;
case DataType::CHAR:
std::cin >> variable.charData;
break;
case DataType::BOOL:
std::cin >> variable.boolData;
break;
case DataType::STRING:
std::cin >> *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_IN, Unknown data type '" + std::to_string(variable.type) + "'"));
}
break;
}
case Instruction::MATH_ADD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result += *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_SUBTRACT:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result -= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MULTIPLY:
{
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result *= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_DIVIDE:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result /= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MOD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
{
result %= *iter;
}
push_integer(result); //Push the result to the stack
break;
}
case Instruction::CLONE_TOP:
{
push_type(stack[bytecode[++a]]); //Clone a variable from a position in the stack to the top of the stack
break;
}
case Instruction::CONCENTRATE_STRINGS:
{
//Pop strings off first that need to be concentrated
unsigned int numberOfStrings = bytecode[++a];
std::string stringBuffer;
std::vector<std::string> poppedStrings;
for(unsigned int a = 0; a < numberOfStrings; a++)
poppedStrings.emplace_back(*pop().stringData);
//Now add the strings to a buffer in reverse, as we need the first one to be first in the string, not last
for(auto iter = poppedStrings.rbegin(); iter != poppedStrings.rend(); iter++)
stringBuffer += *iter;
//Push to stack
push_string(stringBuffer);
break;
}
case Instruction::COMPARE_VALUES:
{
std::cout << "\nVALUE COMPARE";
a++; //Skip number of things to compare, not currently used
//Pop off the things that we're comparing
Type val1 = pop();
Type val2 = pop();
//Ensure that they're the same type or the union comparison will screw up
if(val2.type != val1.type)
{
throwError("Can't compare different data types!");
}
//Compare different things depending on the variable types
switch(val1.type)
{
case INT:
if(val1.intData == val2.intData)
push_bool(true);
else
push_bool(false);
break;
case CHAR:
if(val1.charData == val2.charData)
push_bool(true);
else
push_bool(false);
break;
case STRING:
if(*val1.stringData == *val2.stringData)
push_bool(true);
else
push_bool(false);
break;
case BOOL:
if(val1.boolData == val2.boolData)
push_bool(true);
else
push_bool(false);
default:
throwError("Internal error, attempt to compare unknown data type!");
}
break;
}
case Instruction::CONDITIONAL_IF:
{
std::cout << "\nIF";
//Move bytecode offset to the one specified in the bytecode.
//bytecode[a+1] = position to set if false
Type val = pop();
if(val.type != DataType::BOOL)
{
throwError(std::string("Can't convert type " + std::to_string(val.type) + " to boolean for comparison"));
}
if(!val.boolData)
{
a = bytecode[a+1];
}
else //Else move past the false position and continue running the bytecode
{
a++;
}
break;
}
case Instruction::SET_VARIABLE:
{
Type val = pop(); //Value to set it to
unsigned int variableStackOffset = bytecode[++a]; //Find which variable to set
stack[variableStackOffset] = val; //Update the value
break;
}
default:
throwError("Unknown instruction '" + std::to_string(currentInstruction) + "'");
}
}
}
void VirtualMachine::push_integer(int value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_char(unsigned char value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_bool(bool value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_string(const std::string &value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_type(Type value)
{
pushStackCheck();
stack[stackSize++] = value;
}
Type VirtualMachine::pop()
{
popStackCheck();
return stack[--stackSize];
}
void VirtualMachine::popStackCheck()
{
if(stackSize == 0)
{
throwError("\nCouldn't pop from stack, stack empty!");
}
}
void VirtualMachine::pushStackCheck()
{
if(stackSize == maxStackSize)
{
throwError("\nCouldn't push to stack, stack full!");
}
}
void VirtualMachine::throwError(const std::string& reason)
{
throw std::string(reason);
}
<commit_msg>Removed couts<commit_after>#include "VirtualMachine.h"
VirtualMachine::VirtualMachine()
{
//ctor
stackSize = 0;
}
VirtualMachine::~VirtualMachine()
{
//dtor
}
void VirtualMachine::interpret(unsigned char bytecode[], int byteSize)
{
for(int a = 0; a < byteSize; a++)
{
int currentInstruction = bytecode[a];
switch(currentInstruction)
{
case Instruction::CONSOLE_OUT:
{
Type variable = pop();
switch(variable.type)
{
case DataType::INT:
std::cout << variable.intData;
break;
case DataType::CHAR:
std::cout << variable.charData;
break;
case DataType::BOOL:
std::cout << variable.boolData;
break;
case DataType::STRING:
std::cout << *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_OUT, Unknown data type '" + std::to_string(variable.type) + "'"));
}
}
break;
case Instruction::CREATE_INT:
push_integer(bytecode[++a]);
break;
case Instruction::CREATE_CHAR:
push_char(bytecode[++a]);
break;
case Instruction::CREATE_BOOL:
push_bool(bytecode[++a]);
break;
case Instruction::CREATE_STRING:
{
unsigned int stringSize = bytecode[++a]; //String length stored in next byte
std::string wholeString;
wholeString.resize(stringSize);
for(unsigned int cChar = 0; cChar < stringSize; cChar++) //Read in the string from the bytecode into the allocated memory
wholeString[cChar] = bytecode[++a];
push_string(wholeString); //Push the resulting char*
break;
}
case Instruction::GOTO:
a = static_cast<int>(bytecode[a+1])-1;
break;
case Instruction::CONSOLE_IN:
{
Type &variable = stack[bytecode[++a]];
switch(variable.type)
{
case DataType::INT:
std::cin >> variable.intData;
break;
case DataType::CHAR:
std::cin >> variable.charData;
break;
case DataType::BOOL:
std::cin >> variable.boolData;
break;
case DataType::STRING:
std::cin >> *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_IN, Unknown data type '" + std::to_string(variable.type) + "'"));
}
break;
}
case Instruction::MATH_ADD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result += *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_SUBTRACT:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result -= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MULTIPLY:
{
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result *= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_DIVIDE:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result /= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MOD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
{
result %= *iter;
}
push_integer(result); //Push the result to the stack
break;
}
case Instruction::CLONE_TOP:
{
push_type(stack[bytecode[++a]]); //Clone a variable from a position in the stack to the top of the stack
break;
}
case Instruction::CONCENTRATE_STRINGS:
{
//Pop strings off first that need to be concentrated
unsigned int numberOfStrings = bytecode[++a];
std::string stringBuffer;
std::vector<std::string> poppedStrings;
for(unsigned int a = 0; a < numberOfStrings; a++)
poppedStrings.emplace_back(*pop().stringData);
//Now add the strings to a buffer in reverse, as we need the first one to be first in the string, not last
for(auto iter = poppedStrings.rbegin(); iter != poppedStrings.rend(); iter++)
stringBuffer += *iter;
//Push to stack
push_string(stringBuffer);
break;
}
case Instruction::COMPARE_VALUES:
{
a++; //Skip number of things to compare, not currently used
//Pop off the things that we're comparing
Type val1 = pop();
Type val2 = pop();
//Ensure that they're the same type or the union comparison will screw up
if(val2.type != val1.type)
{
throwError("Can't compare different data types!");
}
//Compare different things depending on the variable types
switch(val1.type)
{
case INT:
if(val1.intData == val2.intData)
push_bool(true);
else
push_bool(false);
break;
case CHAR:
if(val1.charData == val2.charData)
push_bool(true);
else
push_bool(false);
break;
case STRING:
if(*val1.stringData == *val2.stringData)
push_bool(true);
else
push_bool(false);
break;
case BOOL:
if(val1.boolData == val2.boolData)
push_bool(true);
else
push_bool(false);
default:
throwError("Internal error, attempt to compare unknown data type!");
}
break;
}
case Instruction::CONDITIONAL_IF:
{
//Move bytecode offset to the one specified in the bytecode.
//bytecode[a+1] = position to set if false
Type val = pop();
if(val.type != DataType::BOOL)
{
throwError(std::string("Can't convert type " + std::to_string(val.type) + " to boolean for comparison"));
}
if(!val.boolData)
{
a = bytecode[a+1];
}
else //Else move past the false position and continue running the bytecode
{
a++;
}
break;
}
case Instruction::SET_VARIABLE:
{
Type val = pop(); //Value to set it to
unsigned int variableStackOffset = bytecode[++a]; //Find which variable to set
stack[variableStackOffset] = val; //Update the value
break;
}
default:
throwError("Unknown instruction '" + std::to_string(currentInstruction) + "'");
}
}
}
void VirtualMachine::push_integer(int value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_char(unsigned char value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_bool(bool value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_string(const std::string &value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_type(Type value)
{
pushStackCheck();
stack[stackSize++] = value;
}
Type VirtualMachine::pop()
{
popStackCheck();
return stack[--stackSize];
}
void VirtualMachine::popStackCheck()
{
if(stackSize == 0)
{
throwError("\nCouldn't pop from stack, stack empty!");
}
}
void VirtualMachine::pushStackCheck()
{
if(stackSize == maxStackSize)
{
throwError("\nCouldn't push to stack, stack full!");
}
}
void VirtualMachine::throwError(const std::string& reason)
{
throw std::string(reason);
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public :
void set_values (int, int);
int area() { return width*height; }
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main() {
Rectangle rect, rectb;
rect.set_values(3,4);
rectb.set_values(5,6);
cout << "area : " << rect.area() << endl;
cout << "area : " << rectb.area() << endl;
return 0;
}
<commit_msg>constructor of cpp<commit_after>#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public :
Rectangle (int,int);
int area() { return width*height; }
};
Rectangle::Rectangle (int x, int y) {
width = x;
height = y;
}
int main() {
Rectangle rect(3,4), rectb(5,6);
cout << "area : " << rect.area() << endl;
cout << "area : " << rectb.area() << endl;
return 0;
}
<|endoftext|> |
<commit_before>/**
* \file SphericalEngine.hpp
* \brief Header for GeographicLib::SphericalEngine class
*
* Copyright (c) Charles Karney (2011, 2012) <charles@karney.com> and licensed
* under the MIT/X11 License. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_SPHERICALENGINE_HPP)
#define GEOGRAPHICLIB_SPHERICALENGINE_HPP \
"$Id$"
#include <vector>
#include <istream>
#include <GeographicLib/Constants.hpp>
#if defined(_MSC_VER)
// Squelch warnings about dll vs vector
#pragma warning (push)
#pragma warning (disable: 4251)
#endif
namespace GeographicLib {
class CircularEngine;
/**
* \brief The evaluation engine for SphericalHarmonic
*
* This serves as the backend to SphericalHarmonic, SphericalHarmonic1, and
* SphericalHarmonic2. Typically end-users will not have to access this
* class directly.
*
* See SphericalEngine.cpp for more information on the implementation.
*
* Example of use:
* \include example-SphericalEngine.cpp
**********************************************************************/
class GEOGRAPHIC_EXPORT SphericalEngine {
private:
typedef Math::real real;
// A table of the square roots of integers
static std::vector<real> root_;
friend class CircularEngine; // CircularEngine needs access to root_, scale_
// An internal scaling of the coefficients to avoid overflow in
// intermediate calculations.
static const real scale_;
// Move latitudes near the pole off the axis by this amount.
static const real eps_;
static const std::vector<real> Z_;
SphericalEngine(); // Disable constructor
public:
/**
* Supported normalizations for associated Legendre polynomials.
**********************************************************************/
enum normalization {
/**
* Fully normalized associated Legendre polynomials. See
* SphericalHarmonic::FULL for documentation.
*
* @hideinitializer
**********************************************************************/
FULL = 0,
/**
* Schmidt semi-normalized associated Legendre polynomials. See
* SphericalHarmonic::SCHMIDT for documentation.
*
* @hideinitializer
**********************************************************************/
SCHMIDT = 1,
/// \cond SKIP
// These are deprecated...
full = FULL,
schmidt = SCHMIDT,
/// \endcond
};
/**
* \brief Package up coefficients for SphericalEngine
*
* This packages up the \e C, \e S coefficients and information about how
* the coefficients are stored into a single structure. This allows a
* vector of type SphericalEngine::coeff to be passed to
* SphericalEngine::Value. This class also includes functions to aid
* indexing into \e C and \e S.
*
* The storage layout of the coefficients is documented in
* SphericalHarmonic and SphericalHarmonic::SphericalHarmonic.
**********************************************************************/
class GEOGRAPHIC_EXPORT coeff {
private:
int _N, _nmx, _mmx;
std::vector<real>::const_iterator _Cnm;
std::vector<real>::const_iterator _Snm;
public:
/**
* A default constructor
**********************************************************************/
coeff()
: _N(-1)
, _nmx(-1)
, _mmx(-1)
, _Cnm(Z_.begin())
, _Snm(Z_.begin()) {}
/**
* The general constructor.
*
* @param[in] C a vector of coefficients for the cosine terms.
* @param[in] S a vector of coefficients for the sine terms.
* @param[in] N the degree giving storage layout for \e C and \e S.
* @param[in] nmx the maximum degree to be used.
* @param[in] mmx the maximum order to be used.
*
* This requires \e N >= \e nmx >= \e mmx >= -1. \e C and \e S must also
* be large enough to hold the coefficients. Otherwise an exception is
* thrown.
**********************************************************************/
coeff(const std::vector<real>& C,
const std::vector<real>& S,
int N, int nmx, int mmx)
: _N(N)
, _nmx(nmx)
, _mmx(mmx)
, _Cnm(C.begin())
, _Snm(S.begin() - (_N + 1))
{
if (!(_N >= _nmx && _nmx >= _mmx && _mmx >= -1))
throw GeographicErr("Bad indices for coeff");
if (!(index(_nmx, _mmx) < int(C.size()) &&
index(_nmx, _mmx) < int(S.size()) + (_N + 1)))
throw GeographicErr("Arrays too small in coeff");
SphericalEngine::RootTable(_nmx);
}
/**
* The constructor for full coefficient vectors.
*
* @param[in] C a vector of coefficients for the cosine terms.
* @param[in] S a vector of coefficients for the sine terms.
* @param[in] N the maximum degree and order.
*
* This requires \e N >= -1. \e C and \e S must also be large enough to
* hold the coefficients. Otherwise an exception is thrown.
**********************************************************************/
coeff(const std::vector<real>& C,
const std::vector<real>& S,
int N)
: _N(N)
, _nmx(N)
, _mmx(N)
, _Cnm(C.begin())
, _Snm(S.begin() - (_N + 1))
{
if (!(_N >= -1))
throw GeographicErr("Bad indices for coeff");
if (!(index(_nmx, _mmx) < int(C.size()) &&
index(_nmx, _mmx) < int(S.size()) + (_N + 1)))
throw GeographicErr("Arrays too small in coeff");
SphericalEngine::RootTable(_nmx);
}
/**
* @return \e N the degree giving storage layout for \e C and \e S.
**********************************************************************/
inline int N() const throw() { return _N; }
/**
* @return \e nmx the maximum degree to be used.
**********************************************************************/
inline int nmx() const throw() { return _nmx; }
/**
* @return \e mmx the maximum order to be used.
**********************************************************************/
inline int mmx() const throw() { return _mmx; }
/**
* The one-dimensional index into \e C and \e S.
*
* @param[in] n the degree.
* @param[in] m the order.
* @return the one-dimensional index.
**********************************************************************/
inline int index(int n, int m) const throw()
{ return m * _N - m * (m - 1) / 2 + n; }
/**
* An element of \e C.
*
* @param[in] k the one-dimensional index.
* @return the value of the \e C coefficient.
**********************************************************************/
inline Math::real Cv(int k) const { return *(_Cnm + k); }
/**
* An element of \e S.
*
* @param[in] k the one-dimensional index.
* @return the value of the \e S coefficient.
**********************************************************************/
inline Math::real Sv(int k) const { return *(_Snm + k); }
/**
* An element of \e C with checking.
*
* @param[in] k the one-dimensional index.
* @param[in] n the requested degree.
* @param[in] m the requested order.
* @param[in] f a multiplier.
* @return the value of the \e C coefficient multiplied by \e f in \e n
* and \e m are in range else 0.
**********************************************************************/
inline Math::real Cv(int k, int n, int m, real f) const
{ return m > _mmx || n > _nmx ? 0 : *(_Cnm + k) * f; }
/**
* An element of \e S with checking.
*
* @param[in] k the one-dimensional index.
* @param[in] n the requested degree.
* @param[in] m the requested order.
* @param[in] f a multiplier.
* @return the value of the \e S coefficient multiplied by \e f in \e n
* and \e m are in range else 0.
**********************************************************************/
inline Math::real Sv(int k, int n, int m, real f) const
{ return m > _mmx || n > _nmx ? 0 : *(_Snm + k) * f; }
/**
* The size of the coefficient vector for the cosine terms.
*
* @param[in] N the maximum degree.
* @param[in] M the maximum order.
* @return the size of the vector of cosine terms as stored in column
* major order.
**********************************************************************/
static inline int Csize(int N, int M)
{ return (M + 1) * (2 * N - M + 2) / 2; }
/**
* The size of the coefficient vector for the sine terms.
*
* @param[in] N the maximum degree.
* @param[in] M the maximum order.
* @return the size of the vector of cosine terms as stored in column
* major order.
**********************************************************************/
static inline int Ssize(int N, int M)
{ return Csize(N, M) - (N + 1); }
/**
* Load coefficients from a binary stream.
*
* @param[in] stream the input stream.
* @param[out] N The maximum degree of the coefficients.
* @param[out] M The maximum order of the coefficients.
* @param[out] C The vector of cosine coefficients.
* @param[out] S The vector of sine coefficients.
*
* \e N and \e M are read as 4-byte ints. \e C and \e S are resized to
* accommodate all the coefficients (with the \e m = 0 coefficients for
* \e S excluded) and the data for these coefficients read as 8-byte
* doubles. The coefficients are stored in column major order. The
* bytes in the stream should use little-endian ordering. IEEE floating
* point is assumed for the coefficients.
**********************************************************************/
static void readcoeffs(std::istream& stream, int& N, int& M,
std::vector<real>& C, std::vector<real>& S);
};
/**
* Evaluate a spherical harmonic sum and its gradient.
*
* @tparam gradp should the gradient be calculated.
* @tparam norm the normalization for the associated Legendre polynomials.
* @tparam L the number of terms in the coefficients.
* @param[in] c an array of coeff objects.
* @param[in] f array of coefficient multipliers. f[0] should be 1.
* @param[in] x the \e x component of the cartesian position.
* @param[in] y the \e y component of the cartesian position.
* @param[in] z the \e z component of the cartesian position.
* @param[in] a the normalizing radius.
* @param[out] gradx the \e x component of the gradient.
* @param[out] grady the \e y component of the gradient.
* @param[out] gradz the \e z component of the gradient.
* @result the spherical harmonic sum.
*
* See the SphericalHarmonic class for the definition of the sum.
* The coefficients used by this function are, for example,
* c[0].Cv + f[1] * c[1].Cv + ... + f[L-1] * c[L-1].Cv. (Note
* that f[0] is \e not used.) The upper limits on the sum are
* determined by c[0].nmx() and c[0].mmx(); these limits apply to
* \e all the components of the coefficients. The parameters \e
* gradp, \e norm, and \e L are template parameters, to allow more
* optimization to be done at compile time.
*
* Clenshaw summation is used which permits the evaluation of the sum
* without the need to allocate temporary arrays. Thus this function never
* throws an exception.
**********************************************************************/
template<bool gradp, normalization norm, int L>
static Math::real Value(const coeff c[], const real f[],
real x, real y, real z, real a,
real& gradx, real& grady, real& gradz) throw();
/**
* Create a CircularEngine object
*
* @tparam gradp should the gradient be calculated.
* @tparam norm the normalization for the associated Legendre polynomials.
* @tparam L the number of terms in the coefficients.
* @param[in] c an array of coeff objects.
* @param[in] f array of coefficient multipliers. f[0] should be 1.
* @param[in] p the radius of the circle = sqrt(<i>x</i><sup>2</sup> +
* <i>y</i><sup>2</sup>).
* @param[in] z the height of the circle.
* @param[in] a the normalizing radius.
* @result the CircularEngine object.
*
* If you need to evaluate the spherical harmonic sum for several points
* with constant \e f, \e p = sqrt(<i>x</i><sup>2</sup> +
* <i>y</i><sup>2</sup>), \e z, and \e a, it is more efficient to construct
* call SphericalEngine::Circle to give a CircularEngine object and then
* call CircularEngine::operator()() with arguments <i>x</i>/\e p and
* <i>y</i>/\e p.
**********************************************************************/
template<bool gradp, normalization norm, int L>
static CircularEngine Circle(const coeff c[], const real f[],
real p, real z, real a);
/**
* Check that the static table of square roots is big enough and enlarge it
* if necessary.
*
* @param[in] N the maximum degree to be used in SphericalEngine.
*
* Typically, there's no need for an end-user to call this routine, because
* the constructors for SphericalEngine::coeff do so. However, since this
* updates a static table, there's a possible race condition in a
* multi-threaded environment. Because this routine does nothing if the
* table is already large enough, one way to avoid race conditions is to
* call this routine at program start up (when it's still single threaded),
* supplying the largest degree that your program will use. E.g.,
\code
GeographicLib::SphericalEngine::RootTable(2190);
\endcode
* suffices to accommodate extant magnetic and gravity models.
**********************************************************************/
static void RootTable(int N);
/**
* Clear the static table of square roots and release the memory. Call
* this only when you are sure you no longer will be using SphericalEngine.
* Your program will crash if you call SphericalEngine after calling this
* routine. <b>It's safest not to call this routine at all.</b> (The space
* used by the table is modest.)
**********************************************************************/
static void ClearRootTable() {
std::vector<real> temp(0);
root_.swap(temp);
}
};
} // namespace GeographicLib
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#endif // GEOGRAPHICLIB_SPHERICALENGINE_HPP
<commit_msg>SphericalEngine: work around Visual Studio 9's agressive checking of iterators.<commit_after>/**
* \file SphericalEngine.hpp
* \brief Header for GeographicLib::SphericalEngine class
*
* Copyright (c) Charles Karney (2011, 2012) <charles@karney.com> and licensed
* under the MIT/X11 License. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_SPHERICALENGINE_HPP)
#define GEOGRAPHICLIB_SPHERICALENGINE_HPP \
"$Id$"
#include <vector>
#include <istream>
#include <GeographicLib/Constants.hpp>
#if defined(_MSC_VER)
// Squelch warnings about dll vs vector
#pragma warning (push)
#pragma warning (disable: 4251)
#endif
namespace GeographicLib {
class CircularEngine;
/**
* \brief The evaluation engine for SphericalHarmonic
*
* This serves as the backend to SphericalHarmonic, SphericalHarmonic1, and
* SphericalHarmonic2. Typically end-users will not have to access this
* class directly.
*
* See SphericalEngine.cpp for more information on the implementation.
*
* Example of use:
* \include example-SphericalEngine.cpp
**********************************************************************/
class GEOGRAPHIC_EXPORT SphericalEngine {
private:
typedef Math::real real;
// A table of the square roots of integers
static std::vector<real> root_;
friend class CircularEngine; // CircularEngine needs access to root_, scale_
// An internal scaling of the coefficients to avoid overflow in
// intermediate calculations.
static const real scale_;
// Move latitudes near the pole off the axis by this amount.
static const real eps_;
static const std::vector<real> Z_;
SphericalEngine(); // Disable constructor
public:
/**
* Supported normalizations for associated Legendre polynomials.
**********************************************************************/
enum normalization {
/**
* Fully normalized associated Legendre polynomials. See
* SphericalHarmonic::FULL for documentation.
*
* @hideinitializer
**********************************************************************/
FULL = 0,
/**
* Schmidt semi-normalized associated Legendre polynomials. See
* SphericalHarmonic::SCHMIDT for documentation.
*
* @hideinitializer
**********************************************************************/
SCHMIDT = 1,
/// \cond SKIP
// These are deprecated...
full = FULL,
schmidt = SCHMIDT,
/// \endcond
};
/**
* \brief Package up coefficients for SphericalEngine
*
* This packages up the \e C, \e S coefficients and information about how
* the coefficients are stored into a single structure. This allows a
* vector of type SphericalEngine::coeff to be passed to
* SphericalEngine::Value. This class also includes functions to aid
* indexing into \e C and \e S.
*
* The storage layout of the coefficients is documented in
* SphericalHarmonic and SphericalHarmonic::SphericalHarmonic.
**********************************************************************/
class GEOGRAPHIC_EXPORT coeff {
private:
int _N, _nmx, _mmx;
std::vector<real>::const_iterator _Cnm;
std::vector<real>::const_iterator _Snm;
public:
/**
* A default constructor
**********************************************************************/
coeff()
: _N(-1)
, _nmx(-1)
, _mmx(-1)
, _Cnm(Z_.begin())
, _Snm(Z_.begin()) {}
/**
* The general constructor.
*
* @param[in] C a vector of coefficients for the cosine terms.
* @param[in] S a vector of coefficients for the sine terms.
* @param[in] N the degree giving storage layout for \e C and \e S.
* @param[in] nmx the maximum degree to be used.
* @param[in] mmx the maximum order to be used.
*
* This requires \e N >= \e nmx >= \e mmx >= -1. \e C and \e S must also
* be large enough to hold the coefficients. Otherwise an exception is
* thrown.
**********************************************************************/
coeff(const std::vector<real>& C,
const std::vector<real>& S,
int N, int nmx, int mmx)
: _N(N)
, _nmx(nmx)
, _mmx(mmx)
, _Cnm(C.begin())
, _Snm(S.begin())
{
if (!(_N >= _nmx && _nmx >= _mmx && _mmx >= -1))
throw GeographicErr("Bad indices for coeff");
if (!(index(_nmx, _mmx) < int(C.size()) &&
index(_nmx, _mmx) < int(S.size()) + (_N + 1)))
throw GeographicErr("Arrays too small in coeff");
SphericalEngine::RootTable(_nmx);
}
/**
* The constructor for full coefficient vectors.
*
* @param[in] C a vector of coefficients for the cosine terms.
* @param[in] S a vector of coefficients for the sine terms.
* @param[in] N the maximum degree and order.
*
* This requires \e N >= -1. \e C and \e S must also be large enough to
* hold the coefficients. Otherwise an exception is thrown.
**********************************************************************/
coeff(const std::vector<real>& C,
const std::vector<real>& S,
int N)
: _N(N)
, _nmx(N)
, _mmx(N)
, _Cnm(C.begin())
, _Snm(S.begin())
{
if (!(_N >= -1))
throw GeographicErr("Bad indices for coeff");
if (!(index(_nmx, _mmx) < int(C.size()) &&
index(_nmx, _mmx) < int(S.size()) + (_N + 1)))
throw GeographicErr("Arrays too small in coeff");
SphericalEngine::RootTable(_nmx);
}
/**
* @return \e N the degree giving storage layout for \e C and \e S.
**********************************************************************/
inline int N() const throw() { return _N; }
/**
* @return \e nmx the maximum degree to be used.
**********************************************************************/
inline int nmx() const throw() { return _nmx; }
/**
* @return \e mmx the maximum order to be used.
**********************************************************************/
inline int mmx() const throw() { return _mmx; }
/**
* The one-dimensional index into \e C and \e S.
*
* @param[in] n the degree.
* @param[in] m the order.
* @return the one-dimensional index.
**********************************************************************/
inline int index(int n, int m) const throw()
{ return m * _N - m * (m - 1) / 2 + n; }
/**
* An element of \e C.
*
* @param[in] k the one-dimensional index.
* @return the value of the \e C coefficient.
**********************************************************************/
inline Math::real Cv(int k) const { return *(_Cnm + k); }
/**
* An element of \e S.
*
* @param[in] k the one-dimensional index.
* @return the value of the \e S coefficient.
**********************************************************************/
inline Math::real Sv(int k) const { return *(_Snm + (k - (_N + 1))); }
/**
* An element of \e C with checking.
*
* @param[in] k the one-dimensional index.
* @param[in] n the requested degree.
* @param[in] m the requested order.
* @param[in] f a multiplier.
* @return the value of the \e C coefficient multiplied by \e f in \e n
* and \e m are in range else 0.
**********************************************************************/
inline Math::real Cv(int k, int n, int m, real f) const
{ return m > _mmx || n > _nmx ? 0 : *(_Cnm + k) * f; }
/**
* An element of \e S with checking.
*
* @param[in] k the one-dimensional index.
* @param[in] n the requested degree.
* @param[in] m the requested order.
* @param[in] f a multiplier.
* @return the value of the \e S coefficient multiplied by \e f in \e n
* and \e m are in range else 0.
**********************************************************************/
inline Math::real Sv(int k, int n, int m, real f) const
{ return m > _mmx || n > _nmx ? 0 : *(_Snm + (k - (_N + 1))) * f; }
/**
* The size of the coefficient vector for the cosine terms.
*
* @param[in] N the maximum degree.
* @param[in] M the maximum order.
* @return the size of the vector of cosine terms as stored in column
* major order.
**********************************************************************/
static inline int Csize(int N, int M)
{ return (M + 1) * (2 * N - M + 2) / 2; }
/**
* The size of the coefficient vector for the sine terms.
*
* @param[in] N the maximum degree.
* @param[in] M the maximum order.
* @return the size of the vector of cosine terms as stored in column
* major order.
**********************************************************************/
static inline int Ssize(int N, int M)
{ return Csize(N, M) - (N + 1); }
/**
* Load coefficients from a binary stream.
*
* @param[in] stream the input stream.
* @param[out] N The maximum degree of the coefficients.
* @param[out] M The maximum order of the coefficients.
* @param[out] C The vector of cosine coefficients.
* @param[out] S The vector of sine coefficients.
*
* \e N and \e M are read as 4-byte ints. \e C and \e S are resized to
* accommodate all the coefficients (with the \e m = 0 coefficients for
* \e S excluded) and the data for these coefficients read as 8-byte
* doubles. The coefficients are stored in column major order. The
* bytes in the stream should use little-endian ordering. IEEE floating
* point is assumed for the coefficients.
**********************************************************************/
static void readcoeffs(std::istream& stream, int& N, int& M,
std::vector<real>& C, std::vector<real>& S);
};
/**
* Evaluate a spherical harmonic sum and its gradient.
*
* @tparam gradp should the gradient be calculated.
* @tparam norm the normalization for the associated Legendre polynomials.
* @tparam L the number of terms in the coefficients.
* @param[in] c an array of coeff objects.
* @param[in] f array of coefficient multipliers. f[0] should be 1.
* @param[in] x the \e x component of the cartesian position.
* @param[in] y the \e y component of the cartesian position.
* @param[in] z the \e z component of the cartesian position.
* @param[in] a the normalizing radius.
* @param[out] gradx the \e x component of the gradient.
* @param[out] grady the \e y component of the gradient.
* @param[out] gradz the \e z component of the gradient.
* @result the spherical harmonic sum.
*
* See the SphericalHarmonic class for the definition of the sum.
* The coefficients used by this function are, for example,
* c[0].Cv + f[1] * c[1].Cv + ... + f[L-1] * c[L-1].Cv. (Note
* that f[0] is \e not used.) The upper limits on the sum are
* determined by c[0].nmx() and c[0].mmx(); these limits apply to
* \e all the components of the coefficients. The parameters \e
* gradp, \e norm, and \e L are template parameters, to allow more
* optimization to be done at compile time.
*
* Clenshaw summation is used which permits the evaluation of the sum
* without the need to allocate temporary arrays. Thus this function never
* throws an exception.
**********************************************************************/
template<bool gradp, normalization norm, int L>
static Math::real Value(const coeff c[], const real f[],
real x, real y, real z, real a,
real& gradx, real& grady, real& gradz) throw();
/**
* Create a CircularEngine object
*
* @tparam gradp should the gradient be calculated.
* @tparam norm the normalization for the associated Legendre polynomials.
* @tparam L the number of terms in the coefficients.
* @param[in] c an array of coeff objects.
* @param[in] f array of coefficient multipliers. f[0] should be 1.
* @param[in] p the radius of the circle = sqrt(<i>x</i><sup>2</sup> +
* <i>y</i><sup>2</sup>).
* @param[in] z the height of the circle.
* @param[in] a the normalizing radius.
* @result the CircularEngine object.
*
* If you need to evaluate the spherical harmonic sum for several points
* with constant \e f, \e p = sqrt(<i>x</i><sup>2</sup> +
* <i>y</i><sup>2</sup>), \e z, and \e a, it is more efficient to construct
* call SphericalEngine::Circle to give a CircularEngine object and then
* call CircularEngine::operator()() with arguments <i>x</i>/\e p and
* <i>y</i>/\e p.
**********************************************************************/
template<bool gradp, normalization norm, int L>
static CircularEngine Circle(const coeff c[], const real f[],
real p, real z, real a);
/**
* Check that the static table of square roots is big enough and enlarge it
* if necessary.
*
* @param[in] N the maximum degree to be used in SphericalEngine.
*
* Typically, there's no need for an end-user to call this routine, because
* the constructors for SphericalEngine::coeff do so. However, since this
* updates a static table, there's a possible race condition in a
* multi-threaded environment. Because this routine does nothing if the
* table is already large enough, one way to avoid race conditions is to
* call this routine at program start up (when it's still single threaded),
* supplying the largest degree that your program will use. E.g.,
\code
GeographicLib::SphericalEngine::RootTable(2190);
\endcode
* suffices to accommodate extant magnetic and gravity models.
**********************************************************************/
static void RootTable(int N);
/**
* Clear the static table of square roots and release the memory. Call
* this only when you are sure you no longer will be using SphericalEngine.
* Your program will crash if you call SphericalEngine after calling this
* routine. <b>It's safest not to call this routine at all.</b> (The space
* used by the table is modest.)
**********************************************************************/
static void ClearRootTable() {
std::vector<real> temp(0);
root_.swap(temp);
}
};
} // namespace GeographicLib
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#endif // GEOGRAPHICLIB_SPHERICALENGINE_HPP
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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/.
#include "main.h"
#if EIGEN_ALIGN
#define ALIGNMENT 16
#else
#define ALIGNMENT 1
#endif
void check_handmade_aligned_malloc()
{
for(int i = 1; i < 1000; i++)
{
char *p = (char*)internal::handmade_aligned_malloc(i);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
internal::handmade_aligned_free(p);
}
}
void check_aligned_malloc()
{
for(int i = 1; i < 1000; i++)
{
char *p = (char*)internal::aligned_malloc(i);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
internal::aligned_free(p);
}
}
void check_aligned_new()
{
for(int i = 1; i < 1000; i++)
{
float *p = internal::aligned_new<float>(i);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
internal::aligned_delete(p,i);
}
}
void check_aligned_stack_alloc()
{
for(int i = 1; i < 1000; i++)
{
ei_declare_aligned_stack_constructed_variable(float,p,i,0);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
}
}
// test compilation with both a struct and a class...
struct MyStruct
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
char dummychar;
Vector4f avec;
};
class MyClassA
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
char dummychar;
Vector4f avec;
};
template<typename T> void check_dynaligned()
{
T* obj = new T;
VERIFY(T::NeedsToAlign==1);
VERIFY(size_t(obj)%ALIGNMENT==0);
delete obj;
}
void test_dynalloc()
{
// low level dynamic memory allocation
CALL_SUBTEST(check_handmade_aligned_malloc());
CALL_SUBTEST(check_aligned_malloc());
CALL_SUBTEST(check_aligned_new());
CALL_SUBTEST(check_aligned_stack_alloc());
for (int i=0; i<g_repeat*100; ++i)
{
CALL_SUBTEST(check_dynaligned<Vector4f>() );
CALL_SUBTEST(check_dynaligned<Vector2d>() );
CALL_SUBTEST(check_dynaligned<Matrix4f>() );
CALL_SUBTEST(check_dynaligned<Vector4d>() );
CALL_SUBTEST(check_dynaligned<Vector4i>() );
}
// check static allocation, who knows ?
#if EIGEN_ALIGN_STATICALLY
{
MyStruct foo0; VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0);
MyClassA fooA; VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0);
}
// dynamic allocation, single object
for (int i=0; i<g_repeat*100; ++i)
{
MyStruct *foo0 = new MyStruct(); VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);
MyClassA *fooA = new MyClassA(); VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);
delete foo0;
delete fooA;
}
// dynamic allocation, array
const int N = 10;
for (int i=0; i<g_repeat*100; ++i)
{
MyStruct *foo0 = new MyStruct[N]; VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);
MyClassA *fooA = new MyClassA[N]; VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);
delete[] foo0;
delete[] fooA;
}
#endif
}
<commit_msg>Memory allocated on the stack is freed at the function exit, so reduce iteration count to avoid stack overflow (grafted from abaaebabbc07b00379f217fa68b37337ba29d607)<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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/.
#include "main.h"
#if EIGEN_ALIGN
#define ALIGNMENT 16
#else
#define ALIGNMENT 1
#endif
void check_handmade_aligned_malloc()
{
for(int i = 1; i < 1000; i++)
{
char *p = (char*)internal::handmade_aligned_malloc(i);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
internal::handmade_aligned_free(p);
}
}
void check_aligned_malloc()
{
for(int i = 1; i < 1000; i++)
{
char *p = (char*)internal::aligned_malloc(i);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
internal::aligned_free(p);
}
}
void check_aligned_new()
{
for(int i = 1; i < 1000; i++)
{
float *p = internal::aligned_new<float>(i);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
internal::aligned_delete(p,i);
}
}
void check_aligned_stack_alloc()
{
for(int i = 1; i < 400; i++)
{
ei_declare_aligned_stack_constructed_variable(float,p,i,0);
VERIFY(size_t(p)%ALIGNMENT==0);
// if the buffer is wrongly allocated this will give a bad write --> check with valgrind
for(int j = 0; j < i; j++) p[j]=0;
}
}
// test compilation with both a struct and a class...
struct MyStruct
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
char dummychar;
Vector4f avec;
};
class MyClassA
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
char dummychar;
Vector4f avec;
};
template<typename T> void check_dynaligned()
{
T* obj = new T;
VERIFY(T::NeedsToAlign==1);
VERIFY(size_t(obj)%ALIGNMENT==0);
delete obj;
}
void test_dynalloc()
{
// low level dynamic memory allocation
CALL_SUBTEST(check_handmade_aligned_malloc());
CALL_SUBTEST(check_aligned_malloc());
CALL_SUBTEST(check_aligned_new());
CALL_SUBTEST(check_aligned_stack_alloc());
for (int i=0; i<g_repeat*100; ++i)
{
CALL_SUBTEST(check_dynaligned<Vector4f>() );
CALL_SUBTEST(check_dynaligned<Vector2d>() );
CALL_SUBTEST(check_dynaligned<Matrix4f>() );
CALL_SUBTEST(check_dynaligned<Vector4d>() );
CALL_SUBTEST(check_dynaligned<Vector4i>() );
}
// check static allocation, who knows ?
#if EIGEN_ALIGN_STATICALLY
{
MyStruct foo0; VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0);
MyClassA fooA; VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0);
}
// dynamic allocation, single object
for (int i=0; i<g_repeat*100; ++i)
{
MyStruct *foo0 = new MyStruct(); VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);
MyClassA *fooA = new MyClassA(); VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);
delete foo0;
delete fooA;
}
// dynamic allocation, array
const int N = 10;
for (int i=0; i<g_repeat*100; ++i)
{
MyStruct *foo0 = new MyStruct[N]; VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);
MyClassA *fooA = new MyClassA[N]; VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);
delete[] foo0;
delete[] fooA;
}
#endif
}
<|endoftext|> |
<commit_before>#define SOL_CHECK_ARGUMENTS
#include <sol.hpp>
#include <vector>
#include <iostream>
int main(int, char**) {
std::cout << "=== containers example ===" << std::endl;
sol::state lua;
lua.open_libraries();
lua.script(R"(
function f (x)
print('--- Calling f ---')
for k, v in pairs(x) do
print(k, v)
end
end
)");
// Have the function we
// just defined in Lua
sol::function f = lua["f"];
// Set a global variable called
// "arr" to be a vector of 5 lements
lua["arr"] = std::vector<int>{ 2, 4, 6, 8, 10 };
// Call it, see 5 elements
// printed out
f(lua["arr"]);
// Mess with it in C++
// Containers are stored as userdata, unless you
// use `sol::as_table()` and `sol::as_table_t`.
std::vector<int>& reference_to_arr = lua["arr"];
reference_to_arr.push_back(12);
// Call it, see *6* elements
// printed out
f(lua["arr"]);
std::cout << std::endl;
return 0;
}<commit_msg>sigh, Lua 5.1<commit_after>#define SOL_CHECK_ARGUMENTS
#include <sol.hpp>
#include <vector>
#include <iostream>
int main(int, char**) {
std::cout << "=== containers example ===" << std::endl;
sol::state lua;
lua.open_libraries();
lua.script(R"(
function f (x)
print("container has:")
for k=1,#x do
v = x[k]
print("\t", k, v)
end
print()
end
)");
// Have the function we
// just defined in Lua
sol::function f = lua["f"];
// Set a global variable called
// "arr" to be a vector of 5 lements
lua["arr"] = std::vector<int>{ 2, 4, 6, 8, 10 };
// Call it, see 5 elements
// printed out
f(lua["arr"]);
// Mess with it in C++
// Containers are stored as userdata, unless you
// use `sol::as_table()` and `sol::as_table_t`.
std::vector<int>& reference_to_arr = lua["arr"];
reference_to_arr.push_back(12);
// Call it, see *6* elements
// printed out
f(lua["arr"]);
lua.script(R"(
arr:add(28)
)");
// Call it, see *7* elements
// printed out
f(lua["arr"]);
lua.script(R"(
arr:clear()
)");
// Now it's empty
f(lua["arr"]);
std::cout << std::endl;
return 0;
}<|endoftext|> |
<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/RUdpConnection.hpp>
#include <utility>
#include <Nazara/Network/Debug.hpp>
namespace Nz
{
/*!
* \brief Closes the connection
*/
inline void RUdpConnection::Close()
{
m_socket.Close();
}
/*!
* \brief Disconnects the connection
*
* \see Close
*/
inline void RUdpConnection::Disconnect()
{
Close();
}
/*!
* \brief Gets the bound address
* \return IpAddress we are linked to
*/
inline IpAddress RUdpConnection::GetBoundAddress() const
{
return m_socket.GetBoundAddress();
}
/*!
* \brief Gets the port of the bound address
* \return Port we are linked to
*/
inline UInt16 RUdpConnection::GetBoundPort() const
{
return m_socket.GetBoundPort();
}
/*!
* \brief Gets the last error
* \return Socket error
*/
inline SocketError RUdpConnection::GetLastError() const
{
return m_lastError;
}
/*!
* \brief Listens to a socket
* \return true If successfully bound
*
* \param protocol Net protocol to listen to
* \param port Port to listen to
*
* \remark Produces a NazaraAssert if protocol is unknown or any
*/
inline bool RUdpConnection::Listen(NetProtocol protocol, UInt16 port)
{
NazaraAssert(protocol != NetProtocol_Any, "Any protocol not supported for Listen"); //< TODO
NazaraAssert(protocol != NetProtocol_Unknown, "Invalid protocol");
IpAddress any;
switch (protocol)
{
case NetProtocol_Any:
case NetProtocol_Unknown:
NazaraInternalError("Invalid protocol Any at this point");
return false;
case NetProtocol_IPv4:
any = IpAddress::AnyIpV4;
break;
case NetProtocol_IPv6:
any = IpAddress::AnyIpV6;
break;
}
any.SetPort(port);
return Listen(any);
}
/*!
* \brief Sets the protocol id
*
* \param protocolId Protocol ID like NNet
*/
inline void RUdpConnection::SetProtocolId(UInt32 protocolId)
{
m_protocol = protocolId;
}
/*!
* \brief Sets the time before ack
*
* \param Time before acking to send many together (in ms)
*/
inline void RUdpConnection::SetTimeBeforeAck(UInt32 ms)
{
m_forceAckSendTime = ms * 1000; //< Store in microseconds for easier handling
}
/*!
* \brief Computes the difference of sequence
* \return Delta between the two sequences
*
* \param sequence First sequence
* \param sequence2 Second sequence
*/
inline unsigned int RUdpConnection::ComputeSequenceDifference(SequenceIndex sequence, SequenceIndex sequence2)
{
unsigned int difference;
if (sequence2 > sequence)
difference = std::numeric_limits<SequenceIndex>::max() - sequence2 + sequence;
else
difference = sequence - sequence2;
return difference;
}
/*!
* \brief Checks whether the peer has pending packets
* \return true If it is the case
*
* \param peer Data relative to the peer
*/
inline bool RUdpConnection::HasPendingPackets(PeerData& peer)
{
for (unsigned int priority = PacketPriority_Highest; priority <= PacketPriority_Lowest; ++priority)
{
std::vector<PendingPacket>& pendingPackets = peer.pendingPackets[priority];
if (!pendingPackets.empty())
return true;
pendingPackets.clear();
}
return false;
}
/*!
* \brief Checks whether the ack is more recent
* \return true If it is the case
*
* \param ack First sequence
* \param ack2 Second sequence
*/
inline bool RUdpConnection::IsAckMoreRecent(SequenceIndex ack, SequenceIndex ack2)
{
constexpr SequenceIndex maxDifference = std::numeric_limits<SequenceIndex>::max() / 2;
if (ack > ack2)
return ack - ack2 <= maxDifference;
else if (ack2 > ack)
return ack2 - ack > maxDifference;
else
return false; ///< Same ack
}
/*!
* \brief Checks whether the connection is reliable
* \return true If it is the case
*
* \remark Produces a NazaraError if enumeration is invalid
*/
inline bool RUdpConnection::IsReliable(PacketReliability reliability)
{
switch (reliability)
{
case PacketReliability_Reliable:
case PacketReliability_ReliableOrdered:
return true;
case PacketReliability_Unreliable:
return false;
}
NazaraError("PacketReliability not handled (0x" + String::Number(reliability, 16) + ')');
return false;
}
/*!
* \brief Simulates the loss of packets on network
*
* \param packetLoss Ratio of packet loss according to bernoulli distribution
*
* \remark Produces a NazaraAssert if packetLoss is not in between 0.0 and 1.0
*/
inline void RUdpConnection::SimulateNetwork(double packetLoss)
{
NazaraAssert(packetLoss >= 0.0 && packetLoss <= 1.0, "Packet loss must be in range [0..1]");
if (packetLoss > 0.0)
{
m_isSimulationEnabled = true;
m_packetLossProbability = std::bernoulli_distribution(packetLoss);
}
else
m_isSimulationEnabled = false;
}
}
#include <Nazara/Network/DebugOff.hpp>
<commit_msg>Network/RUdpConnection: Remove useless line<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/RUdpConnection.hpp>
#include <utility>
#include <Nazara/Network/Debug.hpp>
namespace Nz
{
/*!
* \brief Closes the connection
*/
inline void RUdpConnection::Close()
{
m_socket.Close();
}
/*!
* \brief Disconnects the connection
*
* \see Close
*/
inline void RUdpConnection::Disconnect()
{
Close();
}
/*!
* \brief Gets the bound address
* \return IpAddress we are linked to
*/
inline IpAddress RUdpConnection::GetBoundAddress() const
{
return m_socket.GetBoundAddress();
}
/*!
* \brief Gets the port of the bound address
* \return Port we are linked to
*/
inline UInt16 RUdpConnection::GetBoundPort() const
{
return m_socket.GetBoundPort();
}
/*!
* \brief Gets the last error
* \return Socket error
*/
inline SocketError RUdpConnection::GetLastError() const
{
return m_lastError;
}
/*!
* \brief Listens to a socket
* \return true If successfully bound
*
* \param protocol Net protocol to listen to
* \param port Port to listen to
*
* \remark Produces a NazaraAssert if protocol is unknown or any
*/
inline bool RUdpConnection::Listen(NetProtocol protocol, UInt16 port)
{
NazaraAssert(protocol != NetProtocol_Any, "Any protocol not supported for Listen"); //< TODO
NazaraAssert(protocol != NetProtocol_Unknown, "Invalid protocol");
IpAddress any;
switch (protocol)
{
case NetProtocol_Any:
case NetProtocol_Unknown:
NazaraInternalError("Invalid protocol Any at this point");
return false;
case NetProtocol_IPv4:
any = IpAddress::AnyIpV4;
break;
case NetProtocol_IPv6:
any = IpAddress::AnyIpV6;
break;
}
any.SetPort(port);
return Listen(any);
}
/*!
* \brief Sets the protocol id
*
* \param protocolId Protocol ID like NNet
*/
inline void RUdpConnection::SetProtocolId(UInt32 protocolId)
{
m_protocol = protocolId;
}
/*!
* \brief Sets the time before ack
*
* \param Time before acking to send many together (in ms)
*/
inline void RUdpConnection::SetTimeBeforeAck(UInt32 ms)
{
m_forceAckSendTime = ms * 1000; //< Store in microseconds for easier handling
}
/*!
* \brief Computes the difference of sequence
* \return Delta between the two sequences
*
* \param sequence First sequence
* \param sequence2 Second sequence
*/
inline unsigned int RUdpConnection::ComputeSequenceDifference(SequenceIndex sequence, SequenceIndex sequence2)
{
unsigned int difference;
if (sequence2 > sequence)
difference = std::numeric_limits<SequenceIndex>::max() - sequence2 + sequence;
else
difference = sequence - sequence2;
return difference;
}
/*!
* \brief Checks whether the peer has pending packets
* \return true If it is the case
*
* \param peer Data relative to the peer
*/
inline bool RUdpConnection::HasPendingPackets(PeerData& peer)
{
for (unsigned int priority = PacketPriority_Highest; priority <= PacketPriority_Lowest; ++priority)
{
std::vector<PendingPacket>& pendingPackets = peer.pendingPackets[priority];
if (!pendingPackets.empty())
return true;
}
return false;
}
/*!
* \brief Checks whether the ack is more recent
* \return true If it is the case
*
* \param ack First sequence
* \param ack2 Second sequence
*/
inline bool RUdpConnection::IsAckMoreRecent(SequenceIndex ack, SequenceIndex ack2)
{
constexpr SequenceIndex maxDifference = std::numeric_limits<SequenceIndex>::max() / 2;
if (ack > ack2)
return ack - ack2 <= maxDifference;
else if (ack2 > ack)
return ack2 - ack > maxDifference;
else
return false; ///< Same ack
}
/*!
* \brief Checks whether the connection is reliable
* \return true If it is the case
*
* \remark Produces a NazaraError if enumeration is invalid
*/
inline bool RUdpConnection::IsReliable(PacketReliability reliability)
{
switch (reliability)
{
case PacketReliability_Reliable:
case PacketReliability_ReliableOrdered:
return true;
case PacketReliability_Unreliable:
return false;
}
NazaraError("PacketReliability not handled (0x" + String::Number(reliability, 16) + ')');
return false;
}
/*!
* \brief Simulates the loss of packets on network
*
* \param packetLoss Ratio of packet loss according to bernoulli distribution
*
* \remark Produces a NazaraAssert if packetLoss is not in between 0.0 and 1.0
*/
inline void RUdpConnection::SimulateNetwork(double packetLoss)
{
NazaraAssert(packetLoss >= 0.0 && packetLoss <= 1.0, "Packet loss must be in range [0..1]");
if (packetLoss > 0.0)
{
m_isSimulationEnabled = true;
m_packetLossProbability = std::bernoulli_distribution(packetLoss);
}
else
m_isSimulationEnabled = false;
}
}
#include <Nazara/Network/DebugOff.hpp>
<|endoftext|> |
<commit_before>#include "HeatMapVisualization.h"
HeatMapVisualization::HeatMapVisualization(QSize resolution) : QWidget() {
mainLayout = new QVBoxLayout();
lastEvents = NULL;
height = resolution.height();
width = resolution.width();
heatMap = new int*[height];
for (int i = 0; i < height; ++i)
heatMap[i] = new int[width];
mouseRoute = new QVector<QPoint>();
clearHeatMap();
marge = 40;
mouseRouteInterval = 1;
leftClick = true;
rightClick = true;
mouseMoveRoute = true;
click = true;
doubleClick = true;
mouseMove = true;
screenWidth = 500;
screenHeight = 300;
image = new QImage(width, height, QImage::Format_RGB32);
heatMapLabel = new QLabel();
/*heatMapLabel->setMinimumWidth(screenWidth);
heatMapLabel->setMaximumWidth(screenWidth);
heatMapLabel->setMinimumHeight(screenHeight);
heatMapLabel->setMaximumHeight(screenHeight);*/
heatMapLabel->setPixmap(QPixmap::fromImage(*image));
QPushButton *showImageButton = new QPushButton("Afbeelding in oorspronkelijke grootte");
connect(showImageButton, SIGNAL(clicked()), this, SLOT(showImage()));
mainLayout->addWidget(heatMapLabel, 0, Qt::AlignCenter);
mainLayout->addWidget(showImageButton,0,Qt::AlignCenter);
QHBoxLayout *checkButtonLayout = new QHBoxLayout();
QGroupBox *box1 = new QGroupBox();
QVBoxLayout *box1Layout = new QVBoxLayout();
leftClickCheckBox = new QCheckBox("&Linker muisklik", this);
rightClickCheckBox = new QCheckBox("&Rechter muisklik", this);
mouseMoveRouteCheckBox = new QCheckBox("&Traject muisbewegingen");
QGroupBox *box2 = new QGroupBox();
QVBoxLayout *box2Layout = new QVBoxLayout();
clickCheckBox = new QCheckBox("&En muisklik", this);
doubleClickCheckBox = new QCheckBox("&Dubbel muisklik", this);
mouseMoveCheckBox = new QCheckBox("&Muisbewegingen", this);
leftClickCheckBox->setCheckState(Qt::Checked);
rightClickCheckBox->setCheckState(Qt::Checked);
mouseMoveRouteCheckBox->setCheckState(Qt::Checked);
clickCheckBox->setCheckState(Qt::Checked);
doubleClickCheckBox->setCheckState(Qt::Checked);
mouseMoveCheckBox->setCheckState(Qt::Checked);
connect(leftClickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(rightClickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(mouseMoveRouteCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(clickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(doubleClickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(mouseMoveCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
box1Layout->addWidget(leftClickCheckBox);
box1Layout->addWidget(rightClickCheckBox);
box1Layout->addWidget(mouseMoveRouteCheckBox);
box2Layout->addWidget(clickCheckBox);
box2Layout->addWidget(doubleClickCheckBox);
box2Layout->addWidget(mouseMoveCheckBox);
box1->setLayout(box1Layout);
box2->setLayout(box2Layout);
checkButtonLayout->addWidget(box1);
checkButtonLayout->addWidget(box2);
QLabel *margeLabel = new QLabel("Marge rond elke klik:");
margeSpinBox = new QSpinBox();
margeSpinBox->setRange(1, 100);
margeSpinBox->setValue(marge);
connect(margeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateMarge(int)));
QLabel *mouseRouteIntervalLabel = new QLabel("Nauwkeurigheid van muisbewegingen");
mouseRouteIntervalSpinBox = new QSpinBox();
mouseRouteIntervalSpinBox->setRange(1, 100);
mouseRouteIntervalSpinBox->setValue(mouseRouteInterval);
connect(mouseRouteIntervalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateMouseRouteInterval(int)));
QGroupBox *box3 = new QGroupBox();
QVBoxLayout *box3Layout = new QVBoxLayout();
box3Layout->addWidget(margeLabel);
box3Layout->addWidget(margeSpinBox);
box3Layout->addWidget(mouseRouteIntervalLabel);
box3Layout->addWidget(mouseRouteIntervalSpinBox);
box3->setLayout(box3Layout);
checkButtonLayout->addWidget(box3);
mainLayout->addLayout(checkButtonLayout);
renderVisualization();
this->setLayout(mainLayout);
this->show();
}
void HeatMapVisualization::update(QVector<Event*> *events = NULL) {
//qDebug() << "HeatMapVisualization::update()";
clearHeatMap();
if (events != NULL)
lastEvents = events;
else if (lastEvents != NULL)
events = lastEvents;
else
return;
int counter = 0, mouseRouteX = 0, mouseRouteY = 0;
for (int i = 0; i < events->count(); ++i) {
if ((click && events->at(i)->getEventType().compare("MouseButtonPress") == 0) || (doubleClick && events->at(i)->getEventType().compare("MouseButtonDblClick") == 0) || ((mouseMove || mouseMoveRoute) && events->at(i)->getEventType().compare("MouseMove") == 0)) {
// enkel muiskliks (enkel en dubbel)
//qDebug() << "Type: " << events->at(i)->getEventType();
QString details = events->at(i)->getDetails();
details.remove("\"");//remove "
QStringList args = details.split(";");
if (args.count() >= 2) {
int x = args.at(0).toInt();
int y = args.at(1).toInt();
//qDebug() << details << x << y;
if (x >= 0 && y >= 0 && x < height && y < width) {
if (mouseMove && events->at(i)->getEventType().compare("MouseMove") == 0)
clickOnHeatMap(x,y);
if ((click || doubleClick) && args.count() == 3 && events->at(i)->getEventType().compare("MouseMove") != 0) {
// controleren: links en rechts filteren indien nodig (checkBoxes)
if (leftClick && args.at(2).indexOf("L") != -1)// args.at(2) == ""L" " "
clickOnHeatMap(x,y);
else if (rightClick && args.at(2).indexOf("R") != -1)
clickOnHeatMap(x,y);
}
if (mouseMoveRoute && events->at(i)->getEventType().compare("MouseMove") == 0) { //muisbewegingen tekenen => gemiddeld punt berekenen per mouseRouteInterval bewegingen
if (counter < mouseRouteInterval) {
mouseRouteX += x;
mouseRouteY += y;
counter++;
}
if(counter == mouseRouteInterval) {
mouseRoute->append(QPoint(mouseRouteY/mouseRouteInterval, mouseRouteX/mouseRouteInterval));
counter = 0;
mouseRouteX = 0;
mouseRouteY = 0;
}
}
}
}
}
}
renderVisualization();
}
void HeatMapVisualization::clickOnHeatMap(int x, int y) {
// waar geklikt is, een hoge score toekennen, de marge errond score alsmaar verkleinen
for (int k = -marge; k <= marge && x + k < height; ++k)
for (int l = -marge; l <= marge && y+l < width; ++l)
if(x + k > 0 && y + l > 0) {
heatMap[x + k][y + l] += (marge + 1) - max(abs(k),abs(l));
}
if (maxClicks < heatMap[x][y])//hoogst voorkomend aantal kliks bijhouden
maxClicks = heatMap[x][y];
}
void HeatMapVisualization::renderVisualization() {
QColor color;
int h, v, s;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (heatMap[i][j] == 0) {// er is niet geklikt
h = 255;
v = 0;
s = 255;
}
else {// geklikt
s = 255;
float value = float(heatMap[i][j])/float(maxClicks);// verhouding: is op deze plaats veel geklikt
v = value * 255.0;
if (value > 0.333){//matig tot veel geklikt => de kleuren geel tot rood hiervoor gebruiken
float inversDiff = 3/2, min = 1/3;
int color = 60;//==colorRange
//0 rood
//60 geel
h = color - (inversDiff * (value - min)) * color;
if (heatMap[i][j] > maxClicks) {
h = 0;
v = 255;//in deze omgeving is heel veel geklikt
s = 230;// => extra benadrukken
}
}
else {// weinig geklikt (marge rond klik) => blauw tinten
float inversDiff = 3/1, min = 0;
int color = 240;
int colorRange = 180;
//60 geel
//240 blauw
h = color - (inversDiff * (value - min)) * colorRange;
}
//qDebug() << "color " << h << v << s;
}
color.setHsv(h,v,s);
color.setAlpha(127);
image->setPixel(j, i, color.rgb());
}
}
QPainter painter;
painter.begin(image);
for(int i = 0; i + 1 < mouseRoute->size(); ++i){
QLineF line(mouseRoute->at(i), mouseRoute->at(i+1));
painter.drawLine(line);
}
painter.end();
QImage scaledImage = image->scaled(QSize(screenWidth,screenHeight),Qt::KeepAspectRatio);
heatMapLabel->setPixmap(QPixmap::fromImage(scaledImage));
}
int HeatMapVisualization::max(int a, int b) {
return (a>b)?a:b;
}
void HeatMapVisualization::clearHeatMap() {
maxClicks = 0;
for (int i = 0; i < height; ++i)
for (int j = 0; j < width; ++j)
heatMap[i][j] = 0;
mouseRoute->clear();
}
void HeatMapVisualization::updateParameters(int state) {
if (leftClickCheckBox->checkState() == Qt::Checked)
leftClick = true;
else
leftClick = false;
if (rightClickCheckBox->checkState() == Qt::Checked)
rightClick = true;
else
rightClick = false;
if (mouseMoveRouteCheckBox->checkState() == Qt::Checked)
mouseMoveRoute = true;
else
mouseMoveRoute = false;
if (clickCheckBox->checkState() == Qt::Checked)
click = true;
else
click = false;
if (doubleClickCheckBox->checkState() == Qt::Checked)
doubleClick = true;
else
doubleClick = false;
if (mouseMoveCheckBox->checkState() == Qt::Checked)
mouseMove = true;
else
mouseMove = false;
update(NULL);
}
void HeatMapVisualization::updateMarge(int marge) {
this->marge = marge;
update(NULL);
}
void HeatMapVisualization::updateMouseRouteInterval(int interval) {
this->mouseRouteInterval = interval;
update(NULL);
}
void HeatMapVisualization::showImage() {
dialog = new QDialog();
QVBoxLayout *layout = new QVBoxLayout();
QLabel *imageLabel = new QLabel();
imageLabel->setPixmap(QPixmap::fromImage(*image));
QPushButton *okButton = new QPushButton("Ok");
connect(okButton, SIGNAL(clicked()), this, SLOT(closeDialog()));
layout->addWidget(imageLabel, 0, Qt::AlignCenter);
layout->addWidget(okButton, 0, Qt::AlignCenter);
dialog->setLayout(layout);
dialog->show();
}
void HeatMapVisualization::closeDialog() {
dialog->close();
delete dialog;
}
<commit_msg>Simplified the state checking of the checkboxes. Also, removed obsolete NULL's when calling update() which already had a default parameter value of NULL set.<commit_after>#include "HeatMapVisualization.h"
HeatMapVisualization::HeatMapVisualization(QSize resolution) : QWidget() {
mainLayout = new QVBoxLayout();
lastEvents = NULL;
height = resolution.height();
width = resolution.width();
heatMap = new int*[height];
for (int i = 0; i < height; ++i)
heatMap[i] = new int[width];
mouseRoute = new QVector<QPoint>();
clearHeatMap();
marge = 40;
mouseRouteInterval = 1;
leftClick = true;
rightClick = true;
mouseMoveRoute = true;
click = true;
doubleClick = true;
mouseMove = true;
screenWidth = 500;
screenHeight = 300;
image = new QImage(width, height, QImage::Format_RGB32);
heatMapLabel = new QLabel();
/*heatMapLabel->setMinimumWidth(screenWidth);
heatMapLabel->setMaximumWidth(screenWidth);
heatMapLabel->setMinimumHeight(screenHeight);
heatMapLabel->setMaximumHeight(screenHeight);*/
heatMapLabel->setPixmap(QPixmap::fromImage(*image));
QPushButton *showImageButton = new QPushButton("Afbeelding in oorspronkelijke grootte");
connect(showImageButton, SIGNAL(clicked()), this, SLOT(showImage()));
mainLayout->addWidget(heatMapLabel, 0, Qt::AlignCenter);
mainLayout->addWidget(showImageButton,0,Qt::AlignCenter);
QHBoxLayout *checkButtonLayout = new QHBoxLayout();
QGroupBox *box1 = new QGroupBox();
QVBoxLayout *box1Layout = new QVBoxLayout();
leftClickCheckBox = new QCheckBox("&Linker muisklik", this);
rightClickCheckBox = new QCheckBox("&Rechter muisklik", this);
mouseMoveRouteCheckBox = new QCheckBox("&Traject muisbewegingen");
QGroupBox *box2 = new QGroupBox();
QVBoxLayout *box2Layout = new QVBoxLayout();
clickCheckBox = new QCheckBox("&En muisklik", this);
doubleClickCheckBox = new QCheckBox("&Dubbel muisklik", this);
mouseMoveCheckBox = new QCheckBox("&Muisbewegingen", this);
leftClickCheckBox->setCheckState(Qt::Checked);
rightClickCheckBox->setCheckState(Qt::Checked);
mouseMoveRouteCheckBox->setCheckState(Qt::Checked);
clickCheckBox->setCheckState(Qt::Checked);
doubleClickCheckBox->setCheckState(Qt::Checked);
mouseMoveCheckBox->setCheckState(Qt::Checked);
connect(leftClickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(rightClickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(mouseMoveRouteCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(clickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(doubleClickCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
connect(mouseMoveCheckBox, SIGNAL(stateChanged(int)), this, SLOT(updateParameters(int)));
box1Layout->addWidget(leftClickCheckBox);
box1Layout->addWidget(rightClickCheckBox);
box1Layout->addWidget(mouseMoveRouteCheckBox);
box2Layout->addWidget(clickCheckBox);
box2Layout->addWidget(doubleClickCheckBox);
box2Layout->addWidget(mouseMoveCheckBox);
box1->setLayout(box1Layout);
box2->setLayout(box2Layout);
checkButtonLayout->addWidget(box1);
checkButtonLayout->addWidget(box2);
QLabel *margeLabel = new QLabel("Marge rond elke klik:");
margeSpinBox = new QSpinBox();
margeSpinBox->setRange(1, 100);
margeSpinBox->setValue(marge);
connect(margeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateMarge(int)));
QLabel *mouseRouteIntervalLabel = new QLabel("Nauwkeurigheid van muisbewegingen");
mouseRouteIntervalSpinBox = new QSpinBox();
mouseRouteIntervalSpinBox->setRange(1, 100);
mouseRouteIntervalSpinBox->setValue(mouseRouteInterval);
connect(mouseRouteIntervalSpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateMouseRouteInterval(int)));
QGroupBox *box3 = new QGroupBox();
QVBoxLayout *box3Layout = new QVBoxLayout();
box3Layout->addWidget(margeLabel);
box3Layout->addWidget(margeSpinBox);
box3Layout->addWidget(mouseRouteIntervalLabel);
box3Layout->addWidget(mouseRouteIntervalSpinBox);
box3->setLayout(box3Layout);
checkButtonLayout->addWidget(box3);
mainLayout->addLayout(checkButtonLayout);
renderVisualization();
this->setLayout(mainLayout);
this->show();
}
void HeatMapVisualization::update(QVector<Event*> *events = NULL) {
//qDebug() << "HeatMapVisualization::update()";
clearHeatMap();
if (events != NULL)
lastEvents = events;
else if (lastEvents != NULL)
events = lastEvents;
else
return;
int counter = 0, mouseRouteX = 0, mouseRouteY = 0;
for (int i = 0; i < events->count(); ++i) {
if ((click && events->at(i)->getEventType().compare("MouseButtonPress") == 0) || (doubleClick && events->at(i)->getEventType().compare("MouseButtonDblClick") == 0) || ((mouseMove || mouseMoveRoute) && events->at(i)->getEventType().compare("MouseMove") == 0)) {
// enkel muiskliks (enkel en dubbel)
//qDebug() << "Type: " << events->at(i)->getEventType();
QString details = events->at(i)->getDetails();
details.remove("\"");//remove "
QStringList args = details.split(";");
if (args.count() >= 2) {
int x = args.at(0).toInt();
int y = args.at(1).toInt();
//qDebug() << details << x << y;
if (x >= 0 && y >= 0 && x < height && y < width) {
if (mouseMove && events->at(i)->getEventType().compare("MouseMove") == 0)
clickOnHeatMap(x,y);
if ((click || doubleClick) && args.count() == 3 && events->at(i)->getEventType().compare("MouseMove") != 0) {
// controleren: links en rechts filteren indien nodig (checkBoxes)
if (leftClick && args.at(2).indexOf("L") != -1)// args.at(2) == ""L" " "
clickOnHeatMap(x,y);
else if (rightClick && args.at(2).indexOf("R") != -1)
clickOnHeatMap(x,y);
}
if (mouseMoveRoute && events->at(i)->getEventType().compare("MouseMove") == 0) { //muisbewegingen tekenen => gemiddeld punt berekenen per mouseRouteInterval bewegingen
if (counter < mouseRouteInterval) {
mouseRouteX += x;
mouseRouteY += y;
counter++;
}
if(counter == mouseRouteInterval) {
mouseRoute->append(QPoint(mouseRouteY/mouseRouteInterval, mouseRouteX/mouseRouteInterval));
counter = 0;
mouseRouteX = 0;
mouseRouteY = 0;
}
}
}
}
}
}
renderVisualization();
}
void HeatMapVisualization::clickOnHeatMap(int x, int y) {
// waar geklikt is, een hoge score toekennen, de marge errond score alsmaar verkleinen
for (int k = -marge; k <= marge && x + k < height; ++k)
for (int l = -marge; l <= marge && y+l < width; ++l)
if(x + k > 0 && y + l > 0) {
heatMap[x + k][y + l] += (marge + 1) - max(abs(k),abs(l));
}
if (maxClicks < heatMap[x][y])//hoogst voorkomend aantal kliks bijhouden
maxClicks = heatMap[x][y];
}
void HeatMapVisualization::renderVisualization() {
QColor color;
int h, v, s;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (heatMap[i][j] == 0) {// er is niet geklikt
h = 255;
v = 0;
s = 255;
}
else {// geklikt
s = 255;
float value = float(heatMap[i][j])/float(maxClicks);// verhouding: is op deze plaats veel geklikt
v = value * 255.0;
if (value > 0.333){//matig tot veel geklikt => de kleuren geel tot rood hiervoor gebruiken
float inversDiff = 3/2, min = 1/3;
int color = 60;//==colorRange
//0 rood
//60 geel
h = color - (inversDiff * (value - min)) * color;
if (heatMap[i][j] > maxClicks) {
h = 0;
v = 255;//in deze omgeving is heel veel geklikt
s = 230;// => extra benadrukken
}
}
else {// weinig geklikt (marge rond klik) => blauw tinten
float inversDiff = 3/1, min = 0;
int color = 240;
int colorRange = 180;
//60 geel
//240 blauw
h = color - (inversDiff * (value - min)) * colorRange;
}
//qDebug() << "color " << h << v << s;
}
color.setHsv(h,v,s);
color.setAlpha(127);
image->setPixel(j, i, color.rgb());
}
}
QPainter painter;
painter.begin(image);
for(int i = 0; i + 1 < mouseRoute->size(); ++i){
QLineF line(mouseRoute->at(i), mouseRoute->at(i+1));
painter.drawLine(line);
}
painter.end();
QImage scaledImage = image->scaled(QSize(screenWidth,screenHeight),Qt::KeepAspectRatio);
heatMapLabel->setPixmap(QPixmap::fromImage(scaledImage));
}
int HeatMapVisualization::max(int a, int b) {
return (a>b)?a:b;
}
void HeatMapVisualization::clearHeatMap() {
maxClicks = 0;
for (int i = 0; i < height; ++i)
for (int j = 0; j < width; ++j)
heatMap[i][j] = 0;
mouseRoute->clear();
}
void HeatMapVisualization::updateParameters(int state) {
leftClick = leftClickCheckBox->isChecked();
rightClick = rightClickCheckBox->isChecked();
mouseMoveRoute = mouseMoveRouteCheckBox->isChecked();
click = clickCheckBox->isChecked();
doubleClick = doubleClickCheckBox->isChecked();
mouseMove = mouseMoveCheckBox->isChecked();
update();
}
void HeatMapVisualization::updateMarge(int marge) {
this->marge = marge;
update();
}
void HeatMapVisualization::updateMouseRouteInterval(int interval) {
mouseRouteInterval = interval;
update();
}
void HeatMapVisualization::showImage() {
dialog = new QDialog();
QVBoxLayout *layout = new QVBoxLayout();
QLabel *imageLabel = new QLabel();
imageLabel->setPixmap(QPixmap::fromImage(*image));
QPushButton *okButton = new QPushButton("Ok");
connect(okButton, SIGNAL(clicked()), this, SLOT(closeDialog()));
layout->addWidget(imageLabel, 0, Qt::AlignCenter);
layout->addWidget(okButton, 0, Qt::AlignCenter);
dialog->setLayout(layout);
dialog->show();
}
void HeatMapVisualization::closeDialog() {
dialog->close();
delete dialog;
}
<|endoftext|> |
<commit_before>/* Copyright 2016 Kristofer Björnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file ParallelepipedCell.cpp
*
* @author Kristofer Björnson
*/
#include "ParallelepipedCell.h"
#include "TBTKMacros.h"
using namespace std;
namespace TBTK{
ParallelepipedCell::ParallelepipedCell(initializer_list<initializer_list<double>> basisVectors){
this->dimensions = basisVectors.size();
TBTKAssert(
dimensions == 1
|| dimensions == 2
|| dimensions == 3,
"ParallelepipedCell::ParallelepipedCell()",
"Basis dimension not supported.",
"Only 1-3 basis vectors are supported, but "
<< basisVectors.size() << " basis vectors supplied."
);
for(unsigned int n = 0; n < dimensions; n++){
TBTKAssert(
(basisVectors.begin() + n)->size() == dimensions,
"ParallelepipedCell::ParallelepipedCell()",
"Incompatible dimensions.",
"The number of basis vectors must agree with the number"
<< " of components of the basis vectors. The number of"
<< " basis vectors are '" << dimensions << "',"
<< " but encountered basis vector with '"
<< (basisVectors.begin() + n)->size() << "' components."
);
vector<double> paddedBasisVector;
for(unsigned int c = 0; c < dimensions; c++)
paddedBasisVector.push_back(*((basisVectors.begin() + n)->begin() + c));
for(unsigned int c = dimensions; c < 3; c++)
paddedBasisVector.push_back(0.);
this->basisVectors.push_back(Vector3d(paddedBasisVector));
}
for(unsigned int n = dimensions; n < 3; n++){
vector<double> vector;
for(unsigned int c = 0; c < 3; c++){
if(c == n)
vector.push_back(1.);
else
vector.push_back(0.);
}
this->basisVectors.push_back(Vector3d(vector));
}
for(unsigned int n = 0; n < 3; n++){
const Vector3d &v0 = this->basisVectors.at(n);
const Vector3d &v1 = this->basisVectors.at((n+1)%3);
const Vector3d &v2 = this->basisVectors.at((n+2)%3);
Vector3d normal = v1*v2;
normal = normal/Vector3d::dotProduct(normal, v0);
reciprocalNormals.push_back(normal);
}
}
ParallelepipedCell::ParallelepipedCell(const vector<vector<double>> &basisVectors){
this->dimensions = basisVectors.size();
TBTKAssert(
dimensions == 1
|| dimensions == 2
|| dimensions == 3,
"ParallelepipedCell::ParallelepipedCell()",
"Basis dimension not supported.",
"Only 1-3 basis vectors are supported, but "
<< basisVectors.size() << " basis vectors supplied."
);
for(unsigned int n = 0; n < dimensions; n++){
TBTKAssert(
basisVectors.at(n).size() == dimensions,
"ParallelepipedCell::ParallelepipedCell()",
"Incompatible dimensions.",
"The number of basis vectors must agree with the number"
<< " of components of the basis vectors. The number of"
<< " basis vectors are '" << dimensions << "',"
<< " but encountered basis vector with '"
<< basisVectors.at(n).size() << "' components."
);
vector<double> paddedBasisVector;
for(unsigned int c = 0; c < dimensions; c++)
paddedBasisVector.push_back(basisVectors.at(n).at(c));
for(unsigned int c = dimensions; c < 3; c++)
paddedBasisVector.push_back(0.);
this->basisVectors.push_back(Vector3d(paddedBasisVector));
}
for(unsigned int n = dimensions; n < 3; n++){
vector<double> vector;
for(unsigned int c = 0; c < 3; c++){
if(c == n)
vector.push_back(1.);
else
vector.push_back(0.);
}
this->basisVectors.push_back(Vector3d(vector));
}
for(unsigned int n = 0; n < 3; n++){
const Vector3d &v0 = basisVectors.at(n);
const Vector3d &v1 = basisVectors.at((n+1)%3);
const Vector3d &v2 = basisVectors.at((n+2)%3);
Vector3d normal = v1*v2;
normal = normal/Vector3d::dotProduct(normal, v0);
reciprocalNormals.push_back(normal);
}
}
ParallelepipedCell::~ParallelepipedCell(){
}
Index ParallelepipedCell::getCellIndex(initializer_list<double> coordinates) const{
TBTKAssert(
coordinates.size() == dimensions,
"ParallelepipedCell::getCellIndex()",
"Incompatible dimensions.",
"The number of coordinate components must agree with the"
<< " dimension of the parallelepiped cell. The parallelepiped"
<< " cell has " << dimensions << " dimensions, but coordinate"
<< " with " << coordinates.size() << " components supplied."
);
Vector3d coordinateVector;
switch(coordinates.size()){
case 1:
coordinateVector = Vector3d({
*(coordinates.begin() + 0),
0.,
0.
});
break;
case 2:
coordinateVector = Vector3d({
*(coordinates.begin() + 0),
*(coordinates.begin() + 1),
0.
});
break;
case 3:
coordinateVector = Vector3d({
*(coordinates.begin() + 0),
*(coordinates.begin() + 1),
*(coordinates.begin() + 2)
});
break;
default:
TBTKExit(
"ParallelepipedCell::getCellIndex()",
"This should never happen.",
"Notify the developer about this bug."
);
break;
}
// Index cellIndex({});
Index cellIndex;
for(unsigned int n = 0; n < dimensions; n++){
double v = Vector3d::dotProduct(
coordinateVector,
reciprocalNormals.at(n)
);
if(v > 0)
cellIndex.push_back((int)(v + 1/2.));
else
cellIndex.push_back((int)(v - 1/2.));
}
return cellIndex;
}
vector<vector<double>> ParallelepipedCell::getMesh(
initializer_list<unsigned int> numMeshPoints
) const{
TBTKAssert(
numMeshPoints.size() == dimensions,
"ParallelepipedCell::getMesh()",
"Incompatible diemsnions.",
"The argument 'numMeshPoints' must have the same number of"
<< " components as the dimension of the parallelepiped cell."
<< " The parallelepiped cell has dimension " << dimensions
<< ", while numMeshPoints have " << numMeshPoints.size()
<< " components."
);
vector<vector<double>> mesh;
unsigned int nmp[3];
nmp[0] = *(numMeshPoints.begin() + 0);
if(numMeshPoints.size() > 1)
nmp[1] = *(numMeshPoints.begin() + 1);
else
nmp[1] = 1;
if(numMeshPoints.size() > 2)
nmp[2] = *(numMeshPoints.begin() + 2);
else
nmp[2] = 1;
for(unsigned int x = 0; x < nmp[0]; x++){
Vector3d v0;
if(nmp[0]%2 == 0)
v0 = ((int)x - (int)(nmp[0]/2) + 1/2.)*basisVectors.at(0)/nmp[0];
else
v0 = ((int)x - (int)(nmp[0]/2))*basisVectors.at(0)/nmp[0];
for(unsigned int y = 0; y < nmp[1]; y++){
Vector3d v1;
if(nmp[1]%2 == 0)
v1 = ((int)y - (int)(nmp[1]/2) + 1/2.)*basisVectors.at(1)/nmp[1];
else
v1 = ((int)y - (int)(nmp[1]/2))*basisVectors.at(1)/nmp[1];
for(unsigned int z = 0; z < nmp[2]; z++){
Vector3d v2;
if(nmp[2]%2 == 0)
v2 = ((int)z - (int)(nmp[2]/2) + 1/2.)*basisVectors.at(2)/nmp[2];
else
v2 = ((int)z - (int)(nmp[2]/2))*basisVectors.at(2)/nmp[2];
if(numMeshPoints.size() == 1){
mesh.push_back({v0.x});
Streams::out << v0.x << "\n";
}
else if(numMeshPoints.size() == 2){
mesh.push_back({
(v0 + v1).x,
(v0 + v1).y
});
}
else if(numMeshPoints.size() == 3){
mesh.push_back({
(v0 + v1 + v2).x,
(v0 + v1 + v2).y,
(v0 + v1 + v2).z
});
}
}
}
}
return mesh;
}
}; //End of namespace TBTK
<commit_msg>Corrected bug in ParallelepiedCell<commit_after>/* Copyright 2016 Kristofer Björnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file ParallelepipedCell.cpp
*
* @author Kristofer Björnson
*/
#include "ParallelepipedCell.h"
#include "TBTKMacros.h"
using namespace std;
namespace TBTK{
ParallelepipedCell::ParallelepipedCell(initializer_list<initializer_list<double>> basisVectors){
this->dimensions = basisVectors.size();
TBTKAssert(
dimensions == 1
|| dimensions == 2
|| dimensions == 3,
"ParallelepipedCell::ParallelepipedCell()",
"Basis dimension not supported.",
"Only 1-3 basis vectors are supported, but "
<< basisVectors.size() << " basis vectors supplied."
);
for(unsigned int n = 0; n < dimensions; n++){
TBTKAssert(
(basisVectors.begin() + n)->size() == dimensions,
"ParallelepipedCell::ParallelepipedCell()",
"Incompatible dimensions.",
"The number of basis vectors must agree with the number"
<< " of components of the basis vectors. The number of"
<< " basis vectors are '" << dimensions << "',"
<< " but encountered basis vector with '"
<< (basisVectors.begin() + n)->size() << "' components."
);
vector<double> paddedBasisVector;
for(unsigned int c = 0; c < dimensions; c++)
paddedBasisVector.push_back(*((basisVectors.begin() + n)->begin() + c));
for(unsigned int c = dimensions; c < 3; c++)
paddedBasisVector.push_back(0.);
this->basisVectors.push_back(Vector3d(paddedBasisVector));
}
for(unsigned int n = dimensions; n < 3; n++){
vector<double> vector;
for(unsigned int c = 0; c < 3; c++){
if(c == n)
vector.push_back(1.);
else
vector.push_back(0.);
}
this->basisVectors.push_back(Vector3d(vector));
}
for(unsigned int n = 0; n < 3; n++){
const Vector3d &v0 = this->basisVectors.at(n);
const Vector3d &v1 = this->basisVectors.at((n+1)%3);
const Vector3d &v2 = this->basisVectors.at((n+2)%3);
Vector3d normal = v1*v2;
normal = normal/Vector3d::dotProduct(normal, v0);
reciprocalNormals.push_back(normal);
}
}
ParallelepipedCell::ParallelepipedCell(const vector<vector<double>> &basisVectors){
this->dimensions = basisVectors.size();
TBTKAssert(
dimensions == 1
|| dimensions == 2
|| dimensions == 3,
"ParallelepipedCell::ParallelepipedCell()",
"Basis dimension not supported.",
"Only 1-3 basis vectors are supported, but "
<< basisVectors.size() << " basis vectors supplied."
);
for(unsigned int n = 0; n < dimensions; n++){
TBTKAssert(
basisVectors.at(n).size() == dimensions,
"ParallelepipedCell::ParallelepipedCell()",
"Incompatible dimensions.",
"The number of basis vectors must agree with the number"
<< " of components of the basis vectors. The number of"
<< " basis vectors are '" << dimensions << "',"
<< " but encountered basis vector with '"
<< basisVectors.at(n).size() << "' components."
);
vector<double> paddedBasisVector;
for(unsigned int c = 0; c < dimensions; c++)
paddedBasisVector.push_back(basisVectors.at(n).at(c));
for(unsigned int c = dimensions; c < 3; c++)
paddedBasisVector.push_back(0.);
this->basisVectors.push_back(Vector3d(paddedBasisVector));
}
for(unsigned int n = dimensions; n < 3; n++){
vector<double> vector;
for(unsigned int c = 0; c < 3; c++){
if(c == n)
vector.push_back(1.);
else
vector.push_back(0.);
}
this->basisVectors.push_back(Vector3d(vector));
}
for(unsigned int n = 0; n < 3; n++){
const Vector3d &v0 = basisVectors.at(n);
const Vector3d &v1 = basisVectors.at((n+1)%3);
const Vector3d &v2 = basisVectors.at((n+2)%3);
Vector3d normal = v1*v2;
normal = normal/Vector3d::dotProduct(normal, v0);
reciprocalNormals.push_back(normal);
}
}
ParallelepipedCell::~ParallelepipedCell(){
}
Index ParallelepipedCell::getCellIndex(initializer_list<double> coordinates) const{
TBTKAssert(
coordinates.size() == dimensions,
"ParallelepipedCell::getCellIndex()",
"Incompatible dimensions.",
"The number of coordinate components must agree with the"
<< " dimension of the parallelepiped cell. The parallelepiped"
<< " cell has " << dimensions << " dimensions, but coordinate"
<< " with " << coordinates.size() << " components supplied."
);
Vector3d coordinateVector;
switch(coordinates.size()){
case 1:
coordinateVector = Vector3d({
*(coordinates.begin() + 0),
0.,
0.
});
break;
case 2:
coordinateVector = Vector3d({
*(coordinates.begin() + 0),
*(coordinates.begin() + 1),
0.
});
break;
case 3:
coordinateVector = Vector3d({
*(coordinates.begin() + 0),
*(coordinates.begin() + 1),
*(coordinates.begin() + 2)
});
break;
default:
TBTKExit(
"ParallelepipedCell::getCellIndex()",
"This should never happen.",
"Notify the developer about this bug."
);
break;
}
// Index cellIndex({});
Index cellIndex;
for(unsigned int n = 0; n < dimensions; n++){
double v = Vector3d::dotProduct(
coordinateVector,
reciprocalNormals.at(n)
);
if(v > 0)
cellIndex.push_back((int)(v + 1/2.));
else
cellIndex.push_back((int)(v - 1/2.));
}
return cellIndex;
}
vector<vector<double>> ParallelepipedCell::getMesh(
initializer_list<unsigned int> numMeshPoints
) const{
TBTKAssert(
numMeshPoints.size() == dimensions,
"ParallelepipedCell::getMesh()",
"Incompatible diemsnions.",
"The argument 'numMeshPoints' must have the same number of"
<< " components as the dimension of the parallelepiped cell."
<< " The parallelepiped cell has dimension " << dimensions
<< ", while numMeshPoints have " << numMeshPoints.size()
<< " components."
);
vector<vector<double>> mesh;
unsigned int nmp[3];
nmp[0] = *(numMeshPoints.begin() + 0);
if(numMeshPoints.size() > 1)
nmp[1] = *(numMeshPoints.begin() + 1);
else
nmp[1] = 1;
if(numMeshPoints.size() > 2)
nmp[2] = *(numMeshPoints.begin() + 2);
else
nmp[2] = 1;
for(unsigned int x = 0; x < nmp[0]; x++){
Vector3d v0;
if(nmp[0]%2 == 0)
v0 = ((int)x - (int)(nmp[0]/2) + 1/2.)*basisVectors.at(0)/(nmp[0]-1);
else
v0 = ((int)x - (int)(nmp[0]/2))*basisVectors.at(0)/(nmp[0]-1);
for(unsigned int y = 0; y < nmp[1]; y++){
Vector3d v1;
if(nmp[1]%2 == 0)
v1 = ((int)y - (int)(nmp[1]/2) + 1/2.)*basisVectors.at(1)/(nmp[1]-1);
else
v1 = ((int)y - (int)(nmp[1]/2))*basisVectors.at(1)/(nmp[1]-1);
for(unsigned int z = 0; z < nmp[2]; z++){
Vector3d v2;
if(nmp[2]%2 == 0)
v2 = ((int)z - (int)(nmp[2]/2) + 1/2.)*basisVectors.at(2)/(nmp[2]-1);
else
v2 = ((int)z - (int)(nmp[2]/2))*basisVectors.at(2)/(nmp[2]-1);
if(numMeshPoints.size() == 1){
mesh.push_back({v0.x});
Streams::out << v0.x << "\n";
}
else if(numMeshPoints.size() == 2){
mesh.push_back({
(v0 + v1).x,
(v0 + v1).y
});
}
else if(numMeshPoints.size() == 3){
mesh.push_back({
(v0 + v1 + v2).x,
(v0 + v1 + v2).y,
(v0 + v1 + v2).z
});
}
}
}
}
return mesh;
}
}; //End of namespace TBTK
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include <precomp.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/core/core.hpp>
cv::SCascade::Channels::Channels(int shr) : shrinkage(shr) {}
void cv::SCascade::Channels::appendHogBins(const cv::Mat gray, std::vector<cv::Mat>& integrals, int bins) const
{
CV_Assert(gray.type() == CV_8UC1);
int h = gray.rows;
int w = gray.cols;
CV_Assert(!(w % shrinkage) && !(h % shrinkage));
cv::Mat df_dx, df_dy, mag, angle;
cv::Sobel(gray, df_dx, CV_32F, 1, 0);
cv::Sobel(gray, df_dy, CV_32F, 0, 1);
cv::cartToPolar(df_dx, df_dy, mag, angle, true);
mag *= (1.f / (8 * sqrt(2)));
cv::Mat nmag;
mag.convertTo(nmag, CV_8UC1);
angle /= 60.f;
std::vector<cv::Mat> hist;
for (int bin = 0; bin < bins; ++bin)
hist.push_back(cv::Mat::zeros(h, w, CV_8UC1));
for (int y = 0; y < h; ++y)
{
uchar* magnitude = nmag.ptr<uchar>(y);
float* ang = angle.ptr<float>(y);
for (int x = 0; x < w; ++x)
{
hist[ (int)ang[x] ].ptr<uchar>(y)[x] = magnitude[x];
}
}
for(int i = 0; i < bins; ++i)
{
cv::Mat shrunk, sum;
cv::resize(hist[i], shrunk, cv::Size(), 1.0 / shrinkage, 1.0 / shrinkage, CV_INTER_AREA);
cv::integral(shrunk, sum, cv::noArray(), CV_32S);
integrals.push_back(sum);
}
cv::Mat shrMag;
cv::resize(nmag, shrMag, cv::Size(), 1.0 / shrinkage, 1.0 / shrinkage, CV_INTER_AREA);
cv::integral(shrMag, mag, cv::noArray(), CV_32S);
integrals.push_back(mag);
}
void cv::SCascade::Channels::appendLuvBins(const cv::Mat frame, std::vector<cv::Mat>& integrals) const
{
CV_Assert(frame.type() == CV_8UC3);
CV_Assert(!(frame.cols % shrinkage) && !(frame.rows % shrinkage));
cv::Mat luv, shrunk;
cv::cvtColor(frame, luv, CV_BGR2Luv);
cv::resize(luv, shrunk, cv::Size(), 1.0 / shrinkage, 1.0 / shrinkage, CV_INTER_AREA);
std::vector<cv::Mat> splited;
split(shrunk, splited);
for (size_t i = 0; i < splited.size(); ++i)
{
cv::Mat sum;
cv::integral(splited[i], sum, cv::noArray(), CV_32S);
integrals.push_back(sum);
}
}<commit_msg>fix angle scaling<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include <precomp.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/core/core.hpp>
cv::SCascade::Channels::Channels(int shr) : shrinkage(shr) {}
void cv::SCascade::Channels::appendHogBins(const cv::Mat gray, std::vector<cv::Mat>& integrals, int bins) const
{
CV_Assert(gray.type() == CV_8UC1);
int h = gray.rows;
int w = gray.cols;
CV_Assert(!(w % shrinkage) && !(h % shrinkage));
cv::Mat df_dx, df_dy, mag, angle;
cv::Sobel(gray, df_dx, CV_32F, 1, 0);
cv::Sobel(gray, df_dy, CV_32F, 0, 1);
cv::cartToPolar(df_dx, df_dy, mag, angle, true);
mag *= (1.f / (8 * sqrt(2)));
cv::Mat nmag;
mag.convertTo(nmag, CV_8UC1);
angle *= bins/360.f;
std::vector<cv::Mat> hist;
for (int bin = 0; bin < bins; ++bin)
hist.push_back(cv::Mat::zeros(h, w, CV_8UC1));
for (int y = 0; y < h; ++y)
{
uchar* magnitude = nmag.ptr<uchar>(y);
float* ang = angle.ptr<float>(y);
for (int x = 0; x < w; ++x)
{
hist[ (int)ang[x] ].ptr<uchar>(y)[x] = magnitude[x];
}
}
for(int i = 0; i < bins; ++i)
{
cv::Mat shrunk, sum;
cv::resize(hist[i], shrunk, cv::Size(), 1.0 / shrinkage, 1.0 / shrinkage, CV_INTER_AREA);
cv::integral(shrunk, sum, cv::noArray(), CV_32S);
integrals.push_back(sum);
}
cv::Mat shrMag;
cv::resize(nmag, shrMag, cv::Size(), 1.0 / shrinkage, 1.0 / shrinkage, CV_INTER_AREA);
cv::integral(shrMag, mag, cv::noArray(), CV_32S);
integrals.push_back(mag);
}
void cv::SCascade::Channels::appendLuvBins(const cv::Mat frame, std::vector<cv::Mat>& integrals) const
{
CV_Assert(frame.type() == CV_8UC3);
CV_Assert(!(frame.cols % shrinkage) && !(frame.rows % shrinkage));
cv::Mat luv, shrunk;
cv::cvtColor(frame, luv, CV_BGR2Luv);
cv::resize(luv, shrunk, cv::Size(), 1.0 / shrinkage, 1.0 / shrinkage, CV_INTER_AREA);
std::vector<cv::Mat> splited;
split(shrunk, splited);
for (size_t i = 0; i < splited.size(); ++i)
{
cv::Mat sum;
cv::integral(splited[i], sum, cv::noArray(), CV_32S);
integrals.push_back(sum);
}
}<|endoftext|> |
<commit_before>#include "Players/UCI_Mediator.h"
#include <string>
#include <future>
#include <numeric>
#include <algorithm>
#include "Players/Player.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Game/Game_Result.h"
#include "Moves/Move.h"
#include "Utility/String.h"
UCI_Mediator::UCI_Mediator(const Player& player)
{
send_command("id name " + player.name());
send_command("id author " + player.author());
send_command("option name UCI_Opponent type string default <empty>");
send_command("uciok");
}
void UCI_Mediator::setup_turn(Board& board, Clock& clock, std::vector<const Move*>&)
{
while(true)
{
auto command = receive_uci_command(board, false);
if(command == "ucinewgame")
{
log("stopping thinking and clocks");
board.pick_move_now();
clock = {};
}
else if(String::starts_with(command, "position "))
{
auto parse = String::split(command);
if(parse.at(1) == "startpos")
{
board = Board();
}
else if(parse.at(1) == "fen")
{
auto fen = std::accumulate(std::next(parse.begin(), 3), std::next(parse.begin(), 8),
parse.at(2),
[](const auto& so_far, const auto& next)
{
return so_far + " " + next;
});
board = Board(fen);
}
auto moves_iter = std::find(parse.begin(), parse.end(), "moves");
if(moves_iter != parse.end())
{
std::for_each(std::next(moves_iter), parse.end(),
[&board](const auto& move)
{
board.submit_move(move);
});
log("All moves applied");
}
log("Board ready for play");
board.set_thinking_mode(Thinking_Output_Type::UCI);
}
else if(String::starts_with(command, "go "))
{
set_log_indent(board.whose_turn());
clock = Clock(0, 0, 0, board.whose_turn(), false, clock.game_start_date_and_time());
auto go_parse = String::split(command);
for(size_t i = 1; i < go_parse.size(); ++i)
{
auto option = go_parse.at(i);
double new_time = 0.0;
if(String::ends_with(option, "time") || String::ends_with(option, "inc"))
{
// All times received are in milliseconds
new_time = std::stod(go_parse.at(++i))/1000;
}
if(option == "wtime")
{
log("Setting White's time to " + std::to_string(new_time));
clock.set_time(WHITE, new_time);
}
else if(option == "btime")
{
log("Setting Black's time to " + std::to_string(new_time));
clock.set_time(BLACK, new_time);
}
else if(option == "winc")
{
log("Setting White's increment time to " + std::to_string(new_time));
clock.set_increment(WHITE, new_time);
}
else if(option == "binc")
{
log("Setting Black's increment time to " + std::to_string(new_time));
clock.set_increment(BLACK, new_time);
}
else if(option == "movestogo")
{
auto moves_to_reset = String::string_to_size_t(go_parse.at(++i));
log("Next time control in " + std::to_string(moves_to_reset));
clock.set_next_time_reset(moves_to_reset);
}
else if(option == "movetime")
{
log("Setting clock to " + std::to_string(new_time) + " seconds per move");
clock = Clock(new_time, 1, 0.0, board.whose_turn(), false, clock.game_start_date_and_time());
}
else
{
log("Ignoring go command: " + option);
}
}
log("Telling AI to choose a move at leisure");
board.choose_move_at_leisure();
return;
}
}
}
void UCI_Mediator::listen(Board& board, Clock&)
{
last_listening_result = std::async(std::launch::async, &UCI_Mediator::listener, this, std::ref(board));
}
Game_Result UCI_Mediator::handle_move(Board& board, const Move& move) const
{
send_command("bestmove " + move.coordinate_move());
return board.submit_move(move);
}
bool UCI_Mediator::pondering_allowed() const
{
return true;
}
std::string UCI_Mediator::listener(Board& board)
{
return receive_uci_command(board, true);
}
std::string UCI_Mediator::receive_uci_command(Board& board, bool while_listening)
{
while(true)
{
std::string command;
if(while_listening)
{
command = receive_command();
}
else
{
command = last_listening_result.valid() ? last_listening_result.get() : receive_command();
}
if(command == "isready")
{
send_command("readyok");
}
else if(command == "stop")
{
log("Stopping local AI thinking");
board.pick_move_now();
}
else if(String::starts_with(command, "setoption name UCI_Opponent value "))
{
// command has 8 fields requiring 7 cuts to get name
set_other_player_name(String::split(command, " ", 7).back());
}
else
{
return command;
}
}
}
<commit_msg>Acknowledge receipt of UCI opponent's name<commit_after>#include "Players/UCI_Mediator.h"
#include <string>
#include <future>
#include <numeric>
#include <algorithm>
#include "Players/Player.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Game/Game_Result.h"
#include "Moves/Move.h"
#include "Utility/String.h"
UCI_Mediator::UCI_Mediator(const Player& player)
{
send_command("id name " + player.name());
send_command("id author " + player.author());
send_command("option name UCI_Opponent type string default <empty>");
send_command("uciok");
}
void UCI_Mediator::setup_turn(Board& board, Clock& clock, std::vector<const Move*>&)
{
while(true)
{
auto command = receive_uci_command(board, false);
if(command == "ucinewgame")
{
log("stopping thinking and clocks");
board.pick_move_now();
clock = {};
}
else if(String::starts_with(command, "position "))
{
auto parse = String::split(command);
if(parse.at(1) == "startpos")
{
board = Board();
}
else if(parse.at(1) == "fen")
{
auto fen = std::accumulate(std::next(parse.begin(), 3), std::next(parse.begin(), 8),
parse.at(2),
[](const auto& so_far, const auto& next)
{
return so_far + " " + next;
});
board = Board(fen);
}
auto moves_iter = std::find(parse.begin(), parse.end(), "moves");
if(moves_iter != parse.end())
{
std::for_each(std::next(moves_iter), parse.end(),
[&board](const auto& move)
{
board.submit_move(move);
});
log("All moves applied");
}
log("Board ready for play");
board.set_thinking_mode(Thinking_Output_Type::UCI);
}
else if(String::starts_with(command, "go "))
{
set_log_indent(board.whose_turn());
clock = Clock(0, 0, 0, board.whose_turn(), false, clock.game_start_date_and_time());
auto go_parse = String::split(command);
for(size_t i = 1; i < go_parse.size(); ++i)
{
auto option = go_parse.at(i);
double new_time = 0.0;
if(String::ends_with(option, "time") || String::ends_with(option, "inc"))
{
// All times received are in milliseconds
new_time = std::stod(go_parse.at(++i))/1000;
}
if(option == "wtime")
{
log("Setting White's time to " + std::to_string(new_time));
clock.set_time(WHITE, new_time);
}
else if(option == "btime")
{
log("Setting Black's time to " + std::to_string(new_time));
clock.set_time(BLACK, new_time);
}
else if(option == "winc")
{
log("Setting White's increment time to " + std::to_string(new_time));
clock.set_increment(WHITE, new_time);
}
else if(option == "binc")
{
log("Setting Black's increment time to " + std::to_string(new_time));
clock.set_increment(BLACK, new_time);
}
else if(option == "movestogo")
{
auto moves_to_reset = String::string_to_size_t(go_parse.at(++i));
log("Next time control in " + std::to_string(moves_to_reset));
clock.set_next_time_reset(moves_to_reset);
}
else if(option == "movetime")
{
log("Setting clock to " + std::to_string(new_time) + " seconds per move");
clock = Clock(new_time, 1, 0.0, board.whose_turn(), false, clock.game_start_date_and_time());
}
else
{
log("Ignoring go command: " + option);
}
}
log("Telling AI to choose a move at leisure");
board.choose_move_at_leisure();
return;
}
}
}
void UCI_Mediator::listen(Board& board, Clock&)
{
last_listening_result = std::async(std::launch::async, &UCI_Mediator::listener, this, std::ref(board));
}
Game_Result UCI_Mediator::handle_move(Board& board, const Move& move) const
{
send_command("bestmove " + move.coordinate_move());
return board.submit_move(move);
}
bool UCI_Mediator::pondering_allowed() const
{
return true;
}
std::string UCI_Mediator::listener(Board& board)
{
return receive_uci_command(board, true);
}
std::string UCI_Mediator::receive_uci_command(Board& board, bool while_listening)
{
while(true)
{
std::string command;
if(while_listening)
{
command = receive_command();
}
else
{
command = last_listening_result.valid() ? last_listening_result.get() : receive_command();
}
if(command == "isready")
{
send_command("readyok");
}
else if(command == "stop")
{
log("Stopping local AI thinking");
board.pick_move_now();
}
else if(String::starts_with(command, "setoption name UCI_Opponent value "))
{
// command has 8 fields requiring 7 cuts to get name
set_other_player_name(String::split(command, " ", 7).back());
log("Opponent's name: " + other_player_name());
}
else
{
return command;
}
}
}
<|endoftext|> |
<commit_before>/*
Advent of Code 2016
Day 4: Squares With Three Sides
*/
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <algorithm>
//#define DEBUG
/*******************************************************
** Room object
*******************************************************/
class Room
{
public:
Room(std::string, int, std::string);
bool isReal();
std::string getDecryptedName();
int sectorId;
private:
std::string encryptedName;
std::string checksum;
};
Room::Room(std::string n, int s, std::string c)
{
encryptedName = n;
sectorId = s;
checksum = c;
}
//
// Return if the room is real (or a decoy)
//
bool Room::isReal()
{
std::map<char, unsigned int> charCount;
// Count characters
for (char character : encryptedName)
if( character != '-') charCount[character]++;
// Build vector of pairs
std::vector<std::pair<char, unsigned int>> pairs;
for (auto itr = charCount.begin(); itr != charCount.end(); ++itr)
pairs.push_back(*itr);
// Sort based on frequency and alphabetical order
std::sort(pairs.begin(), pairs.end(), [=](std::pair<char, unsigned int>& a, std::pair<char, unsigned int>& b)
{
return a.second > b.second;
});
// Check checksum
int i = 0;
for (auto itr = pairs.begin(); itr != pairs.begin() + 5; ++itr, i++)
{
if (checksum[i] != (*itr).first)
return false;
}
return true;
}
//
// Return the decrypted room name
//
std::string Room::getDecryptedName()
{
std::string decryptedName = encryptedName;
for (auto itr = decryptedName.begin(); itr != decryptedName.end(); ++itr)
{
if (*itr == '-')
(*itr) = ' ';
else
{
(*itr) = 'a' + (((*itr) - 'a' + sectorId) % 26);
}
}
return decryptedName;
}
/********************************************************
** Method to read room input
********************************************************/
std::vector<Room> readRooms(std::string &fileName)
{
std::vector<Room> vect;
std::string line;
std::ifstream myfile(fileName);
if (myfile.is_open())
{
while (getline(myfile, line))
{
std::size_t sectorIdStart = line.find_last_of("-");
std::size_t checksumStart = line.find("[");
std::string encryptedName = line.substr(0, sectorIdStart);
int sectorId = stoi(line.substr(sectorIdStart + 1, checksumStart - sectorIdStart));
std::string checksum = line.substr(checksumStart + 1, 5);
vect.push_back(Room(encryptedName, sectorId, checksum));
}
myfile.close();
}
#ifdef DEBUG
std::cout << "Read " << vect.size() << " rooms." << std::endl;
#endif
return vect;
}
/********************************************************
** Main
********************************************************/
int main()
{
// Read input file contents
std::string fileName = "AoC2016_04_input.txt";
std::vector<Room> rooms = readRooms(fileName);
int sectorSum = 0;
int northPoleObjectId = 0;
for (std::vector<Room>::iterator itr = rooms.begin(); itr < rooms.end(); ++itr)
{
if ((*itr).isReal() == true)
{
sectorSum += (*itr).sectorId;
std::string decryptedName = (*itr).getDecryptedName();
#ifdef DEBUG
std::cout << "Decrypted name: " << decryptedName << std::endl;
#endif
if (decryptedName == "northpole object storage")
northPoleObjectId = (*itr).sectorId;
}
}
std::cout << "Real room sector ID sum: " << sectorSum << std::endl;
std::cout << "North pole object storage sector ID: " << northPoleObjectId << std::endl;
return 0;
}<commit_msg>Updated day name<commit_after>/*
Advent of Code 2016
Day 4: Security Through Obscurity
*/
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <algorithm>
//#define DEBUG
/*******************************************************
** Room object
*******************************************************/
class Room
{
public:
Room(std::string, int, std::string);
bool isReal();
std::string getDecryptedName();
int sectorId;
private:
std::string encryptedName;
std::string checksum;
};
Room::Room(std::string n, int s, std::string c)
{
encryptedName = n;
sectorId = s;
checksum = c;
}
//
// Return if the room is real (or a decoy)
//
bool Room::isReal()
{
std::map<char, unsigned int> charCount;
// Count characters
for (char character : encryptedName)
if( character != '-') charCount[character]++;
// Build vector of pairs
std::vector<std::pair<char, unsigned int>> pairs;
for (auto itr = charCount.begin(); itr != charCount.end(); ++itr)
pairs.push_back(*itr);
// Sort based on frequency and alphabetical order
std::sort(pairs.begin(), pairs.end(), [=](std::pair<char, unsigned int>& a, std::pair<char, unsigned int>& b)
{
return a.second > b.second;
});
// Check checksum
int i = 0;
for (auto itr = pairs.begin(); itr != pairs.begin() + 5; ++itr, i++)
{
if (checksum[i] != (*itr).first)
return false;
}
return true;
}
//
// Return the decrypted room name
//
std::string Room::getDecryptedName()
{
std::string decryptedName = encryptedName;
for (auto itr = decryptedName.begin(); itr != decryptedName.end(); ++itr)
{
if (*itr == '-')
(*itr) = ' ';
else
{
(*itr) = 'a' + (((*itr) - 'a' + sectorId) % 26);
}
}
return decryptedName;
}
/********************************************************
** Method to read room input
********************************************************/
std::vector<Room> readRooms(std::string &fileName)
{
std::vector<Room> vect;
std::string line;
std::ifstream myfile(fileName);
if (myfile.is_open())
{
while (getline(myfile, line))
{
std::size_t sectorIdStart = line.find_last_of("-");
std::size_t checksumStart = line.find("[");
std::string encryptedName = line.substr(0, sectorIdStart);
int sectorId = stoi(line.substr(sectorIdStart + 1, checksumStart - sectorIdStart));
std::string checksum = line.substr(checksumStart + 1, 5);
vect.push_back(Room(encryptedName, sectorId, checksum));
}
myfile.close();
}
#ifdef DEBUG
std::cout << "Read " << vect.size() << " rooms." << std::endl;
#endif
return vect;
}
/********************************************************
** Main
********************************************************/
int main()
{
// Read input file contents
std::string fileName = "AoC2016_04_input.txt";
std::vector<Room> rooms = readRooms(fileName);
int sectorSum = 0;
int northPoleObjectId = 0;
for (std::vector<Room>::iterator itr = rooms.begin(); itr < rooms.end(); ++itr)
{
if ((*itr).isReal() == true)
{
sectorSum += (*itr).sectorId;
std::string decryptedName = (*itr).getDecryptedName();
#ifdef DEBUG
std::cout << "Decrypted name: " << decryptedName << std::endl;
#endif
if (decryptedName == "northpole object storage")
northPoleObjectId = (*itr).sectorId;
}
}
std::cout << "Real room sector ID sum: " << sectorSum << std::endl;
std::cout << "North pole object storage sector ID: " << northPoleObjectId << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#ifndef _FM_INDEX_FM_INDEX_HPP
#define _FM_INDEX_FM_INDEX_HPP
#include "wavelet_tree_huffman.hpp"
#include "wavelet_tree_binary.hpp"
#include "wavelet_matrix.hpp"
#include <am/succinct/rsdic/RSDic.hpp>
#include <am/succinct/sdarray/SDArray.hpp>
#include <am/succinct/sais/sais.hxx>
#include <algorithm>
NS_IZENELIB_AM_BEGIN
namespace succinct
{
namespace fm_index
{
template <class CharT>
class FMIndex
{
public:
typedef CharT char_type;
FMIndex();
~FMIndex();
void clear();
void addDoc(const char_type *text, size_t len);
void setOrigText(std::vector<char_type> &orig_text);
void build();
void reconstructText(const std::vector<uint32_t> &del_docid_list, std::vector<char_type> &orig_text);
size_t backwardSearch(const char_type *pattern, size_t len, std::pair<size_t, size_t> &match_range) const;
size_t longestSuffixMatch(const char_type *patter, size_t len, std::vector<std::pair<size_t, size_t> > &match_ranges) const;
void getMatchedDocIdList(const std::pair<size_t, size_t> &match_range, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const;
void getMatchedDocIdList(const std::vector<std::pair<size_t, size_t> > &match_ranges, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const;
size_t length() const;
size_t allocSize() const;
size_t bufferLength() const;
size_t docCount() const;
void save(std::ostream &ostr) const;
void load(std::istream &istr);
private:
template <class T>
WaveletTree<T> *getWaveletTree_(size_t charset_size) const
{
if (charset_size <= 65536)
{
return new WaveletTreeHuffman<T>(charset_size);
}
else
{
return new WaveletMatrix<T>(charset_size);
}
}
private:
size_t length_;
size_t alphabet_num_;
sdarray::SDArray doc_delim_;
WaveletTree<char_type> *bwt_tree_;
WaveletTree<uint32_t> *doc_array_;
std::vector<char_type> temp_text_;
};
template <class CharT>
FMIndex<CharT>::FMIndex()
: length_(), alphabet_num_()
, bwt_tree_()
, doc_array_()
{
}
template <class CharT>
FMIndex<CharT>::~FMIndex()
{
if (bwt_tree_) delete bwt_tree_;
if (doc_array_) delete doc_array_;
}
template <class CharT>
void FMIndex<CharT>::clear()
{
length_ = 0;
alphabet_num_ = 0;
doc_delim_.clear();
if (bwt_tree_)
{
delete bwt_tree_;
bwt_tree_ = NULL;
}
if (doc_array_)
{
delete doc_array_;
doc_array_ = NULL;
}
std::vector<char_type>().swap(temp_text_);
}
template <class CharT>
void FMIndex<CharT>::addDoc(const char_type *text, size_t len)
{
temp_text_.insert(temp_text_.end(), text, text + len);
temp_text_.push_back(003);
}
template <class CharT>
void FMIndex<CharT>::setOrigText(std::vector<char_type> &orig_text)
{
temp_text_.swap(orig_text);
}
template <class CharT>
void FMIndex<CharT>::build()
{
temp_text_.push_back('\0');
length_ = temp_text_.size();
alphabet_num_ = WaveletTree<char_type>::getAlphabetNum(&temp_text_[0], length_);
std::vector<int32_t> sa(length_);
if (saisxx(temp_text_.begin(), sa.begin(), (int32_t)length_, (int32_t)alphabet_num_) < 0)
{
std::vector<char_type>().swap(temp_text_);
return;
}
size_t pos = 0;
while (temp_text_[pos] != 003) ++pos;
doc_delim_.add(pos + 1);
for (size_t i = pos + 1; i < length_; ++i)
{
if (temp_text_[i] == 003)
{
doc_delim_.add(i - pos);
pos = i;
}
}
doc_delim_.build();
std::vector<char_type> bwt(length_);
for (size_t i = 0; i < length_; ++i)
{
if (sa[i] == 0)
{
bwt[i] = temp_text_[length_ - 1];
sa[i] = docCount();
}
else
{
bwt[i] = temp_text_[sa[i] - 1];
sa[i] = doc_delim_.find(sa[i]);
}
}
std::vector<char_type>().swap(temp_text_);
bwt_tree_ = getWaveletTree_<char_type>(alphabet_num_);
bwt_tree_->build(&bwt[0], length_);
std::vector<char_type>().swap(bwt);
doc_array_ = getWaveletTree_<uint32_t>(docCount());
doc_array_->build((uint32_t *)&sa[0], length_);
std::vector<int32_t>().swap(sa);
--length_;
}
template <class CharT>
void FMIndex<CharT>::reconstructText(const std::vector<uint32_t> &del_docid_list, std::vector<char_type> &orig_text)
{
orig_text.resize(length_);
size_t pos = 0;
char_type c;
for (size_t i = 0; i < length_; ++i)
{
c = bwt_tree_->access(pos, pos);
orig_text[length_ - i - 1] = c;
pos += bwt_tree_->getOcc(c);
}
if (del_docid_list.empty() || del_docid_list[0] > doc_delim_.size()) return;
size_t old_pos = doc_delim_.prefixSum(del_docid_list[0] - 1);
size_t new_pos = doc_delim_.prefixSum(del_docid_list[0]) - 1;
for (size_t i = 1; i < del_docid_list.size() && del_docid_list[i] <= doc_delim_.size(); ++i)
{
pos = doc_delim_.prefixSum(del_docid_list[i] - 1);
if (old_pos == new_pos)
{
old_pos = pos;
}
else
{
for (; new_pos < pos; ++old_pos, ++new_pos)
{
orig_text[old_pos] = orig_text[new_pos];
}
}
new_pos = doc_delim_.prefixSum(del_docid_list[i]) - 1;
}
if (old_pos != new_pos)
{
for (; new_pos < length_; ++old_pos, ++new_pos)
{
orig_text[old_pos] = orig_text[new_pos];
}
orig_text.resize(old_pos);
}
}
template <class CharT>
size_t FMIndex<CharT>::backwardSearch(const char_type *pattern, size_t len, std::pair<size_t, size_t> &match_range) const
{
size_t orig_len = len;
char_type c = pattern[--len];
size_t occ;
size_t sp = bwt_tree_->getOcc(c);
size_t ep = bwt_tree_->getOcc(c + 1);
if (sp == ep) return 0;
match_range.first = sp;
match_range.second = ep;
for (; len > 0; --len)
{
c = pattern[len - 1];
occ = bwt_tree_->getOcc(c);
sp = occ + bwt_tree_->rank(c, sp);
ep = occ + bwt_tree_->rank(c, ep);
if (sp == ep) break;
match_range.first = sp;
match_range.second = ep;
}
return orig_len - len;
}
template <class CharT>
size_t FMIndex<CharT>::longestSuffixMatch(const char_type *pattern, size_t len, std::vector<std::pair<size_t, size_t> > &match_ranges) const
{
std::pair<size_t, size_t> match_range;
std::vector<std::pair<size_t, size_t> > prune_bounds(len);
size_t max_match = 0;
char_type c;
size_t occ, sp, ep;
size_t i, j;
for (i = len; i > max_match; --i)
{
c = pattern[i - 1];
sp = bwt_tree_->getOcc(c);
ep = bwt_tree_->getOcc(c + 1);
if (ep - sp <= prune_bounds[i - 1].second - prune_bounds[i - 1].first)
goto PRUNED;
match_range.first = sp;
match_range.second = ep;
prune_bounds[i - 1] = match_range;
for (j = i - 1; j > 0; --j)
{
c = pattern[j - 1];
occ = bwt_tree_->getOcc(c);
sp = occ + bwt_tree_->rank(c, sp);
ep = occ + bwt_tree_->rank(c, ep);
if (sp == ep) break;
if (ep - sp <= prune_bounds[j - 1].second - prune_bounds[j - 1].first)
goto PRUNED;
match_range.first = sp;
match_range.second = ep;
prune_bounds[j - 1] = match_range;
}
if (max_match < i - j)
{
max_match = i - j;
match_ranges.clear();
match_ranges.push_back(match_range);
}
else if (max_match == i - j)
{
match_ranges.push_back(match_range);
}
PRUNED:
assert(true);
}
return max_match;
}
template <class CharT>
void FMIndex<CharT>::getMatchedDocIdList(const std::pair<size_t, size_t> &match_range, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const
{
for (size_t i = match_range.first; i < match_range.second; ++i)
{
docid_list.push_back(doc_array_->access(i) + 1);
if (docid_list.size() == max_docs) break;
}
std::sort(docid_list.begin(), docid_list.end());
docid_list.erase(std::unique(docid_list.begin(), docid_list.end()), docid_list.end());
doclen_list.resize(docid_list.size());
for (size_t i = 0; i < docid_list.size(); ++i)
{
doclen_list[i] = doc_delim_.getVal(docid_list[i] - 1) - 1;
}
}
template <class CharT>
void FMIndex<CharT>::getMatchedDocIdList(const std::vector<std::pair<size_t, size_t> > &match_ranges, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const
{
for (std::vector<std::pair<size_t, size_t> >::const_iterator it = match_ranges.begin();
it != match_ranges.end(); ++it)
{
for (size_t i = it->first; i < it->second; ++i)
{
docid_list.push_back(doc_array_->access(i) + 1);
if (docid_list.size() == max_docs) goto EXIT;
}
}
EXIT:
std::sort(docid_list.begin(), docid_list.end());
docid_list.erase(std::unique(docid_list.begin(), docid_list.end()), docid_list.end());
doclen_list.resize(docid_list.size());
for (size_t i = 0; i < docid_list.size(); ++i)
{
doclen_list[i] = doc_delim_.getVal(docid_list[i] - 1) - 1;
}
}
template <class CharT>
size_t FMIndex<CharT>::length() const
{
return length_;
}
template <class CharT>
size_t FMIndex<CharT>::allocSize() const
{
return sizeof(FMIndex)
+ doc_delim_.allocSize() - sizeof(sdarray::SDArray)
+ bwt_tree_->allocSize() + doc_array_->allocSize();
}
template <class CharT>
size_t FMIndex<CharT>::bufferLength() const
{
return temp_text_.size();
}
template <class CharT>
size_t FMIndex<CharT>::docCount() const
{
return doc_delim_.size();
}
template <class CharT>
void FMIndex<CharT>::save(std::ostream &ostr) const
{
ostr.write((const char *)&length_, sizeof(length_));
ostr.write((const char *)&alphabet_num_, sizeof(alphabet_num_));
doc_delim_.save(ostr);
bwt_tree_->save(ostr);
doc_array_->save(ostr);
}
template <class CharT>
void FMIndex<CharT>::load(std::istream &istr)
{
istr.read((char *)&length_, sizeof(length_));
istr.read((char *)&alphabet_num_, sizeof(alphabet_num_));
doc_delim_.load(istr);
bwt_tree_ = getWaveletTree_<char_type>(alphabet_num_);
bwt_tree_->load(istr);
doc_array_ = getWaveletTree_<uint32_t>(docCount());
doc_array_->load(istr);
}
}
}
NS_IZENELIB_AM_END
#endif
<commit_msg>tiny fix<commit_after>#ifndef _FM_INDEX_FM_INDEX_HPP
#define _FM_INDEX_FM_INDEX_HPP
#include "wavelet_tree_huffman.hpp"
#include "wavelet_tree_binary.hpp"
#include "wavelet_matrix.hpp"
#include <am/succinct/rsdic/RSDic.hpp>
#include <am/succinct/sdarray/SDArray.hpp>
#include <am/succinct/sais/sais.hxx>
#include <algorithm>
NS_IZENELIB_AM_BEGIN
namespace succinct
{
namespace fm_index
{
template <class CharT>
class FMIndex
{
public:
typedef CharT char_type;
FMIndex();
~FMIndex();
void clear();
void addDoc(const char_type *text, size_t len);
void setOrigText(std::vector<char_type> &orig_text);
void build();
void reconstructText(const std::vector<uint32_t> &del_docid_list, std::vector<char_type> &orig_text);
size_t backwardSearch(const char_type *pattern, size_t len, std::pair<size_t, size_t> &match_range) const;
size_t longestSuffixMatch(const char_type *patter, size_t len, std::vector<std::pair<size_t, size_t> > &match_ranges) const;
void getMatchedDocIdList(const std::pair<size_t, size_t> &match_range, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const;
void getMatchedDocIdList(const std::vector<std::pair<size_t, size_t> > &match_ranges, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const;
size_t length() const;
size_t allocSize() const;
size_t bufferLength() const;
size_t docCount() const;
void save(std::ostream &ostr) const;
void load(std::istream &istr);
private:
template <class T>
WaveletTree<T> *getWaveletTree_(size_t charset_size) const
{
if (charset_size <= 65536)
{
return new WaveletTreeHuffman<T>(charset_size);
}
else
{
return new WaveletMatrix<T>(charset_size);
}
}
private:
size_t length_;
size_t alphabet_num_;
sdarray::SDArray doc_delim_;
WaveletTree<char_type> *bwt_tree_;
WaveletTree<uint32_t> *doc_array_;
std::vector<char_type> temp_text_;
};
template <class CharT>
FMIndex<CharT>::FMIndex()
: length_(), alphabet_num_()
, bwt_tree_()
, doc_array_()
{
}
template <class CharT>
FMIndex<CharT>::~FMIndex()
{
if (bwt_tree_) delete bwt_tree_;
if (doc_array_) delete doc_array_;
}
template <class CharT>
void FMIndex<CharT>::clear()
{
length_ = 0;
alphabet_num_ = 0;
doc_delim_.clear();
if (bwt_tree_)
{
delete bwt_tree_;
bwt_tree_ = NULL;
}
if (doc_array_)
{
delete doc_array_;
doc_array_ = NULL;
}
std::vector<char_type>().swap(temp_text_);
}
template <class CharT>
void FMIndex<CharT>::addDoc(const char_type *text, size_t len)
{
temp_text_.insert(temp_text_.end(), text, text + len);
temp_text_.push_back(003);
}
template <class CharT>
void FMIndex<CharT>::setOrigText(std::vector<char_type> &orig_text)
{
temp_text_.swap(orig_text);
}
template <class CharT>
void FMIndex<CharT>::build()
{
temp_text_.push_back('\0');
length_ = temp_text_.size();
alphabet_num_ = WaveletTree<char_type>::getAlphabetNum(&temp_text_[0], length_);
std::vector<int32_t> sa(length_);
if (saisxx(temp_text_.begin(), sa.begin(), (int32_t)length_, (int32_t)alphabet_num_) < 0)
{
std::vector<char_type>().swap(temp_text_);
return;
}
size_t pos = 0;
while (temp_text_[pos] != 003) ++pos;
doc_delim_.add(pos + 1);
for (size_t i = pos + 1; i < length_; ++i)
{
if (temp_text_[i] == 003)
{
doc_delim_.add(i - pos);
pos = i;
}
}
doc_delim_.build();
std::vector<char_type> bwt(length_);
for (size_t i = 0; i < length_; ++i)
{
if (sa[i] == 0)
{
bwt[i] = temp_text_[length_ - 1];
sa[i] = docCount();
}
else
{
bwt[i] = temp_text_[sa[i] - 1];
sa[i] = doc_delim_.find(sa[i]);
}
}
std::vector<char_type>().swap(temp_text_);
bwt_tree_ = getWaveletTree_<char_type>(alphabet_num_);
bwt_tree_->build(&bwt[0], length_);
std::vector<char_type>().swap(bwt);
doc_array_ = getWaveletTree_<uint32_t>(docCount());
doc_array_->build((uint32_t *)&sa[0], length_);
std::vector<int32_t>().swap(sa);
--length_;
}
template <class CharT>
void FMIndex<CharT>::reconstructText(const std::vector<uint32_t> &del_docid_list, std::vector<char_type> &orig_text)
{
orig_text.resize(length_);
size_t pos = 0;
char_type c;
for (size_t i = 0; i < length_; ++i)
{
c = bwt_tree_->access(pos, pos);
orig_text[length_ - i - 1] = c;
pos += bwt_tree_->getOcc(c);
}
if (del_docid_list.empty() || del_docid_list[0] > doc_delim_.size()) return;
size_t old_pos = doc_delim_.prefixSum(del_docid_list[0] - 1);
size_t new_pos = doc_delim_.prefixSum(del_docid_list[0]) - 1;
for (size_t i = 1; i < del_docid_list.size() && del_docid_list[i] <= doc_delim_.size(); ++i)
{
pos = doc_delim_.prefixSum(del_docid_list[i] - 1);
if (old_pos == new_pos)
{
old_pos = pos;
}
else
{
for (; new_pos < pos; ++old_pos, ++new_pos)
{
orig_text[old_pos] = orig_text[new_pos];
}
}
new_pos = doc_delim_.prefixSum(del_docid_list[i]) - 1;
}
if (old_pos != new_pos)
{
for (; new_pos < length_; ++old_pos, ++new_pos)
{
orig_text[old_pos] = orig_text[new_pos];
}
orig_text.resize(old_pos);
}
}
template <class CharT>
size_t FMIndex<CharT>::backwardSearch(const char_type *pattern, size_t len, std::pair<size_t, size_t> &match_range) const
{
if (len == 0) return 0;
size_t orig_len = len;
char_type c = pattern[--len];
size_t occ;
size_t sp = bwt_tree_->getOcc(c);
size_t ep = bwt_tree_->getOcc(c + 1);
if (sp == ep) return 0;
match_range.first = sp;
match_range.second = ep;
for (; len > 0; --len)
{
c = pattern[len - 1];
occ = bwt_tree_->getOcc(c);
sp = occ + bwt_tree_->rank(c, sp);
ep = occ + bwt_tree_->rank(c, ep);
if (sp == ep) break;
match_range.first = sp;
match_range.second = ep;
}
return orig_len - len;
}
template <class CharT>
size_t FMIndex<CharT>::longestSuffixMatch(const char_type *pattern, size_t len, std::vector<std::pair<size_t, size_t> > &match_ranges) const
{
if (len == 0) return 0;
std::pair<size_t, size_t> match_range;
std::vector<std::pair<size_t, size_t> > prune_bounds(len);
size_t max_match = 0;
char_type c;
size_t occ, sp, ep;
size_t i, j;
for (i = len; i > max_match; --i)
{
c = pattern[i - 1];
sp = bwt_tree_->getOcc(c);
ep = bwt_tree_->getOcc(c + 1);
if (ep - sp <= prune_bounds[i - 1].second - prune_bounds[i - 1].first)
goto PRUNED;
match_range.first = sp;
match_range.second = ep;
prune_bounds[i - 1] = match_range;
for (j = i - 1; j > 0; --j)
{
c = pattern[j - 1];
occ = bwt_tree_->getOcc(c);
sp = occ + bwt_tree_->rank(c, sp);
ep = occ + bwt_tree_->rank(c, ep);
if (sp == ep) break;
if (ep - sp <= prune_bounds[j - 1].second - prune_bounds[j - 1].first)
goto PRUNED;
match_range.first = sp;
match_range.second = ep;
prune_bounds[j - 1] = match_range;
}
if (max_match < i - j)
{
max_match = i - j;
match_ranges.clear();
match_ranges.push_back(match_range);
}
else if (max_match == i - j)
{
match_ranges.push_back(match_range);
}
PRUNED:
assert(true);
}
return max_match;
}
template <class CharT>
void FMIndex<CharT>::getMatchedDocIdList(const std::pair<size_t, size_t> &match_range, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const
{
for (size_t i = match_range.first; i < match_range.second; ++i)
{
docid_list.push_back(doc_array_->access(i) + 1);
if (docid_list.size() == max_docs) break;
}
std::sort(docid_list.begin(), docid_list.end());
docid_list.erase(std::unique(docid_list.begin(), docid_list.end()), docid_list.end());
doclen_list.resize(docid_list.size());
for (size_t i = 0; i < docid_list.size(); ++i)
{
doclen_list[i] = doc_delim_.getVal(docid_list[i] - 1) - 1;
}
}
template <class CharT>
void FMIndex<CharT>::getMatchedDocIdList(const std::vector<std::pair<size_t, size_t> > &match_ranges, size_t max_docs, std::vector<uint32_t> &docid_list, std::vector<size_t> &doclen_list) const
{
for (std::vector<std::pair<size_t, size_t> >::const_iterator it = match_ranges.begin();
it != match_ranges.end(); ++it)
{
for (size_t i = it->first; i < it->second; ++i)
{
docid_list.push_back(doc_array_->access(i) + 1);
if (docid_list.size() == max_docs) goto EXIT;
}
}
EXIT:
std::sort(docid_list.begin(), docid_list.end());
docid_list.erase(std::unique(docid_list.begin(), docid_list.end()), docid_list.end());
doclen_list.resize(docid_list.size());
for (size_t i = 0; i < docid_list.size(); ++i)
{
doclen_list[i] = doc_delim_.getVal(docid_list[i] - 1) - 1;
}
}
template <class CharT>
size_t FMIndex<CharT>::length() const
{
return length_;
}
template <class CharT>
size_t FMIndex<CharT>::allocSize() const
{
return sizeof(FMIndex)
+ doc_delim_.allocSize() - sizeof(sdarray::SDArray)
+ bwt_tree_->allocSize() + doc_array_->allocSize();
}
template <class CharT>
size_t FMIndex<CharT>::bufferLength() const
{
return temp_text_.size();
}
template <class CharT>
size_t FMIndex<CharT>::docCount() const
{
return doc_delim_.size();
}
template <class CharT>
void FMIndex<CharT>::save(std::ostream &ostr) const
{
ostr.write((const char *)&length_, sizeof(length_));
ostr.write((const char *)&alphabet_num_, sizeof(alphabet_num_));
doc_delim_.save(ostr);
bwt_tree_->save(ostr);
doc_array_->save(ostr);
}
template <class CharT>
void FMIndex<CharT>::load(std::istream &istr)
{
istr.read((char *)&length_, sizeof(length_));
istr.read((char *)&alphabet_num_, sizeof(alphabet_num_));
doc_delim_.load(istr);
bwt_tree_ = getWaveletTree_<char_type>(alphabet_num_);
bwt_tree_->load(istr);
doc_array_ = getWaveletTree_<uint32_t>(docCount());
doc_array_->load(istr);
}
}
}
NS_IZENELIB_AM_END
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#ifdef ENABLE_QUICKSTART_APPLET
#include <unotools/moduleoptions.hxx>
#include <unotools/dynamicmenuoptions.hxx>
#include <gtk/gtk.h>
#include <glib.h>
#include <osl/mutex.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/bmpacc.hxx>
#include <sfx2/app.hxx>
#include "app.hrc"
#ifndef __SHUTDOWNICON_HXX__
#define USE_APP_SHORTCUTS
#include "shutdownicon.hxx"
#endif
#ifdef ENABLE_GIO
#include <gio/gio.h>
#endif
// Cut/paste from vcl/inc/svids.hrc
#define SV_ICON_SMALL_START 25000
#define SV_ICON_ID_OFFICE 1
#define SV_ICON_ID_TEXT 2
#define SV_ICON_ID_SPREADSHEET 4
#define SV_ICON_ID_DRAWING 6
#define SV_ICON_ID_PRESENTATION 8
#define SV_ICON_ID_DATABASE 14
#define SV_ICON_ID_FORMULA 15
#define SV_ICON_ID_TEMPLATE 16
using namespace ::rtl;
using namespace ::osl;
static ResMgr *pVCLResMgr;
static GtkStatusIcon* pTrayIcon;
static GtkWidget *pExitMenuItem = NULL;
static GtkWidget *pOpenMenuItem = NULL;
static GtkWidget *pDisableMenuItem = NULL;
#ifdef ENABLE_GIO
GFileMonitor* pMonitor = NULL;
#endif
static void open_url_cb( GtkWidget *, gpointer data )
{
ShutdownIcon::OpenURL( *(OUString *)data,
OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
}
static void open_file_cb( GtkWidget * )
{
if ( !ShutdownIcon::bModalMode )
ShutdownIcon::FileOpen();
}
static void open_template_cb( GtkWidget * )
{
if ( !ShutdownIcon::bModalMode )
ShutdownIcon::FromTemplate();
}
static void systray_disable_cb()
{
ShutdownIcon::SetAutostart( false );
ShutdownIcon::terminateDesktop();
}
static void exit_quickstarter_cb( GtkWidget * )
{
plugin_shutdown_sys_tray();
//terminate may cause this .so to be unloaded. So we must be hands off
//all calls into this .so after this call
ShutdownIcon::terminateDesktop();
}
static void menu_deactivate_cb( GtkWidget *pMenu )
{
gtk_menu_popdown( GTK_MENU( pMenu ) );
}
static GdkPixbuf * ResIdToPixbuf( sal_uInt16 nResId )
{
ResId aResId( SV_ICON_SMALL_START + nResId, *pVCLResMgr );
BitmapEx aIcon( aResId );
Bitmap pInSalBitmap = aIcon.GetBitmap();
AlphaMask pInSalAlpha = aIcon.GetAlpha();
BitmapReadAccess* pSalBitmap = pInSalBitmap.AcquireReadAccess();
BitmapReadAccess* pSalAlpha = pInSalAlpha.AcquireReadAccess();
g_return_val_if_fail( pSalBitmap != NULL, NULL );
Size aSize( pSalBitmap->Width(), pSalBitmap->Height() );
if (pSalAlpha)
g_return_val_if_fail( Size( pSalAlpha->Width(), pSalAlpha->Height() ) == aSize, NULL );
int nX, nY;
guchar *pPixbufData = ( guchar * )g_malloc( 4 * aSize.Width() * aSize.Height() );
guchar *pDestData = pPixbufData;
for( nY = 0; nY < pSalBitmap->Height(); nY++ )
{
for( nX = 0; nX < pSalBitmap->Width(); nX++ )
{
BitmapColor aPix;
aPix = pSalBitmap->GetPixel( nY, nX );
pDestData[0] = aPix.GetRed();
pDestData[1] = aPix.GetGreen();
pDestData[2] = aPix.GetBlue();
if (pSalAlpha)
{
aPix = pSalAlpha->GetPixel( nY, nX );
pDestData[3] = 255 - aPix.GetIndex();
}
else
pDestData[3] = 255;
pDestData += 4;
}
}
pInSalBitmap.ReleaseAccess( pSalBitmap );
if( pSalAlpha )
pInSalAlpha.ReleaseAccess( pSalAlpha );
return gdk_pixbuf_new_from_data( pPixbufData,
GDK_COLORSPACE_RGB, sal_True, 8,
aSize.Width(), aSize.Height(),
aSize.Width() * 4,
(GdkPixbufDestroyNotify) g_free,
NULL );
}
extern "C" {
static void oustring_delete (gpointer data,
GClosure * /* closure */)
{
OUString *pURL = (OUString *) data;
delete pURL;
}
}
static void add_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
OUString *pOverrideLabel,
sal_uInt16 nResId, GCallback pFnCallback )
{
OUString *pURL = new OUString (OStringToOUString( pAsciiURL,
RTL_TEXTENCODING_UTF8 ));
OString aLabel;
if (pOverrideLabel)
aLabel = OUStringToOString (*pOverrideLabel, RTL_TEXTENCODING_UTF8);
else
{
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
aLabel = OUStringToOString (pShutdownIcon->GetUrlDescription( *pURL ),
RTL_TEXTENCODING_UTF8);
}
GdkPixbuf *pPixbuf= ResIdToPixbuf( nResId );
GtkWidget *pImage = gtk_image_new_from_pixbuf( pPixbuf );
g_object_unref( G_OBJECT( pPixbuf ) );
GtkWidget *pMenuItem = gtk_image_menu_item_new_with_label( aLabel );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );
g_signal_connect_data( pMenuItem, "activate", pFnCallback, pURL,
oustring_delete, GConnectFlags(0));
gtk_menu_shell_append( pMenuShell, pMenuItem );
}
// Unbelievably nasty
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
static void add_ugly_db_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
sal_uInt16 nResId, GCallback pFnCallback )
{
SvtDynamicMenuOptions aOpt;
Sequence < Sequence < PropertyValue > > aMenu = aOpt.GetMenu( E_NEWMENU );
for ( sal_Int32 n=0; n<aMenu.getLength(); n++ )
{
::rtl::OUString aURL;
::rtl::OUString aDescription;
Sequence < PropertyValue >& aEntry = aMenu[n];
for ( sal_Int32 m=0; m<aEntry.getLength(); m++ )
{
if ( aEntry[m].Name.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("URL")) )
aEntry[m].Value >>= aURL;
if ( aEntry[m].Name.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Title")) )
aEntry[m].Value >>= aDescription;
}
if ( aURL.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(BASE_URL)) && aDescription.getLength() )
{
add_item (pMenuShell, pAsciiURL, &aDescription, nResId, pFnCallback);
break;
}
}
}
static GtkWidget *
add_image_menu_item( GtkMenuShell *pMenuShell,
const gchar *stock_id,
rtl::OUString aLabel,
GCallback activate_cb )
{
OString aUtfLabel = rtl::OUStringToOString (aLabel, RTL_TEXTENCODING_UTF8 );
GtkWidget *pImage;
pImage = gtk_image_new_from_stock( stock_id, GTK_ICON_SIZE_MENU );
GtkWidget *pMenuItem;
pMenuItem = gtk_image_menu_item_new_with_label( aUtfLabel );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );
gtk_menu_shell_append( pMenuShell, pMenuItem );
g_signal_connect( pMenuItem, "activate", activate_cb, NULL);
return pMenuItem;
}
static void populate_menu( GtkWidget *pMenu )
{
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
GtkMenuShell *pMenuShell = GTK_MENU_SHELL( pMenu );
SvtModuleOptions aModuleOptions;
if ( aModuleOptions.IsWriter() )
add_item (pMenuShell, WRITER_URL, NULL,
SV_ICON_ID_TEXT, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsCalc() )
add_item (pMenuShell, CALC_URL, NULL,
SV_ICON_ID_SPREADSHEET, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsImpress() )
add_item (pMenuShell, IMPRESS_URL, NULL,
SV_ICON_ID_PRESENTATION, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsDraw() )
add_item (pMenuShell, DRAW_URL, NULL,
SV_ICON_ID_DRAWING, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsDataBase() )
add_ugly_db_item (pMenuShell, BASE_URL,
SV_ICON_ID_DATABASE, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsMath() )
add_item (pMenuShell, MATH_URL, NULL,
SV_ICON_ID_FORMULA, G_CALLBACK( open_url_cb ));
OUString aULabel = pShutdownIcon->GetResString( STR_QUICKSTART_FROMTEMPLATE );
add_item (pMenuShell, "dummy", &aULabel,
SV_ICON_ID_TEMPLATE, G_CALLBACK( open_template_cb ));
OString aLabel;
GtkWidget *pMenuItem;
pMenuItem = gtk_separator_menu_item_new();
gtk_menu_shell_append( pMenuShell, pMenuItem );
pOpenMenuItem = add_image_menu_item
(pMenuShell, GTK_STOCK_OPEN,
pShutdownIcon->GetResString( STR_QUICKSTART_FILEOPEN ),
G_CALLBACK( open_file_cb ));
pMenuItem = gtk_separator_menu_item_new();
gtk_menu_shell_append( pMenuShell, pMenuItem );
pDisableMenuItem = add_image_menu_item
( pMenuShell, GTK_STOCK_CLOSE,
pShutdownIcon->GetResString( STR_QUICKSTART_PRELAUNCH_UNX ),
G_CALLBACK( systray_disable_cb ) );
pMenuItem = gtk_separator_menu_item_new();
gtk_menu_shell_append( pMenuShell, pMenuItem );
pExitMenuItem = add_image_menu_item
( pMenuShell, GTK_STOCK_QUIT,
pShutdownIcon->GetResString( STR_QUICKSTART_EXIT ),
G_CALLBACK( exit_quickstarter_cb ) );
gtk_widget_show_all( pMenu );
}
static void refresh_menu( GtkWidget *pMenu )
{
if (!pExitMenuItem)
populate_menu( pMenu );
bool bModal = ShutdownIcon::bModalMode;
gtk_widget_set_sensitive( pExitMenuItem, !bModal);
gtk_widget_set_sensitive( pOpenMenuItem, !bModal);
gtk_widget_set_sensitive( pDisableMenuItem, !bModal);
}
static gboolean display_menu_cb( GtkWidget *,
GdkEventButton *event, GtkWidget *pMenu )
{
if (event->button == 2)
return sal_False;
refresh_menu( pMenu );
gtk_menu_popup( GTK_MENU( pMenu ), NULL, NULL,
gtk_status_icon_position_menu, pTrayIcon,
0, event->time );
return sal_True;
}
#ifdef ENABLE_GIO
/*
* If the quickstarter is running, then LibreOffice is
* upgraded, then the old quickstarter is still running, but is now unreliable
* as the old install has been deleted. A fairly intractable problem but we
* can avoid much of the pain if we turn off the quickstarter if we detect
* that it has been physically deleted or overwritten
*/
static void notify_file_changed(GFileMonitor * /*gfilemonitor*/, GFile * /*arg1*/,
GFile * /*arg2*/, GFileMonitorEvent event_type, gpointer /*user_data*/)
{
//Shutdown the quick starter if anything has happened to make it unsafe
//to remain running, e.g. rpm --erased and all libs deleted, or
//rpm --upgrade and libs being overwritten
switch (event_type)
{
case G_FILE_MONITOR_EVENT_DELETED:
case G_FILE_MONITOR_EVENT_CREATED:
case G_FILE_MONITOR_EVENT_PRE_UNMOUNT:
case G_FILE_MONITOR_EVENT_UNMOUNTED:
exit_quickstarter_cb(GTK_WIDGET(pTrayIcon));
break;
default:
break;
}
}
#endif
void SAL_DLLPUBLIC_EXPORT plugin_init_sys_tray()
{
::SolarMutexGuard aGuard;
if( /* need gtk_status to resolve */
(gtk_check_version( 2, 10, 0 ) != NULL) ||
/* we need the vcl plugin and mainloop initialized */
!g_type_from_name( "GdkDisplay" ) )
return;
OString aLabel;
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
aLabel = rtl::OUStringToOString (
pShutdownIcon->GetResString( STR_QUICKSTART_TIP ),
RTL_TEXTENCODING_UTF8 );
pVCLResMgr = CREATEVERSIONRESMGR( vcl );
GdkPixbuf *pPixbuf = ResIdToPixbuf( SV_ICON_ID_OFFICE );
pTrayIcon = gtk_status_icon_new_from_pixbuf(pPixbuf);
g_object_unref( pPixbuf );
g_object_set (pTrayIcon, "title", aLabel.getStr(),
"tooltip_text", aLabel.getStr(), NULL);
GtkWidget *pMenu = gtk_menu_new();
g_signal_connect (pMenu, "deactivate",
G_CALLBACK (menu_deactivate_cb), NULL);
g_signal_connect(pTrayIcon, "button_press_event",
G_CALLBACK(display_menu_cb), pMenu);
// disable shutdown
pShutdownIcon->SetVeto( true );
pShutdownIcon->addTerminateListener();
#ifdef ENABLE_GIO
GFile* pFile = NULL;
rtl::OUString sLibraryFileUrl;
if (osl::Module::getUrlFromAddress(plugin_init_sys_tray, sLibraryFileUrl))
pFile = g_file_new_for_uri(rtl::OUStringToOString(sLibraryFileUrl, RTL_TEXTENCODING_UTF8).getStr());
if (pFile)
{
if ((pMonitor = g_file_monitor_file(pFile, G_FILE_MONITOR_NONE, NULL, NULL)))
g_signal_connect(pMonitor, "changed", (GCallback)notify_file_changed, NULL);
g_object_unref(pFile);
}
#endif
}
void SAL_DLLPUBLIC_EXPORT plugin_shutdown_sys_tray()
{
::SolarMutexGuard aGuard;
if( !pTrayIcon )
return;
#ifdef ENABLE_GIO
if (pMonitor)
{
g_signal_handlers_disconnect_by_func(pMonitor,
(void*)notify_file_changed, pMonitor);
g_file_monitor_cancel(pMonitor);
g_object_unref(pMonitor);
pMonitor = NULL;
}
#endif
g_object_unref(pTrayIcon);
pTrayIcon = NULL;
pExitMenuItem = NULL;
pOpenMenuItem = NULL;
pDisableMenuItem = NULL;
}
#endif // ENABLE_QUICKSTART_APPLET
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>avoid memory leak<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#ifdef ENABLE_QUICKSTART_APPLET
#include <unotools/moduleoptions.hxx>
#include <unotools/dynamicmenuoptions.hxx>
#include <gtk/gtk.h>
#include <glib.h>
#include <osl/mutex.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/bmpacc.hxx>
#include <sfx2/app.hxx>
#include "app.hrc"
#ifndef __SHUTDOWNICON_HXX__
#define USE_APP_SHORTCUTS
#include "shutdownicon.hxx"
#endif
#ifdef ENABLE_GIO
#include <gio/gio.h>
#endif
// Cut/paste from vcl/inc/svids.hrc
#define SV_ICON_SMALL_START 25000
#define SV_ICON_ID_OFFICE 1
#define SV_ICON_ID_TEXT 2
#define SV_ICON_ID_SPREADSHEET 4
#define SV_ICON_ID_DRAWING 6
#define SV_ICON_ID_PRESENTATION 8
#define SV_ICON_ID_DATABASE 14
#define SV_ICON_ID_FORMULA 15
#define SV_ICON_ID_TEMPLATE 16
using namespace ::rtl;
using namespace ::osl;
static ResMgr *pVCLResMgr;
static GtkStatusIcon* pTrayIcon;
static GtkWidget *pExitMenuItem = NULL;
static GtkWidget *pOpenMenuItem = NULL;
static GtkWidget *pDisableMenuItem = NULL;
#ifdef ENABLE_GIO
GFileMonitor* pMonitor = NULL;
#endif
static void open_url_cb( GtkWidget *, gpointer data )
{
ShutdownIcon::OpenURL( *(OUString *)data,
OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
}
static void open_file_cb( GtkWidget * )
{
if ( !ShutdownIcon::bModalMode )
ShutdownIcon::FileOpen();
}
static void open_template_cb( GtkWidget * )
{
if ( !ShutdownIcon::bModalMode )
ShutdownIcon::FromTemplate();
}
static void systray_disable_cb()
{
ShutdownIcon::SetAutostart( false );
ShutdownIcon::terminateDesktop();
}
static void exit_quickstarter_cb( GtkWidget * )
{
plugin_shutdown_sys_tray();
//terminate may cause this .so to be unloaded. So we must be hands off
//all calls into this .so after this call
ShutdownIcon::terminateDesktop();
}
static void menu_deactivate_cb( GtkWidget *pMenu )
{
gtk_menu_popdown( GTK_MENU( pMenu ) );
}
static GdkPixbuf * ResIdToPixbuf( sal_uInt16 nResId )
{
ResId aResId( SV_ICON_SMALL_START + nResId, *pVCLResMgr );
BitmapEx aIcon( aResId );
Bitmap pInSalBitmap = aIcon.GetBitmap();
AlphaMask pInSalAlpha = aIcon.GetAlpha();
Bitmap::ScopedReadAccess pSalBitmap(pInSalBitmap);
AlphaMask::ScopedReadAccess pSalAlpha(pInSalAlpha);
g_return_val_if_fail( pSalBitmap, NULL );
Size aSize( pSalBitmap->Width(), pSalBitmap->Height() );
if (pSalAlpha)
g_return_val_if_fail( Size( pSalAlpha->Width(), pSalAlpha->Height() ) == aSize, NULL );
int nX, nY;
guchar *pPixbufData = ( guchar * )g_malloc( 4 * aSize.Width() * aSize.Height() );
guchar *pDestData = pPixbufData;
for( nY = 0; nY < pSalBitmap->Height(); nY++ )
{
for( nX = 0; nX < pSalBitmap->Width(); nX++ )
{
BitmapColor aPix;
aPix = pSalBitmap->GetPixel( nY, nX );
pDestData[0] = aPix.GetRed();
pDestData[1] = aPix.GetGreen();
pDestData[2] = aPix.GetBlue();
if (pSalAlpha)
{
aPix = pSalAlpha->GetPixel( nY, nX );
pDestData[3] = 255 - aPix.GetIndex();
}
else
pDestData[3] = 255;
pDestData += 4;
}
}
return gdk_pixbuf_new_from_data( pPixbufData,
GDK_COLORSPACE_RGB, sal_True, 8,
aSize.Width(), aSize.Height(),
aSize.Width() * 4,
(GdkPixbufDestroyNotify) g_free,
NULL );
}
extern "C" {
static void oustring_delete (gpointer data,
GClosure * /* closure */)
{
OUString *pURL = (OUString *) data;
delete pURL;
}
}
static void add_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
OUString *pOverrideLabel,
sal_uInt16 nResId, GCallback pFnCallback )
{
OUString *pURL = new OUString (OStringToOUString( pAsciiURL,
RTL_TEXTENCODING_UTF8 ));
OString aLabel;
if (pOverrideLabel)
aLabel = OUStringToOString (*pOverrideLabel, RTL_TEXTENCODING_UTF8);
else
{
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
aLabel = OUStringToOString (pShutdownIcon->GetUrlDescription( *pURL ),
RTL_TEXTENCODING_UTF8);
}
GdkPixbuf *pPixbuf= ResIdToPixbuf( nResId );
GtkWidget *pImage = gtk_image_new_from_pixbuf( pPixbuf );
g_object_unref( G_OBJECT( pPixbuf ) );
GtkWidget *pMenuItem = gtk_image_menu_item_new_with_label( aLabel );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );
g_signal_connect_data( pMenuItem, "activate", pFnCallback, pURL,
oustring_delete, GConnectFlags(0));
gtk_menu_shell_append( pMenuShell, pMenuItem );
}
// Unbelievably nasty
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
static void add_ugly_db_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
sal_uInt16 nResId, GCallback pFnCallback )
{
SvtDynamicMenuOptions aOpt;
Sequence < Sequence < PropertyValue > > aMenu = aOpt.GetMenu( E_NEWMENU );
for ( sal_Int32 n=0; n<aMenu.getLength(); n++ )
{
::rtl::OUString aURL;
::rtl::OUString aDescription;
Sequence < PropertyValue >& aEntry = aMenu[n];
for ( sal_Int32 m=0; m<aEntry.getLength(); m++ )
{
if ( aEntry[m].Name.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("URL")) )
aEntry[m].Value >>= aURL;
if ( aEntry[m].Name.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Title")) )
aEntry[m].Value >>= aDescription;
}
if ( aURL.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(BASE_URL)) && aDescription.getLength() )
{
add_item (pMenuShell, pAsciiURL, &aDescription, nResId, pFnCallback);
break;
}
}
}
static GtkWidget *
add_image_menu_item( GtkMenuShell *pMenuShell,
const gchar *stock_id,
rtl::OUString aLabel,
GCallback activate_cb )
{
OString aUtfLabel = rtl::OUStringToOString (aLabel, RTL_TEXTENCODING_UTF8 );
GtkWidget *pImage;
pImage = gtk_image_new_from_stock( stock_id, GTK_ICON_SIZE_MENU );
GtkWidget *pMenuItem;
pMenuItem = gtk_image_menu_item_new_with_label( aUtfLabel );
gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );
gtk_menu_shell_append( pMenuShell, pMenuItem );
g_signal_connect( pMenuItem, "activate", activate_cb, NULL);
return pMenuItem;
}
static void populate_menu( GtkWidget *pMenu )
{
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
GtkMenuShell *pMenuShell = GTK_MENU_SHELL( pMenu );
SvtModuleOptions aModuleOptions;
if ( aModuleOptions.IsWriter() )
add_item (pMenuShell, WRITER_URL, NULL,
SV_ICON_ID_TEXT, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsCalc() )
add_item (pMenuShell, CALC_URL, NULL,
SV_ICON_ID_SPREADSHEET, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsImpress() )
add_item (pMenuShell, IMPRESS_URL, NULL,
SV_ICON_ID_PRESENTATION, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsDraw() )
add_item (pMenuShell, DRAW_URL, NULL,
SV_ICON_ID_DRAWING, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsDataBase() )
add_ugly_db_item (pMenuShell, BASE_URL,
SV_ICON_ID_DATABASE, G_CALLBACK( open_url_cb ));
if ( aModuleOptions.IsMath() )
add_item (pMenuShell, MATH_URL, NULL,
SV_ICON_ID_FORMULA, G_CALLBACK( open_url_cb ));
OUString aULabel = pShutdownIcon->GetResString( STR_QUICKSTART_FROMTEMPLATE );
add_item (pMenuShell, "dummy", &aULabel,
SV_ICON_ID_TEMPLATE, G_CALLBACK( open_template_cb ));
OString aLabel;
GtkWidget *pMenuItem;
pMenuItem = gtk_separator_menu_item_new();
gtk_menu_shell_append( pMenuShell, pMenuItem );
pOpenMenuItem = add_image_menu_item
(pMenuShell, GTK_STOCK_OPEN,
pShutdownIcon->GetResString( STR_QUICKSTART_FILEOPEN ),
G_CALLBACK( open_file_cb ));
pMenuItem = gtk_separator_menu_item_new();
gtk_menu_shell_append( pMenuShell, pMenuItem );
pDisableMenuItem = add_image_menu_item
( pMenuShell, GTK_STOCK_CLOSE,
pShutdownIcon->GetResString( STR_QUICKSTART_PRELAUNCH_UNX ),
G_CALLBACK( systray_disable_cb ) );
pMenuItem = gtk_separator_menu_item_new();
gtk_menu_shell_append( pMenuShell, pMenuItem );
pExitMenuItem = add_image_menu_item
( pMenuShell, GTK_STOCK_QUIT,
pShutdownIcon->GetResString( STR_QUICKSTART_EXIT ),
G_CALLBACK( exit_quickstarter_cb ) );
gtk_widget_show_all( pMenu );
}
static void refresh_menu( GtkWidget *pMenu )
{
if (!pExitMenuItem)
populate_menu( pMenu );
bool bModal = ShutdownIcon::bModalMode;
gtk_widget_set_sensitive( pExitMenuItem, !bModal);
gtk_widget_set_sensitive( pOpenMenuItem, !bModal);
gtk_widget_set_sensitive( pDisableMenuItem, !bModal);
}
static gboolean display_menu_cb( GtkWidget *,
GdkEventButton *event, GtkWidget *pMenu )
{
if (event->button == 2)
return sal_False;
refresh_menu( pMenu );
gtk_menu_popup( GTK_MENU( pMenu ), NULL, NULL,
gtk_status_icon_position_menu, pTrayIcon,
0, event->time );
return sal_True;
}
#ifdef ENABLE_GIO
/*
* If the quickstarter is running, then LibreOffice is
* upgraded, then the old quickstarter is still running, but is now unreliable
* as the old install has been deleted. A fairly intractable problem but we
* can avoid much of the pain if we turn off the quickstarter if we detect
* that it has been physically deleted or overwritten
*/
static void notify_file_changed(GFileMonitor * /*gfilemonitor*/, GFile * /*arg1*/,
GFile * /*arg2*/, GFileMonitorEvent event_type, gpointer /*user_data*/)
{
//Shutdown the quick starter if anything has happened to make it unsafe
//to remain running, e.g. rpm --erased and all libs deleted, or
//rpm --upgrade and libs being overwritten
switch (event_type)
{
case G_FILE_MONITOR_EVENT_DELETED:
case G_FILE_MONITOR_EVENT_CREATED:
case G_FILE_MONITOR_EVENT_PRE_UNMOUNT:
case G_FILE_MONITOR_EVENT_UNMOUNTED:
exit_quickstarter_cb(GTK_WIDGET(pTrayIcon));
break;
default:
break;
}
}
#endif
void SAL_DLLPUBLIC_EXPORT plugin_init_sys_tray()
{
::SolarMutexGuard aGuard;
if( /* need gtk_status to resolve */
(gtk_check_version( 2, 10, 0 ) != NULL) ||
/* we need the vcl plugin and mainloop initialized */
!g_type_from_name( "GdkDisplay" ) )
return;
OString aLabel;
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
aLabel = rtl::OUStringToOString (
pShutdownIcon->GetResString( STR_QUICKSTART_TIP ),
RTL_TEXTENCODING_UTF8 );
pVCLResMgr = CREATEVERSIONRESMGR( vcl );
GdkPixbuf *pPixbuf = ResIdToPixbuf( SV_ICON_ID_OFFICE );
pTrayIcon = gtk_status_icon_new_from_pixbuf(pPixbuf);
g_object_unref( pPixbuf );
g_object_set (pTrayIcon, "title", aLabel.getStr(),
"tooltip_text", aLabel.getStr(), NULL);
GtkWidget *pMenu = gtk_menu_new();
g_signal_connect (pMenu, "deactivate",
G_CALLBACK (menu_deactivate_cb), NULL);
g_signal_connect(pTrayIcon, "button_press_event",
G_CALLBACK(display_menu_cb), pMenu);
// disable shutdown
pShutdownIcon->SetVeto( true );
pShutdownIcon->addTerminateListener();
#ifdef ENABLE_GIO
GFile* pFile = NULL;
rtl::OUString sLibraryFileUrl;
if (osl::Module::getUrlFromAddress(plugin_init_sys_tray, sLibraryFileUrl))
pFile = g_file_new_for_uri(rtl::OUStringToOString(sLibraryFileUrl, RTL_TEXTENCODING_UTF8).getStr());
if (pFile)
{
if ((pMonitor = g_file_monitor_file(pFile, G_FILE_MONITOR_NONE, NULL, NULL)))
g_signal_connect(pMonitor, "changed", (GCallback)notify_file_changed, NULL);
g_object_unref(pFile);
}
#endif
}
void SAL_DLLPUBLIC_EXPORT plugin_shutdown_sys_tray()
{
::SolarMutexGuard aGuard;
if( !pTrayIcon )
return;
#ifdef ENABLE_GIO
if (pMonitor)
{
g_signal_handlers_disconnect_by_func(pMonitor,
(void*)notify_file_changed, pMonitor);
g_file_monitor_cancel(pMonitor);
g_object_unref(pMonitor);
pMonitor = NULL;
}
#endif
g_object_unref(pTrayIcon);
pTrayIcon = NULL;
pExitMenuItem = NULL;
pOpenMenuItem = NULL;
pDisableMenuItem = NULL;
}
#endif // ENABLE_QUICKSTART_APPLET
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <Rcpp.h>
#include "XlsWorkBook.h"
#include "XlsWorkSheet.h"
#include <libxls/xls.h>
using namespace Rcpp;
// [[Rcpp::export]]
CharacterVector xls_col_types(std::string path, std::string na, int i = 0,
int nskip = 0, int n = 100) {
std::vector<CellType> types = XlsWorkBook(path).sheet(i).colTypes(na, nskip, n);
CharacterVector out(types.size());
for (size_t i = 0; i < types.size(); ++i) {
out[i] = cellTypeDesc(types[i]);
}
return out;
}
// [[Rcpp::export]]
CharacterVector xls_col_names(std::string path, int i = 0, int nskip = 0) {
return XlsWorkBook(path).sheet(i).colNames(nskip);
}
// [[Rcpp::export]]
List xls_cols(std::string path, int i, CharacterVector col_names,
CharacterVector col_types, std::string na, int nskip = 0) {
XlsWorkSheet sheet = XlsWorkBook(path).sheet(i);
if (col_names.size() != col_types.size())
stop("`col_names` and `col_types` must have the same length");
std::vector<CellType> types = cellTypes(col_types);
return sheet.readCols(col_names, types, na, nskip);
}
<commit_msg>Must keep workbook alive for scope of worksheet<commit_after>#include <Rcpp.h>
#include "XlsWorkBook.h"
#include "XlsWorkSheet.h"
#include <libxls/xls.h>
using namespace Rcpp;
// [[Rcpp::export]]
CharacterVector xls_col_types(std::string path, std::string na, int i = 0,
int nskip = 0, int n = 100) {
XlsWorkBook wb = XlsWorkBook(path);
std::vector<CellType> types = wb.sheet(i).colTypes(na, nskip, n);
CharacterVector out(types.size());
for (size_t i = 0; i < types.size(); ++i) {
out[i] = cellTypeDesc(types[i]);
}
return out;
}
// [[Rcpp::export]]
CharacterVector xls_col_names(std::string path, int i = 0, int nskip = 0) {
XlsWorkBook wb = XlsWorkBook(path);
return wb.sheet(i).colNames(nskip);
}
// [[Rcpp::export]]
List xls_cols(std::string path, int i, CharacterVector col_names,
CharacterVector col_types, std::string na, int nskip = 0) {
XlsWorkBook wb = XlsWorkBook(path);
XlsWorkSheet sheet = wb.sheet(i);
if (col_names.size() != col_types.size())
stop("`col_names` and `col_types` must have the same length");
std::vector<CellType> types = cellTypes(col_types);
return sheet.readCols(col_names, types, na, nskip);
}
<|endoftext|> |
<commit_before>//
// RowVectorBlock.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// 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/.
//
#ifndef EIGENJS_ROWVECTORBLOCK_HPP
#define EIGENJS_ROWVECTORBLOCK_HPP
#include <v8.h>
#include <node.h>
#include <nan.h>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>
#include "base.hpp"
#include "definition.hpp"
#include "Matrix.hpp"
#include "RowVector.hpp"
#include "RowVectorBlock_fwd.hpp"
#include "RowVectorBlock/definitions.hpp"
#include "throw_error.hpp"
namespace EigenJS {
template <
typename ScalarType
, typename ValueType
, const char* ClassName
>
class RowVectorBlock
: public base<RowVectorBlock, ScalarType, ValueType, ClassName> {
public:
typedef base<
::EigenJS::RowVectorBlock, ScalarType, ValueType, ClassName> base_type;
typedef ScalarType scalar_type;
typedef ValueType value_type;
typedef ::EigenJS::RowVector<scalar_type> RowVector;
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
NanAssignPersistent(base_type::function_template, tpl);
tpl->SetClassName(NanNew(ClassName));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
EIGENJS_OBJECT_INITIALIZE(Matrix, tpl)
EIGENJS_OBJECT_INITIALIZE(RowVector, tpl)
exports->Set(NanNew(ClassName), tpl->GetFunction());
NanAssignPersistent(base_type::constructor, tpl->GetFunction());
}
NAN_INLINE value_type& operator*() { return block_; }
NAN_INLINE const value_type& operator*() const { return block_; }
NAN_INLINE value_type* operator->() { return &block_; }
NAN_INLINE const value_type* operator->() const { return &block_; }
protected:
explicit RowVectorBlock(
const typename base_type::pointer_type& value_ptr
, const typename value_type::Index& startCol
, const typename value_type::Index& blockCols
) : base_type(value_ptr)
, block_(
base_type::value_ptr_->block(0, startCol, 1, blockCols)
) {}
~RowVectorBlock() {}
static NAN_METHOD(New) {
NanScope();
if (args.Length() != 3) {
NanThrowError(
"Tried creating a block without "
"RowVector, startCol and blockCols arguments");
NanReturnUndefined();
}
if (RowVector::is_rowvector(args[0]) &&
args[1]->IsNumber() &&
args[2]->IsNumber()
) {
const RowVector* const& rhs_obj =
node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());
const RowVector& rhs_RowVector = *rhs_obj;
const typename RowVector::value_type& rhs_rowvector = *rhs_RowVector;
const typename value_type::Index startRow = 0;
const typename value_type::Index startCol = args[1]->Int32Value();
const typename value_type::Index blockRows = 1;
const typename value_type::Index blockCols = args[2]->Int32Value();
const typename value_type::Index&& rows = startRow + blockRows - 1;
const typename value_type::Index&& cols = startCol + blockCols - 1;
if (RowVector::is_out_of_range(rhs_rowvector, rows, cols)) {
NanReturnUndefined();
}
if (startCol >= 0 && blockCols >= 0) {
if (args.IsConstructCall()) {
RowVectorBlock* obj =
new RowVectorBlock(rhs_RowVector, startCol, blockCols);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Value> argv[] = { args[0], args[1], args[2] };
NanReturnValue(
base_type::new_instance(
args
, sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
}
EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
NanReturnUndefined();
}
private:
value_type block_;
};
} // namespace EigenJS
#endif // EIGENJS_ROWVECTORBLOCK_HPP
<commit_msg>src: inherits from MatrixBlock<commit_after>//
// RowVectorBlock.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// 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/.
//
#ifndef EIGENJS_ROWVECTORBLOCK_HPP
#define EIGENJS_ROWVECTORBLOCK_HPP
#include <v8.h>
#include <node.h>
#include <nan.h>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>
#include "base.hpp"
#include "definition.hpp"
#include "Matrix.hpp"
#include "MatrixBlock.hpp"
#include "RowVector.hpp"
#include "RowVectorBlock_fwd.hpp"
#include "RowVectorBlock/definitions.hpp"
#include "throw_error.hpp"
namespace EigenJS {
template <
typename ScalarType
, typename ValueType
, const char* ClassName
>
class RowVectorBlock
: public base<RowVectorBlock, ScalarType, ValueType, ClassName> {
public:
typedef base<
::EigenJS::RowVectorBlock, ScalarType, ValueType, ClassName> base_type;
typedef ScalarType scalar_type;
typedef ValueType value_type;
typedef ::EigenJS::RowVector<scalar_type> RowVector;
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
NanAssignPersistent(base_type::function_template, tpl);
tpl->SetClassName(NanNew(ClassName));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
EIGENJS_OBJECT_INITIALIZE(Matrix, tpl)
EIGENJS_OBJECT_INITIALIZE(MatrixBlock, tpl)
EIGENJS_OBJECT_INITIALIZE(RowVector, tpl)
exports->Set(NanNew(ClassName), tpl->GetFunction());
NanAssignPersistent(base_type::constructor, tpl->GetFunction());
}
NAN_INLINE value_type& operator*() { return block_; }
NAN_INLINE const value_type& operator*() const { return block_; }
NAN_INLINE value_type* operator->() { return &block_; }
NAN_INLINE const value_type* operator->() const { return &block_; }
protected:
explicit RowVectorBlock(
const typename base_type::pointer_type& value_ptr
, const typename value_type::Index& startCol
, const typename value_type::Index& blockCols
) : base_type(value_ptr)
, block_(
base_type::value_ptr_->block(0, startCol, 1, blockCols)
) {}
~RowVectorBlock() {}
static NAN_METHOD(New) {
NanScope();
if (args.Length() != 3) {
NanThrowError(
"Tried creating a block without "
"RowVector, startCol and blockCols arguments");
NanReturnUndefined();
}
if (RowVector::is_rowvector(args[0]) &&
args[1]->IsNumber() &&
args[2]->IsNumber()
) {
const RowVector* const& rhs_obj =
node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());
const RowVector& rhs_RowVector = *rhs_obj;
const typename RowVector::value_type& rhs_rowvector = *rhs_RowVector;
const typename value_type::Index startRow = 0;
const typename value_type::Index startCol = args[1]->Int32Value();
const typename value_type::Index blockRows = 1;
const typename value_type::Index blockCols = args[2]->Int32Value();
const typename value_type::Index&& rows = startRow + blockRows - 1;
const typename value_type::Index&& cols = startCol + blockCols - 1;
if (RowVector::is_out_of_range(rhs_rowvector, rows, cols)) {
NanReturnUndefined();
}
if (startCol >= 0 && blockCols >= 0) {
if (args.IsConstructCall()) {
RowVectorBlock* obj =
new RowVectorBlock(rhs_RowVector, startCol, blockCols);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Value> argv[] = { args[0], args[1], args[2] };
NanReturnValue(
base_type::new_instance(
args
, sizeof(argv) / sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
}
EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
NanReturnUndefined();
}
private:
value_type block_;
};
} // namespace EigenJS
#endif // EIGENJS_ROWVECTORBLOCK_HPP
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2016 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <string>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/MulticastMatcher.h"
TEST(MulticastMatcherTest, checkSingleLevelWildcard)
{
std::string multicastId = "provider/broad/+";
joynr::MulticastMatcher m(multicastId);
EXPECT_TRUE(m.doesMatch("provider/broad/AnyPart"));
EXPECT_FALSE(m.doesMatch("provider/broad"));
EXPECT_FALSE(m.doesMatch("provider/broad/AnyPart/NoMatch"));
}
TEST(MulticastMatcherTest, checkMultipleSingleLevelWildcard)
{
std::string multicastId = "provider/broad/+/part1/+";
joynr::MulticastMatcher m(multicastId);
EXPECT_TRUE(m.doesMatch("provider/broad/AnyPart/part1/AnyPart"));
EXPECT_FALSE(m.doesMatch("provider/broad"));
EXPECT_FALSE(m.doesMatch("provider/broad/AnyPart"));
EXPECT_FALSE(m.doesMatch("provider/broad/AnyPart/part1"));
EXPECT_FALSE(m.doesMatch("provider/broad/AnyPart/NoMatch/AnyPart"));
EXPECT_FALSE(m.doesMatch("provider/broad/AnyPart/part1/AnyPart/NoMatch"));
}
TEST(MulticastMatcherTest, checkMultiLevelWildcard)
{
std::string multicastId = "provider/broad/*";
joynr::MulticastMatcher m(multicastId);
EXPECT_TRUE(m.doesMatch("provider/broad/AnyPart"));
EXPECT_TRUE(m.doesMatch("provider/broad"));
EXPECT_TRUE(m.doesMatch("provider/broad/AnyPart/AnyPart/AnyPart/AnyPart"));
EXPECT_FALSE(m.doesMatch("provider/NoMatch"));
}
<commit_msg>[C++] adapt MulticastMatcherTest to java tests<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2016 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <string>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/MulticastMatcher.h"
TEST(MulticastMatcherTest, replaceLeadingSingleLevelWildcard)
{
std::string multicastId = "+/one/two/three";
joynr::MulticastMatcher matcher(multicastId);
EXPECT_TRUE(matcher.doesMatch("anything/one/two/three"));
EXPECT_TRUE(matcher.doesMatch("1/one/two/three"));
EXPECT_TRUE(matcher.doesMatch("hello/one/two/three"));
EXPECT_FALSE(matcher.doesMatch("one/two/three"));
EXPECT_FALSE(matcher.doesMatch("one/any/two/three"));
EXPECT_FALSE(matcher.doesMatch("/one/two/three"));
EXPECT_FALSE(matcher.doesMatch("five/six/one/two/three"));
}
TEST(MulticastMatcherTest, singleLevelWildcardInMiddle)
{
std::string multicastId = "one/+/three";
joynr::MulticastMatcher matcher(multicastId);
EXPECT_TRUE(matcher.doesMatch("one/anything/three"));
EXPECT_TRUE(matcher.doesMatch("one/1/three"));
EXPECT_TRUE(matcher.doesMatch("one/here/three"));
EXPECT_FALSE(matcher.doesMatch("one/two/four/three"));
EXPECT_FALSE(matcher.doesMatch("one/three"));
}
TEST(MulticastMatcherTest, singleLevelWildcardAtEnd)
{
std::string multicastId = "one/two/+";
joynr::MulticastMatcher matcher(multicastId);
EXPECT_TRUE(matcher.doesMatch("one/two/anything"));
EXPECT_TRUE(matcher.doesMatch("one/two/3"));
EXPECT_TRUE(matcher.doesMatch("one/two/andAnotherPartition"));
EXPECT_FALSE(matcher.doesMatch("one/two/three/four"));
EXPECT_FALSE(matcher.doesMatch("one/two"));
}
TEST(MulticastMatcherTest, multiLevelWildcardAtEnd)
{
std::string multicastId = "one/two/*";
joynr::MulticastMatcher matcher(multicastId);
EXPECT_TRUE(matcher.doesMatch("one/two/anything"));
EXPECT_TRUE(matcher.doesMatch("one/two/3"));
EXPECT_TRUE(matcher.doesMatch("one/two/andAnotherPartition"));
EXPECT_TRUE(matcher.doesMatch("one/two/three/four"));
EXPECT_TRUE(matcher.doesMatch("one/two"));
EXPECT_FALSE(matcher.doesMatch("one/twothree"));
}
<|endoftext|> |
<commit_before>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/core/image/opencv_interop.hpp
*
* Copyright 2017 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef EOS_IMAGE_OPENCV_INTEROP_HPP_
#define EOS_IMAGE_OPENCV_INTEROP_HPP_
#include "eos/core/Image.hpp"
#include "opencv2/core/core.hpp"
#include <array>
#include <cstdint>
#include <stdexcept>
namespace eos {
namespace core {
// We can support different types by making this a template and constexpr if? :-)
inline cv::Mat to_mat(const Image4u& image)
{
cv::Mat opencv_matrix(static_cast<int>(image.height()), static_cast<int>(image.width()), CV_8UC4);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<cv::Vec4b>(r, c) =
cv::Vec4b(image(r, c)[0], image(r, c)[1], image(r, c)[2], image(r, c)[3]);
}
}
return opencv_matrix;
};
inline cv::Mat to_mat(const Image3u& image)
{
cv::Mat opencv_matrix(image.height(), image.width(), CV_8UC3);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<cv::Vec3b>(r, c) = cv::Vec3b(image(r, c)[0], image(r, c)[1], image(r, c)[2]);
}
}
return opencv_matrix;
};
inline cv::Mat to_mat(const Image1d& image)
{
cv::Mat opencv_matrix(static_cast<int>(image.height()), static_cast<int>(image.width()), CV_64FC1);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<double>(r, c) = image(r, c);
}
}
return opencv_matrix;
};
inline cv::Mat to_mat(const Image1u& image)
{
cv::Mat opencv_matrix(static_cast<int>(image.height()), static_cast<int>(image.width()), CV_8UC1);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<unsigned char>(r, c) = image(r, c);
}
}
return opencv_matrix;
};
inline Image3u from_mat(const cv::Mat& image)
{
if (image.type() != CV_8UC3)
{
throw std::runtime_error("Can only convert a CV_8UC3 cv::Mat to an eos::core::Image3u.");
}
Image3u converted(image.rows, image.cols);
for (int r = 0; r < image.rows; ++r)
{
for (int c = 0; c < image.cols; ++c)
{
converted(r, c) = {image.at<cv::Vec3b>(r, c)[0], image.at<cv::Vec3b>(r, c)[1],
image.at<cv::Vec3b>(r, c)[2]};
}
}
return converted;
};
} /* namespace core */
} /* namespace eos */
#endif /* EOS_IMAGE_OPENCV_INTEROP_HPP_ */
<commit_msg>Added function from_mat_with_alpha<commit_after>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/core/image/opencv_interop.hpp
*
* Copyright 2017 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef EOS_IMAGE_OPENCV_INTEROP_HPP_
#define EOS_IMAGE_OPENCV_INTEROP_HPP_
#include "eos/core/Image.hpp"
#include "opencv2/core/core.hpp"
#include <array>
#include <cstdint>
#include <stdexcept>
namespace eos {
namespace core {
// We can support different types by making this a template and constexpr if? :-)
inline cv::Mat to_mat(const Image4u& image)
{
cv::Mat opencv_matrix(static_cast<int>(image.height()), static_cast<int>(image.width()), CV_8UC4);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<cv::Vec4b>(r, c) =
cv::Vec4b(image(r, c)[0], image(r, c)[1], image(r, c)[2], image(r, c)[3]);
}
}
return opencv_matrix;
};
inline cv::Mat to_mat(const Image3u& image)
{
cv::Mat opencv_matrix(image.height(), image.width(), CV_8UC3);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<cv::Vec3b>(r, c) = cv::Vec3b(image(r, c)[0], image(r, c)[1], image(r, c)[2]);
}
}
return opencv_matrix;
};
inline cv::Mat to_mat(const Image1d& image)
{
cv::Mat opencv_matrix(static_cast<int>(image.height()), static_cast<int>(image.width()), CV_64FC1);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<double>(r, c) = image(r, c);
}
}
return opencv_matrix;
};
inline cv::Mat to_mat(const Image1u& image)
{
cv::Mat opencv_matrix(static_cast<int>(image.height()), static_cast<int>(image.width()), CV_8UC1);
for (int c = 0; c < image.width(); ++c)
{ // size_t
for (int r = 0; r < image.height(); ++r)
{
// auto vals = image(r, c);
opencv_matrix.at<unsigned char>(r, c) = image(r, c);
}
}
return opencv_matrix;
};
inline Image3u from_mat(const cv::Mat& image)
{
if (image.type() != CV_8UC3)
{
throw std::runtime_error("Can only convert a CV_8UC3 cv::Mat to an eos::core::Image3u.");
}
Image3u converted(image.rows, image.cols);
for (int r = 0; r < image.rows; ++r)
{
for (int c = 0; c < image.cols; ++c)
{
converted(r, c) = {image.at<cv::Vec3b>(r, c)[0], image.at<cv::Vec3b>(r, c)[1],
image.at<cv::Vec3b>(r, c)[2]};
}
}
return converted;
};
inline Image4u from_mat_with_alpha(const cv::Mat& image)
{
if (image.type() != CV_8UC4)
{
throw std::runtime_error("Can only convert a CV_8UC4 cv::Mat to an eos::core::Image4u.");
}
Image4u converted(image.rows, image.cols);
for (int r = 0; r < image.rows; ++r)
{
for (int c = 0; c < image.cols; ++c)
{
converted(r, c) = {image.at<cv::Vec4b>(r, c)[0], image.at<cv::Vec4b>(r, c)[1],
image.at<cv::Vec4b>(r, c)[2], image.at<cv::Vec4b>(r, c)[3]};
}
}
return converted;
};
} /* namespace core */
} /* namespace eos */
#endif /* EOS_IMAGE_OPENCV_INTEROP_HPP_ */
<|endoftext|> |
<commit_before>#pragma once
#include <cstddef>
#include <cstdint>
#include <array>
#include <atomic>
#include <limits>
#include <utility>
#include <vector>
#include <insertionfinder/algorithm.hpp>
#include <insertionfinder/case.hpp>
#include <insertionfinder/cube.hpp>
#include <insertionfinder/twist.hpp>
#include <insertionfinder/utils.hpp>
namespace InsertionFinder {
namespace FinderStatus {
constexpr std::byte success {0};
constexpr std::byte parity_algorithms_needed {1};
constexpr std::byte corner_cycle_algorithms_needed {2};
constexpr std::byte edge_cycle_algorithms_needed {4};
constexpr std::byte center_algorithms_needed {8};
constexpr std::byte full = parity_algorithms_needed
| corner_cycle_algorithms_needed | edge_cycle_algorithms_needed
| center_algorithms_needed;
};
class Finder {
protected:
struct CycleStatus {
bool parity;
std::int8_t corner_cycles;
std::int8_t edge_cycles;
std::int8_t placement;
CycleStatus() = default;
CycleStatus(bool parity, int corner_cycles, int edge_cycles, Rotation placement):
parity(parity), corner_cycles(corner_cycles), edge_cycles(edge_cycles), placement(placement) {}
};
public:
struct Insertion {
Algorithm skeleton;
std::size_t insert_place;
const Algorithm* insertion;
explicit Insertion(
const Algorithm& skeleton,
std::size_t insert_place = 0,
const Algorithm* insertion = nullptr
): skeleton(skeleton), insert_place(insert_place), insertion(insertion) {}
explicit Insertion(
Algorithm&& skeleton,
std::size_t insert_place = 0,
const Algorithm* insertion = nullptr
): skeleton(std::move(skeleton)), insert_place(insert_place), insertion(insertion) {}
};
struct Solution {
std::vector<Insertion> insertions;
std::size_t cancellation = 0;
Solution(const std::vector<Insertion>& insertions): insertions(insertions) {}
Solution(std::vector<Insertion>&& insertions): insertions(std::move(insertions)) {}
};
struct Result {
std::byte status = FinderStatus::full;
std::int64_t duration;
};
struct SearchParams {
std::size_t search_target;
double parity_multiplier;
std::size_t max_threads;
};
protected:
const Algorithm scramble;
const std::vector<Algorithm> skeletons;
const std::vector<Case>& cases;
std::atomic<std::size_t> fewest_moves = std::numeric_limits<std::size_t>::max();
std::vector<Solution> solutions;
Result result;
int parity_multiplier = 3;
bool verbose = false;
protected:
int corner_cycle_index[6 * 24 * 24];
int edge_cycle_index[10 * 24 * 24];
int center_index[24];
bool change_parity = false;
bool change_corner = false;
bool change_edge = false;
bool change_center = false;
Cube scramble_cube;
Cube inverse_scramble_cube;
public:
Finder(const Algorithm& scramble, const std::vector<Algorithm>& skeletons, const std::vector<Case>& cases):
scramble(scramble), skeletons(skeletons), cases(cases),
scramble_cube(Cube() * scramble), inverse_scramble_cube(Cube::inverse(this->scramble_cube)) {
this->init();
}
Finder(const Algorithm& scramble, std::vector<Algorithm>&& skeletons, const std::vector<Case>& cases):
scramble(scramble), skeletons(std::move(skeletons)), cases(cases),
scramble_cube(Cube() * scramble), inverse_scramble_cube(Cube::inverse(this->scramble_cube)) {
this->init();
}
Finder(const Algorithm& scramble, const Algorithm& skeleton, const std::vector<Case>& cases):
scramble(scramble), skeletons({skeleton}), cases(cases),
scramble_cube(Cube() * scramble), inverse_scramble_cube(Cube::inverse(this->scramble_cube)) {
this->init();
}
virtual ~Finder() = default;
public:
void search(const SearchParams& params);
protected:
void init();
virtual void search_core(const SearchParams& params) = 0;
public:
std::size_t get_fewest_moves() const noexcept {
return this->fewest_moves;
}
const std::vector<Solution>& get_solutions() const noexcept {
return this->solutions;
}
Result get_result() const noexcept {
return this->result;
}
public:
void set_verbose(bool verbose = true) noexcept {
this->verbose = verbose;
}
public:
int get_total_cycles(bool parity, int corner_cycles, int edge_cycles, Rotation placement) {
int center_cycles = Cube::center_cycles[placement];
return (center_cycles > 1 ? 0 : parity * this->parity_multiplier)
+ (corner_cycles + edge_cycles + center_cycles) * 2;
}
};
};
<commit_msg>add const<commit_after>#pragma once
#include <cstddef>
#include <cstdint>
#include <array>
#include <atomic>
#include <limits>
#include <utility>
#include <vector>
#include <insertionfinder/algorithm.hpp>
#include <insertionfinder/case.hpp>
#include <insertionfinder/cube.hpp>
#include <insertionfinder/twist.hpp>
#include <insertionfinder/utils.hpp>
namespace InsertionFinder {
namespace FinderStatus {
constexpr std::byte success {0};
constexpr std::byte parity_algorithms_needed {1};
constexpr std::byte corner_cycle_algorithms_needed {2};
constexpr std::byte edge_cycle_algorithms_needed {4};
constexpr std::byte center_algorithms_needed {8};
constexpr std::byte full = parity_algorithms_needed
| corner_cycle_algorithms_needed | edge_cycle_algorithms_needed
| center_algorithms_needed;
};
class Finder {
protected:
struct CycleStatus {
bool parity;
std::int8_t corner_cycles;
std::int8_t edge_cycles;
std::int8_t placement;
CycleStatus() = default;
CycleStatus(bool parity, int corner_cycles, int edge_cycles, Rotation placement):
parity(parity), corner_cycles(corner_cycles), edge_cycles(edge_cycles), placement(placement) {}
};
public:
struct Insertion {
Algorithm skeleton;
std::size_t insert_place;
const Algorithm* insertion;
explicit Insertion(
const Algorithm& skeleton,
std::size_t insert_place = 0,
const Algorithm* insertion = nullptr
): skeleton(skeleton), insert_place(insert_place), insertion(insertion) {}
explicit Insertion(
Algorithm&& skeleton,
std::size_t insert_place = 0,
const Algorithm* insertion = nullptr
): skeleton(std::move(skeleton)), insert_place(insert_place), insertion(insertion) {}
};
struct Solution {
std::vector<Insertion> insertions;
std::size_t cancellation = 0;
Solution(const std::vector<Insertion>& insertions): insertions(insertions) {}
Solution(std::vector<Insertion>&& insertions): insertions(std::move(insertions)) {}
};
struct Result {
std::byte status = FinderStatus::full;
std::int64_t duration;
};
struct SearchParams {
std::size_t search_target;
double parity_multiplier;
std::size_t max_threads;
};
protected:
const Algorithm scramble;
const std::vector<Algorithm> skeletons;
const std::vector<Case>& cases;
std::atomic<std::size_t> fewest_moves = std::numeric_limits<std::size_t>::max();
std::vector<Solution> solutions;
Result result;
int parity_multiplier = 3;
bool verbose = false;
protected:
int corner_cycle_index[6 * 24 * 24];
int edge_cycle_index[10 * 24 * 24];
int center_index[24];
bool change_parity = false;
bool change_corner = false;
bool change_edge = false;
bool change_center = false;
const Cube scramble_cube;
const Cube inverse_scramble_cube;
public:
Finder(const Algorithm& scramble, const std::vector<Algorithm>& skeletons, const std::vector<Case>& cases):
scramble(scramble), skeletons(skeletons), cases(cases),
scramble_cube(Cube() * scramble), inverse_scramble_cube(Cube::inverse(this->scramble_cube)) {
this->init();
}
Finder(const Algorithm& scramble, std::vector<Algorithm>&& skeletons, const std::vector<Case>& cases):
scramble(scramble), skeletons(std::move(skeletons)), cases(cases),
scramble_cube(Cube() * scramble), inverse_scramble_cube(Cube::inverse(this->scramble_cube)) {
this->init();
}
Finder(const Algorithm& scramble, const Algorithm& skeleton, const std::vector<Case>& cases):
scramble(scramble), skeletons({skeleton}), cases(cases),
scramble_cube(Cube() * scramble), inverse_scramble_cube(Cube::inverse(this->scramble_cube)) {
this->init();
}
virtual ~Finder() = default;
public:
void search(const SearchParams& params);
protected:
void init();
virtual void search_core(const SearchParams& params) = 0;
public:
std::size_t get_fewest_moves() const noexcept {
return this->fewest_moves;
}
const std::vector<Solution>& get_solutions() const noexcept {
return this->solutions;
}
Result get_result() const noexcept {
return this->result;
}
public:
void set_verbose(bool verbose = true) noexcept {
this->verbose = verbose;
}
public:
int get_total_cycles(bool parity, int corner_cycles, int edge_cycles, Rotation placement) {
int center_cycles = Cube::center_cycles[placement];
return (center_cycles > 1 ? 0 : parity * this->parity_multiplier)
+ (corner_cycles + edge_cycles + center_cycles) * 2;
}
};
};
<|endoftext|> |
<commit_before>
#include <iostream>
//GlEW, before GLFW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// Should make it cross platform
// glm
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// SOIL
#include <soil/SOIL.h>
#include "Shader.h"
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
int textureWidth, textureHeight;
void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
void DrawPolygon(std::string type, Shader shader,
const GLuint &VAO, const bool &wireFramed,
bool drawWithTexture, GLuint &texture1, GLuint &texture2)
{
shader.Use();
if (drawWithTexture)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glUniform1i(glGetUniformLocation(shader.Program, "ourTexture1"), 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
glUniform1i(glGetUniformLocation(shader.Program, "ourTexture2"), 1);
}
glBindVertexArray(VAO);
if (wireFramed)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if (type == "triangle")
{
glDrawArrays(GL_TRIANGLES, 0, 3); // Arg1 0 start index of vertex array
// Arg2 3 vertices are to be drawn
}
else if (type == "rectangle")
{
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // Arg2 6 indices
// Arg4 0 offset in EBO
}
else
{
std::cout << "Wrong type of polygon in call to DrawPolygon(). " << std::endl;
}
glBindVertexArray(0);
}
bool InitGlfwAndGlew(GLFWwindow* &window)
{
std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
// Init GLFW and set all its required options
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Use OpenGl 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Don't use old functionality
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Necessary for Mac OSX
// Init GLFWwindow object
window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return false;
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, KeyCallback);
// Init GLEW to setup function pointers for OpenGl
glewExperimental = GL_TRUE; // Use core profile modern OpenGL techniques
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to init GLEW" << std::endl;
return false;
}
// Define width and height for OpenGL (viewport dimensions)
// OpenGL uses this data to map from processed coordinates in range (-1,1) to (0,800) and (0,600)
int width, height;
glfwGetFramebufferSize(window, &width, &height); // Framebuffer size in pixels instead of screen coordinates
glViewport(0, 0, width, height); // (0, 0) = Southwest corner of window
return true;
}
void GlmPlay()
{
glm::vec4 vec(1.0f, 0.0f, 0.0f, 0.0f);
std::cout << vec.x << vec.y << vec.z << std::endl;
glm::mat4 trans;
trans = glm::translate(trans, glm::vec3(1.0f, 1.0f, 0.0f));
vec = trans * vec;
std::cout << vec.x << vec.y << vec.z << std::endl;
}
void InitTexture(const char* path, GLuint &texture)
{
unsigned char* image;
// Load image from file
image = SOIL_load_image(path, &textureWidth, &textureHeight, 0, SOIL_LOAD_RGB);
if (image == NULL)
{
std::cout << "Error: Failed to load image: " << path << std::endl;
}
// Generate texture
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
// Set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT (usually basic wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 0,
GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D, 0); // Unbind
}
int main()
{
GlmPlay();
GLFWwindow* window;
bool initGlfwGlewSuccess;
initGlfwGlewSuccess = InitGlfwAndGlew(window);
if (!initGlfwGlewSuccess) { return -1; }
// Triangle vertices as normalized device coordinates
GLfloat vertices[] = {
// Positions // Colors // Texture Coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left
};
GLuint indices[6] =
{
0, 1, 3, // First triangle
1, 2, 3 // Second triangle
};
GLuint texture1;
InitTexture("Images/stone.jpg", texture1);
GLuint texture2;
InitTexture("Images/medallion.jpg", texture2);
// Init triangle VBO to store vertices in GPU memory, rectangle EBO to index vertices
// and VAO to collect all states
GLuint VBO, VAO, EBO;
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Copies vertex data to GPU
// GL_STATIC_DRAW since the data most likely
// will not change
// The VBO is stored in VAO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // Stored in VAO
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// Specify how vertex data is to be interpreted...........................................
// Position attributes
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); // Arg1 0 since position is layout 0
// Arg2 3 since position data vec3
// Arg4 false since already normalized values
// Arg5 Space between attribute sets
// Arg6 No data offset in buffer
glEnableVertexAttribArray(0); // Vertex attribute location is 0 for position
// Color attributes
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1); // Vertex attribute location is 1 for color
// Texture attributes
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
glBindVertexArray(0); // Unbind vertex array to not risk misconfiguring later on
Shader simpleShader("./shader.vert", "./shader.frag");
// Game loop
while (!glfwWindowShouldClose(window))
{
glfwPollEvents(); // Check if events have been activated
// Rendering commands
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
bool wireFramed = false;
bool drawWithTexture = true;
DrawPolygon("rectangle", simpleShader, VAO, wireFramed, drawWithTexture, texture1, texture2);
glfwSwapBuffers(window);
}
// Deallocate resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
glfwTerminate(); // Clear allocated resources
return 0;
}<commit_msg>Textures done.<commit_after>
#include <iostream>
//GlEW, before GLFW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// Should make it cross platform
// glm
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// SOIL
#include <soil/SOIL.h>
#include "Shader.h"
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
int textureWidth, textureHeight;
void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
void DrawPolygon(std::string type, Shader shader,
const GLuint &VAO, const bool &wireFramed,
bool drawWithTexture, GLuint &texture1, GLuint &texture2)
{
shader.Use();
if (drawWithTexture)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glUniform1i(glGetUniformLocation(shader.Program, "ourTexture1"), 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
glUniform1i(glGetUniformLocation(shader.Program, "ourTexture2"), 1);
}
glBindVertexArray(VAO);
if (wireFramed)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if (type == "triangle")
{
glDrawArrays(GL_TRIANGLES, 0, 3); // Arg1 0 start index of vertex array
// Arg2 3 vertices are to be drawn
}
else if (type == "rectangle")
{
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // Arg2 6 indices
// Arg4 0 offset in EBO
}
else
{
std::cout << "Wrong type of polygon in call to DrawPolygon(). " << std::endl;
}
glBindVertexArray(0);
}
bool InitGlfwAndGlew(GLFWwindow* &window)
{
std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
// Init GLFW and set all its required options
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Use OpenGl 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Don't use old functionality
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Necessary for Mac OSX
// Init GLFWwindow object
window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return false;
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, KeyCallback);
// Init GLEW to setup function pointers for OpenGl
glewExperimental = GL_TRUE; // Use core profile modern OpenGL techniques
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to init GLEW" << std::endl;
return false;
}
// Define width and height for OpenGL (viewport dimensions)
// OpenGL uses this data to map from processed coordinates in range (-1,1) to (0,800) and (0,600)
int width, height;
glfwGetFramebufferSize(window, &width, &height); // Framebuffer size in pixels instead of screen coordinates
glViewport(0, 0, width, height); // (0, 0) = Southwest corner of window
return true;
}
void GlmPlay()
{
glm::vec4 vec(1.0f, 0.0f, 0.0f, 0.0f);
std::cout << vec.x << vec.y << vec.z << std::endl;
glm::mat4 trans;
trans = glm::translate(trans, glm::vec3(1.0f, 1.0f, 0.0f));
vec = trans * vec;
std::cout << vec.x << vec.y << vec.z << std::endl;
}
void InitTexture(const char* path, GLuint &texture)
{
unsigned char* image;
// Load image from file
image = SOIL_load_image(path, &textureWidth, &textureHeight, 0, SOIL_LOAD_RGB);
if (image == NULL)
{
std::cout << "Error: Failed to load image: " << path << std::endl;
}
// Generate texture
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
// Set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT (usually basic wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 0,
GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D, 0); // Unbind
}
int main()
{
GlmPlay();
GLFWwindow* window;
bool initGlfwGlewSuccess;
initGlfwGlewSuccess = InitGlfwAndGlew(window);
if (!initGlfwGlewSuccess) { return -1; }
// Triangle vertices as normalized device coordinates
GLfloat vertices[] = {
// Positions // Colors // Texture Coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left
};
GLuint indices[6] =
{
0, 1, 3, // First triangle
1, 2, 3 // Second triangle
};
// Init textures
GLuint texture1;
InitTexture("Images/stone.jpg", texture1);
GLuint texture2;
InitTexture("Images/medallion.jpg", texture2);
// Init triangle VBO to store vertices in GPU memory, rectangle EBO to index vertices
// and VAO to collect all states
GLuint VBO, VAO, EBO;
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Copies vertex data to GPU
// GL_STATIC_DRAW since the data most likely
// will not change
// The VBO is stored in VAO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // Stored in VAO
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// Specify how vertex data is to be interpreted...........................................
// Position attributes
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); // Arg1 0 since position is layout 0
// Arg2 3 since position data vec3
// Arg4 false since already normalized values
// Arg5 Space between attribute sets
// Arg6 No data offset in buffer
glEnableVertexAttribArray(0); // Vertex attribute location is 0 for position
// Color attributes
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1); // Vertex attribute location is 1 for color
// Texture attributes
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
glBindVertexArray(0); // Unbind vertex array to not risk misconfiguring later on
Shader simpleShader("./shader.vert", "./shader.frag");
// Game loop
while (!glfwWindowShouldClose(window))
{
glfwPollEvents(); // Check if events have been activated
// Rendering commands
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
bool wireFramed = false;
bool drawWithTexture = true;
DrawPolygon("rectangle", simpleShader, VAO, wireFramed, drawWithTexture, texture1, texture2);
glfwSwapBuffers(window);
}
// Deallocate resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
glfwTerminate(); // Clear allocated resources
return 0;
}<|endoftext|> |
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "MemoryStream.h"
#include <algorithm>
using namespace leap;
MemoryStream::MemoryStream(void) {}
bool MemoryStream::Write(const void* pBuf, std::streamsize ncb) {
if (buffer.size() - m_writeOffset < ncb)
// Exponential growth on the buffer:
buffer.resize(
std::max(
buffer.size() * 2,
m_writeOffset + static_cast<size_t>(ncb)
)
);
memcpy(
buffer.data() + m_writeOffset,
pBuf,
static_cast<size_t>(ncb)
);
m_writeOffset += static_cast<size_t>(ncb);
return true;
}
bool MemoryStream::IsEof(void) const {
return m_readOffset >= buffer.size();
}
std::streamsize MemoryStream::Read(void* pBuf, std::streamsize ncb) {
const void* pSrcData = buffer.data() + m_readOffset;
ncb = Skip(ncb);
memcpy(pBuf, pSrcData, static_cast<size_t>(ncb));
return ncb;
}
std::streamsize MemoryStream::Skip(std::streamsize ncb) {
ncb = std::min(
ncb,
static_cast<std::streamsize>(buffer.size() - m_readOffset)
);
m_readOffset += static_cast<size_t>(ncb);
if (m_readOffset == buffer.size()) {
// Reset criteria, no data left in the buffer
m_readOffset = 0;
m_writeOffset = 0;
}
return ncb;
}
std::streamsize MemoryStream::Length(void) {
return static_cast<std::streamsize>(m_writeOffset - m_readOffset);
}
<commit_msg>Add missing include<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "MemoryStream.h"
#include <algorithm>
#include <memory.h>
using namespace leap;
MemoryStream::MemoryStream(void) {}
bool MemoryStream::Write(const void* pBuf, std::streamsize ncb) {
if (buffer.size() - m_writeOffset < ncb)
// Exponential growth on the buffer:
buffer.resize(
std::max(
buffer.size() * 2,
m_writeOffset + static_cast<size_t>(ncb)
)
);
memcpy(
buffer.data() + m_writeOffset,
pBuf,
static_cast<size_t>(ncb)
);
m_writeOffset += static_cast<size_t>(ncb);
return true;
}
bool MemoryStream::IsEof(void) const {
return m_readOffset >= buffer.size();
}
std::streamsize MemoryStream::Read(void* pBuf, std::streamsize ncb) {
const void* pSrcData = buffer.data() + m_readOffset;
ncb = Skip(ncb);
memcpy(pBuf, pSrcData, static_cast<size_t>(ncb));
return ncb;
}
std::streamsize MemoryStream::Skip(std::streamsize ncb) {
ncb = std::min(
ncb,
static_cast<std::streamsize>(buffer.size() - m_readOffset)
);
m_readOffset += static_cast<size_t>(ncb);
if (m_readOffset == buffer.size()) {
// Reset criteria, no data left in the buffer
m_readOffset = 0;
m_writeOffset = 0;
}
return ncb;
}
std::streamsize MemoryStream::Length(void) {
return static_cast<std::streamsize>(m_writeOffset - m_readOffset);
}
<|endoftext|> |
<commit_before>#ifndef OPENGM_LEARNING_WEIGHTS
#define OPENGM_LEARNING_WEIGHTS
namespace opengm{
namespace learning{
template<class T>
class Weights{
public:
typedef T ValueType;
Weights(const size_t numberOfParameters=0)
: weights_(numberOfParameters){
}
ValueType getWeight(const size_t pi)const{
OPENGM_ASSERT_OP(pi,<,weights_.size());
return weights_[pi];
}
void setWeight(const size_t pi,const ValueType value){
OPENGM_ASSERT_OP(pi,<,weights_.size());
weights_[pi]=value;
}
const ValueType& operator[](const size_t pi)const{
return weights_[pi];
}
ValueType& operator[](const size_t pi) {
return weights_[pi];
}
size_t numberOfWeights()const{
return weights_.size();
}
private:
std::vector<ValueType> weights_;
};
} // namespace learning
} // namespace opengm
#endif /* OPENGM_LEARNING_WEIGHTS */
<commit_msg>rename argument, add missing include<commit_after>#ifndef OPENGM_LEARNING_WEIGHTS
#define OPENGM_LEARNING_WEIGHTS
#include <opengm/opengm.hxx>
namespace opengm{
namespace learning{
template<class T>
class Weights{
public:
typedef T ValueType;
Weights(const size_t numberOfWeights=0)
: weights_(numberOfWeights){
}
ValueType getWeight(const size_t pi)const{
OPENGM_ASSERT_OP(pi,<,weights_.size());
return weights_[pi];
}
void setWeight(const size_t pi,const ValueType value){
OPENGM_ASSERT_OP(pi,<,weights_.size());
weights_[pi]=value;
}
const ValueType& operator[](const size_t pi)const{
return weights_[pi];
}
ValueType& operator[](const size_t pi) {
return weights_[pi];
}
size_t numberOfWeights()const{
return weights_.size();
}
private:
std::vector<ValueType> weights_;
};
} // namespace learning
} // namespace opengm
#endif /* OPENGM_LEARNING_WEIGHTS */
<|endoftext|> |
<commit_before>/**
* @file streamingaudio_fmodex.cpp
* @brief LLStreamingAudio_FMODEX implementation
*
* $LicenseInfo:firstyear=2002&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llmath.h"
#include "fmod.hpp"
#include "fmod_errors.h"
#include "llstreamingaudio_fmodex.h"
class LLAudioStreamManagerFMODEX
{
public:
LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url);
FMOD::Channel* startStream();
bool stopStream(); // Returns true if the stream was successfully stopped.
bool ready();
// <FS:Ansariel> Streamtitle display
bool hasNewMetadata();
std::string getCurrentArtist();
std::string getCurrentTitle();
// </FS:Ansariel>
const std::string& getURL() { return mInternetStreamURL; }
FMOD_OPENSTATE getOpenState(unsigned int* percentbuffered=NULL, bool* starving=NULL, bool* diskbusy=NULL);
protected:
FMOD::System* mSystem;
FMOD::Channel* mStreamChannel;
FMOD::Sound* mInternetStream;
bool mReady;
std::string mInternetStreamURL;
// <FS:Ansariel FS:CR> Streamtitle display
std::string mArtist;
std::string mTitle;
// </FS:Ansariel FS:CR>
};
//---------------------------------------------------------------------------
// Internet Streaming
//---------------------------------------------------------------------------
LLStreamingAudio_FMODEX::LLStreamingAudio_FMODEX(FMOD::System *system) :
mSystem(system),
mCurrentInternetStreamp(NULL),
mFMODInternetStreamChannelp(NULL),
mGain(1.0f)
{
// Number of milliseconds of audio to buffer for the audio card.
// Must be larger than the usual Second Life frame stutter time.
const U32 buffer_seconds = 10; //sec
const U32 estimated_bitrate = 128; //kbit/sec
mSystem->setStreamBufferSize(estimated_bitrate * buffer_seconds * 128/*bytes/kbit*/, FMOD_TIMEUNIT_RAWBYTES);
// Here's where we set the size of the network buffer and some buffering
// parameters. In this case we want a network buffer of 16k, we want it
// to prebuffer 40% of that when we first connect, and we want it
// to rebuffer 80% of that whenever we encounter a buffer underrun.
// Leave the net buffer properties at the default.
//FSOUND_Stream_Net_SetBufferProperties(20000, 40, 80);
}
LLStreamingAudio_FMODEX::~LLStreamingAudio_FMODEX()
{
// nothing interesting/safe to do.
}
void LLStreamingAudio_FMODEX::start(const std::string& url)
{
//if (!mInited)
//{
// llwarns << "startInternetStream before audio initialized" << llendl;
// return;
//}
// "stop" stream but don't clear url, etc. in case url == mInternetStreamURL
stop();
if (!url.empty())
{
llinfos << "Starting internet stream: " << url << llendl;
mCurrentInternetStreamp = new LLAudioStreamManagerFMODEX(mSystem,url);
mURL = url;
}
else
{
llinfos << "Set internet stream to null" << llendl;
mURL.clear();
}
}
void LLStreamingAudio_FMODEX::update()
{
// Kill dead internet streams, if possible
std::list<LLAudioStreamManagerFMODEX *>::iterator iter;
for (iter = mDeadStreams.begin(); iter != mDeadStreams.end();)
{
LLAudioStreamManagerFMODEX *streamp = *iter;
if (streamp->stopStream())
{
llinfos << "Closed dead stream" << llendl;
delete streamp;
mDeadStreams.erase(iter++);
}
else
{
iter++;
}
}
// Don't do anything if there are no streams playing
if (!mCurrentInternetStreamp)
{
return;
}
unsigned int progress;
bool starving;
bool diskbusy;
FMOD_OPENSTATE open_state = mCurrentInternetStreamp->getOpenState(&progress, &starving, &diskbusy);
if (open_state == FMOD_OPENSTATE_READY)
{
// Stream is live
// start the stream if it's ready
if (!mFMODInternetStreamChannelp &&
(mFMODInternetStreamChannelp = mCurrentInternetStreamp->startStream()))
{
// Reset volume to previously set volume
setGain(getGain());
mFMODInternetStreamChannelp->setPaused(false);
}
}
else if(open_state == FMOD_OPENSTATE_ERROR)
{
stop();
return;
}
if(mFMODInternetStreamChannelp)
{
FMOD::Sound *sound = NULL;
if(mFMODInternetStreamChannelp->getCurrentSound(&sound) == FMOD_OK && sound)
{
FMOD_TAG tag;
S32 tagcount, dirtytagcount;
if(sound->getNumTags(&tagcount, &dirtytagcount) == FMOD_OK && dirtytagcount)
{
for(S32 i = 0; i < tagcount; ++i)
{
if(sound->getTag(NULL, i, &tag)!=FMOD_OK)
continue;
if (tag.type == FMOD_TAGTYPE_FMOD)
{
if (!strcmp(tag.name, "Sample Rate Change"))
{
llinfos << "Stream forced changing sample rate to " << *((float *)tag.data) << llendl;
mFMODInternetStreamChannelp->setFrequency(*((float *)tag.data));
}
continue;
}
}
}
if(starving)
{
bool paused = false;
mFMODInternetStreamChannelp->getPaused(&paused);
if(!paused)
{
llinfos << "Stream starvation detected! Pausing stream until buffer nearly full." << llendl;
llinfos << " (diskbusy="<<diskbusy<<")" << llendl;
llinfos << " (progress="<<progress<<")" << llendl;
mFMODInternetStreamChannelp->setPaused(true);
}
}
else if(progress > 80)
{
mFMODInternetStreamChannelp->setPaused(false);
}
}
}
}
void LLStreamingAudio_FMODEX::stop()
{
if (mFMODInternetStreamChannelp)
{
mFMODInternetStreamChannelp->setPaused(true);
mFMODInternetStreamChannelp->setPriority(0);
mFMODInternetStreamChannelp = NULL;
}
if (mCurrentInternetStreamp)
{
llinfos << "Stopping internet stream: " << mCurrentInternetStreamp->getURL() << llendl;
if (mCurrentInternetStreamp->stopStream())
{
delete mCurrentInternetStreamp;
}
else
{
llwarns << "Pushing stream to dead list: " << mCurrentInternetStreamp->getURL() << llendl;
mDeadStreams.push_back(mCurrentInternetStreamp);
}
mCurrentInternetStreamp = NULL;
//mURL.clear();
}
}
void LLStreamingAudio_FMODEX::pause(int pauseopt)
{
if (pauseopt < 0)
{
pauseopt = mCurrentInternetStreamp ? 1 : 0;
}
if (pauseopt)
{
if (mCurrentInternetStreamp)
{
stop();
}
}
else
{
start(getURL());
}
}
// A stream is "playing" if it has been requested to start. That
// doesn't necessarily mean audio is coming out of the speakers.
int LLStreamingAudio_FMODEX::isPlaying()
{
if (mCurrentInternetStreamp)
{
return 1; // Active and playing
}
else if (!mURL.empty())
{
return 2; // "Paused"
}
else
{
return 0;
}
}
F32 LLStreamingAudio_FMODEX::getGain()
{
return mGain;
}
std::string LLStreamingAudio_FMODEX::getURL()
{
return mURL;
}
void LLStreamingAudio_FMODEX::setGain(F32 vol)
{
mGain = vol;
if (mFMODInternetStreamChannelp)
{
vol = llclamp(vol * vol, 0.f, 1.f); //should vol be squared here?
mFMODInternetStreamChannelp->setVolume(vol);
}
}
// <FS:Ansariel> Streamtitle display
bool LLStreamingAudio_FMODEX::hasNewMetadata()
{
if (mCurrentInternetStreamp)
{
return mCurrentInternetStreamp->hasNewMetadata();
}
return false;
}
std::string LLStreamingAudio_FMODEX::getCurrentTitle()
{
if (mCurrentInternetStreamp)
{
return mCurrentInternetStreamp->getCurrentTitle();
}
return "";
}
std::string LLStreamingAudio_FMODEX::getCurrentArtist()
{
if (mCurrentInternetStreamp)
{
return mCurrentInternetStreamp->getCurrentArtist();
}
return "";
}
// </FS:Ansariel>
///////////////////////////////////////////////////////
// manager of possibly-multiple internet audio streams
LLAudioStreamManagerFMODEX::LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url) :
mSystem(system),
mStreamChannel(NULL),
mInternetStream(NULL),
mReady(false)
{
mInternetStreamURL = url;
FMOD_RESULT result = mSystem->createStream(url.c_str(), FMOD_2D | FMOD_NONBLOCKING | FMOD_IGNORETAGS, 0, &mInternetStream);
if (result!= FMOD_OK)
{
llwarns << "Couldn't open fmod stream, error "
<< FMOD_ErrorString(result)
<< llendl;
mReady = false;
return;
}
mReady = true;
}
FMOD::Channel *LLAudioStreamManagerFMODEX::startStream()
{
// We need a live and opened stream before we try and play it.
if (!mInternetStream || getOpenState() != FMOD_OPENSTATE_READY)
{
llwarns << "No internet stream to start playing!" << llendl;
return NULL;
}
if(mStreamChannel)
return mStreamChannel; //Already have a channel for this stream.
mSystem->playSound(FMOD_CHANNEL_FREE, mInternetStream, true, &mStreamChannel);
return mStreamChannel;
}
bool LLAudioStreamManagerFMODEX::stopStream()
{
if (mInternetStream)
{
bool close = true;
switch (getOpenState())
{
case FMOD_OPENSTATE_CONNECTING:
close = false;
break;
default:
close = true;
}
if (close)
{
mInternetStream->release();
mStreamChannel = NULL;
mInternetStream = NULL;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
FMOD_OPENSTATE LLAudioStreamManagerFMODEX::getOpenState(unsigned int* percentbuffered, bool* starving, bool* diskbusy)
{
FMOD_OPENSTATE state;
mInternetStream->getOpenState(&state, percentbuffered, starving, diskbusy);
return state;
}
void LLStreamingAudio_FMODEX::setBufferSizes(U32 streambuffertime, U32 decodebuffertime)
{
mSystem->setStreamBufferSize(streambuffertime/1000*128*128, FMOD_TIMEUNIT_RAWBYTES);
FMOD_ADVANCEDSETTINGS settings;
memset(&settings,0,sizeof(settings));
settings.cbsize=sizeof(settings);
settings.defaultDecodeBufferSize = decodebuffertime;//ms
mSystem->setAdvancedSettings(&settings);
}
// <FS:Ansariel> Streamtitle display
bool LLAudioStreamManagerFMODEX::hasNewMetadata()
{
bool ret = false;
FMOD_TAG tag;
FMOD_RESULT res;
res = mInternetStream->getTag("TITLE", 0, &tag);
if (res == FMOD_OK)
{
std::string new_title = std::string((char*)tag.data);
if (new_title != mTitle)
{
mTitle = new_title;
ret = true;
}
}
res = mInternetStream->getTag("ARTIST", 0, &tag);
if (res == FMOD_OK)
{
std::string new_artist = std::string((char*)tag.data);
if (new_artist != mArtist)
{
mArtist = new_artist;
ret = true;
}
}
return ret;
}
std::string LLAudioStreamManagerFMODEX::getCurrentTitle()
{
return mTitle;
}
std::string LLAudioStreamManagerFMODEX::getCurrentArtist()
{
return mArtist;
}
// </FS:Ansariel>
<commit_msg>Add a little debugging to llstreamingaudio_fmodex.cpp<commit_after>/**
* @file streamingaudio_fmodex.cpp
* @brief LLStreamingAudio_FMODEX implementation
*
* $LicenseInfo:firstyear=2002&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llmath.h"
#include "fmod.hpp"
#include "fmod_errors.h"
#include "llstreamingaudio_fmodex.h"
// <FS:CR> FmodEX Error checking
bool fmod_error_check(FMOD_RESULT result)
{
if (result != FMOD_OK)
{
LL_DEBUGS("FmodEX") << result << " " << FMOD_ErrorString(result) << llendl;
return false;
}
else
return true;
}
// </FS:CR>
class LLAudioStreamManagerFMODEX
{
public:
LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url);
FMOD::Channel* startStream();
bool stopStream(); // Returns true if the stream was successfully stopped.
bool ready();
// <FS:Ansariel> Streamtitle display
bool hasNewMetadata();
std::string getCurrentArtist();
std::string getCurrentTitle();
// </FS:Ansariel>
const std::string& getURL() { return mInternetStreamURL; }
FMOD_OPENSTATE getOpenState(unsigned int* percentbuffered=NULL, bool* starving=NULL, bool* diskbusy=NULL);
protected:
FMOD::System* mSystem;
FMOD::Channel* mStreamChannel;
FMOD::Sound* mInternetStream;
bool mReady;
std::string mInternetStreamURL;
// <FS:Ansariel FS:CR> Streamtitle display
std::string mArtist;
std::string mTitle;
// </FS:Ansariel FS:CR>
};
//---------------------------------------------------------------------------
// Internet Streaming
//---------------------------------------------------------------------------
LLStreamingAudio_FMODEX::LLStreamingAudio_FMODEX(FMOD::System *system) :
mSystem(system),
mCurrentInternetStreamp(NULL),
mFMODInternetStreamChannelp(NULL),
mGain(1.0f)
{
// Number of milliseconds of audio to buffer for the audio card.
// Must be larger than the usual Second Life frame stutter time.
const U32 buffer_seconds = 10; //sec
const U32 estimated_bitrate = 128; //kbit/sec
mSystem->setStreamBufferSize(estimated_bitrate * buffer_seconds * 128/*bytes/kbit*/, FMOD_TIMEUNIT_RAWBYTES);
// Here's where we set the size of the network buffer and some buffering
// parameters. In this case we want a network buffer of 16k, we want it
// to prebuffer 40% of that when we first connect, and we want it
// to rebuffer 80% of that whenever we encounter a buffer underrun.
// Leave the net buffer properties at the default.
//FSOUND_Stream_Net_SetBufferProperties(20000, 40, 80);
}
LLStreamingAudio_FMODEX::~LLStreamingAudio_FMODEX()
{
// nothing interesting/safe to do.
}
void LLStreamingAudio_FMODEX::start(const std::string& url)
{
//if (!mInited)
//{
// llwarns << "startInternetStream before audio initialized" << llendl;
// return;
//}
// "stop" stream but don't clear url, etc. in case url == mInternetStreamURL
stop();
if (!url.empty())
{
llinfos << "Starting internet stream: " << url << llendl;
mCurrentInternetStreamp = new LLAudioStreamManagerFMODEX(mSystem,url);
mURL = url;
}
else
{
llinfos << "Set internet stream to null" << llendl;
mURL.clear();
}
}
void LLStreamingAudio_FMODEX::update()
{
// Kill dead internet streams, if possible
std::list<LLAudioStreamManagerFMODEX *>::iterator iter;
for (iter = mDeadStreams.begin(); iter != mDeadStreams.end();)
{
LLAudioStreamManagerFMODEX *streamp = *iter;
if (streamp->stopStream())
{
llinfos << "Closed dead stream" << llendl;
delete streamp;
mDeadStreams.erase(iter++);
}
else
{
iter++;
}
}
// Don't do anything if there are no streams playing
if (!mCurrentInternetStreamp)
{
return;
}
unsigned int progress;
bool starving;
bool diskbusy;
FMOD_OPENSTATE open_state = mCurrentInternetStreamp->getOpenState(&progress, &starving, &diskbusy);
if (open_state == FMOD_OPENSTATE_READY)
{
// Stream is live
// start the stream if it's ready
if (!mFMODInternetStreamChannelp &&
(mFMODInternetStreamChannelp = mCurrentInternetStreamp->startStream()))
{
// Reset volume to previously set volume
setGain(getGain());
mFMODInternetStreamChannelp->setPaused(false);
}
}
else if(open_state == FMOD_OPENSTATE_ERROR)
{
stop();
return;
}
if(mFMODInternetStreamChannelp)
{
FMOD::Sound *sound = NULL;
// <FS:CR> FmodEX Error checking
//if(mFMODInternetStreamChannelp->getCurrentSound(&sound) == FMOD_OK && sound)
if (fmod_error_check(mFMODInternetStreamChannelp->getCurrentSound(&sound)) && sound)
// </FS:CR>
{
FMOD_TAG tag;
S32 tagcount, dirtytagcount;
// <FS:CR> FmodEX Error checking
//if(sound->getNumTags(&tagcount, &dirtytagcount) == FMOD_OK && dirtytagcount)
if(fmod_error_check(sound->getNumTags(&tagcount, &dirtytagcount)) && dirtytagcount)
// </FS:CR>
{
for(S32 i = 0; i < tagcount; ++i)
{
if(sound->getTag(NULL, i, &tag) != FMOD_OK)
continue;
if (tag.type == FMOD_TAGTYPE_FMOD)
{
if (!strcmp(tag.name, "Sample Rate Change"))
{
llinfos << "Stream forced changing sample rate to " << *((float *)tag.data) << llendl;
mFMODInternetStreamChannelp->setFrequency(*((float *)tag.data));
}
continue;
}
}
}
if(starving)
{
bool paused = false;
mFMODInternetStreamChannelp->getPaused(&paused);
if(!paused)
{
llinfos << "Stream starvation detected! Pausing stream until buffer nearly full." << llendl;
llinfos << " (diskbusy="<<diskbusy<<")" << llendl;
llinfos << " (progress="<<progress<<")" << llendl;
mFMODInternetStreamChannelp->setPaused(true);
}
}
else if(progress > 80)
{
mFMODInternetStreamChannelp->setPaused(false);
}
}
}
}
void LLStreamingAudio_FMODEX::stop()
{
if (mFMODInternetStreamChannelp)
{
mFMODInternetStreamChannelp->setPaused(true);
mFMODInternetStreamChannelp->setPriority(0);
mFMODInternetStreamChannelp = NULL;
}
if (mCurrentInternetStreamp)
{
llinfos << "Stopping internet stream: " << mCurrentInternetStreamp->getURL() << llendl;
if (mCurrentInternetStreamp->stopStream())
{
delete mCurrentInternetStreamp;
}
else
{
llwarns << "Pushing stream to dead list: " << mCurrentInternetStreamp->getURL() << llendl;
mDeadStreams.push_back(mCurrentInternetStreamp);
}
mCurrentInternetStreamp = NULL;
//mURL.clear();
}
}
void LLStreamingAudio_FMODEX::pause(int pauseopt)
{
if (pauseopt < 0)
{
pauseopt = mCurrentInternetStreamp ? 1 : 0;
}
if (pauseopt)
{
if (mCurrentInternetStreamp)
{
stop();
}
}
else
{
start(getURL());
}
}
// A stream is "playing" if it has been requested to start. That
// doesn't necessarily mean audio is coming out of the speakers.
int LLStreamingAudio_FMODEX::isPlaying()
{
if (mCurrentInternetStreamp)
{
return 1; // Active and playing
}
else if (!mURL.empty())
{
return 2; // "Paused"
}
else
{
return 0;
}
}
F32 LLStreamingAudio_FMODEX::getGain()
{
return mGain;
}
std::string LLStreamingAudio_FMODEX::getURL()
{
return mURL;
}
void LLStreamingAudio_FMODEX::setGain(F32 vol)
{
mGain = vol;
if (mFMODInternetStreamChannelp)
{
vol = llclamp(vol * vol, 0.f, 1.f); //should vol be squared here?
mFMODInternetStreamChannelp->setVolume(vol);
}
}
// <FS:Ansariel> Streamtitle display
// virtual
bool LLStreamingAudio_FMODEX::hasNewMetadata()
{
if (mCurrentInternetStreamp)
{
return mCurrentInternetStreamp->hasNewMetadata();
}
return false;
}
// virtual
std::string LLStreamingAudio_FMODEX::getCurrentTitle()
{
if (mCurrentInternetStreamp)
{
return mCurrentInternetStreamp->getCurrentTitle();
}
return "";
}
// virtual
std::string LLStreamingAudio_FMODEX::getCurrentArtist()
{
if (mCurrentInternetStreamp)
{
return mCurrentInternetStreamp->getCurrentArtist();
}
return "";
}
// </FS:Ansariel>
///////////////////////////////////////////////////////
// manager of possibly-multiple internet audio streams
LLAudioStreamManagerFMODEX::LLAudioStreamManagerFMODEX(FMOD::System *system, const std::string& url) :
mSystem(system),
mStreamChannel(NULL),
mInternetStream(NULL),
mReady(false)
{
mInternetStreamURL = url;
FMOD_RESULT result = mSystem->createStream(url.c_str(), FMOD_2D | FMOD_NONBLOCKING | FMOD_IGNORETAGS, 0, &mInternetStream);
if (result != FMOD_OK)
{
llwarns << "Couldn't open fmod stream, error "
<< FMOD_ErrorString(result)
<< llendl;
mReady = false;
return;
}
mReady = true;
}
FMOD::Channel *LLAudioStreamManagerFMODEX::startStream()
{
// We need a live and opened stream before we try and play it.
if (!mInternetStream || getOpenState() != FMOD_OPENSTATE_READY)
{
llwarns << "No internet stream to start playing!" << llendl;
return NULL;
}
if(mStreamChannel)
return mStreamChannel; //Already have a channel for this stream.
mSystem->playSound(FMOD_CHANNEL_FREE, mInternetStream, true, &mStreamChannel);
return mStreamChannel;
}
bool LLAudioStreamManagerFMODEX::stopStream()
{
if (mInternetStream)
{
bool close = true;
switch (getOpenState())
{
case FMOD_OPENSTATE_CONNECTING:
close = false;
break;
default:
close = true;
}
if (close)
{
mInternetStream->release();
mStreamChannel = NULL;
mInternetStream = NULL;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
FMOD_OPENSTATE LLAudioStreamManagerFMODEX::getOpenState(unsigned int* percentbuffered, bool* starving, bool* diskbusy)
{
FMOD_OPENSTATE state;
mInternetStream->getOpenState(&state, percentbuffered, starving, diskbusy);
return state;
}
void LLStreamingAudio_FMODEX::setBufferSizes(U32 streambuffertime, U32 decodebuffertime)
{
mSystem->setStreamBufferSize(streambuffertime/1000*128*128, FMOD_TIMEUNIT_RAWBYTES);
FMOD_ADVANCEDSETTINGS settings;
memset(&settings,0,sizeof(settings));
settings.cbsize=sizeof(settings);
settings.defaultDecodeBufferSize = decodebuffertime;//ms
mSystem->setAdvancedSettings(&settings);
}
// <FS:Ansariel> Streamtitle display
bool LLAudioStreamManagerFMODEX::hasNewMetadata()
{
bool changed = false;
FMOD_TAG tag;
FMOD_RESULT res;
res = mInternetStream->getTag("TITLE", 0, &tag);
if (fmod_error_check(res))
{
std::string new_title = std::string((char*)tag.data);
if (new_title != mTitle)
{
mTitle = new_title;
changed = true;
}
}
res = mInternetStream->getTag("ARTIST", 0, &tag);
if (fmod_error_check(res))
{
std::string new_artist = std::string((char*)tag.data);
if (new_artist != mArtist)
{
mArtist = new_artist;
changed = true;
}
}
return changed;
}
std::string LLAudioStreamManagerFMODEX::getCurrentTitle()
{
return mTitle;
}
std::string LLAudioStreamManagerFMODEX::getCurrentArtist()
{
return mArtist;
}
// </FS:Ansariel>
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Henry de Valence <hdevalence@gmail.com>
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
#include "MarbleRunnerManager.h"
#include "MarblePlacemarkModel.h"
#include "MarbleDebug.h"
#include "MarbleModel.h"
#include "Planet.h"
#include "GeoDataPlacemark.h"
#include "PluginManager.h"
#include "RunnerPlugin.h"
#include "RunnerTask.h"
#include "routing/RouteRequest.h"
#include "routing/RoutingProfilesModel.h"
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QVector>
#include <QtCore/QThreadPool>
#include <QtCore/QTimer>
namespace Marble
{
class MarbleModel;
class MarbleRunnerManagerPrivate
{
public:
MarbleRunnerManager* q;
QString m_lastSearchTerm;
QMutex m_modelMutex;
MarbleModel * m_marbleModel;
MarblePlacemarkModel *m_model;
QVector<GeoDataPlacemark*> m_placemarkContainer;
QVector<GeoDataDocument*> m_routingResult;
QList<GeoDataCoordinates> m_reverseGeocodingResults;
RouteRequest* m_routeRequest;
PluginManager* m_pluginManager;
MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager );
~MarbleRunnerManagerPrivate();
QList<RunnerPlugin*> plugins( RunnerPlugin::Capability capability );
QList<RunnerTask*> m_searchTasks;
QList<RunnerTask*> m_routingTasks;
void cleanupSearchTask( RunnerTask* task );
void cleanupRoutingTask( RunnerTask* task );
};
MarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager ) :
q( parent ),
m_marbleModel( 0 ),
m_model( new MarblePlacemarkModel ),
m_routeRequest( 0 ),
m_pluginManager( pluginManager )
{
m_model->setPlacemarkContainer( &m_placemarkContainer );
qRegisterMetaType<GeoDataPlacemark>( "GeoDataPlacemark" );
qRegisterMetaType<GeoDataCoordinates>( "GeoDataCoordinates" );
qRegisterMetaType<QVector<GeoDataPlacemark*> >( "QVector<GeoDataPlacemark*>" );
}
MarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate()
{
delete m_model;
}
QList<RunnerPlugin*> MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability )
{
QList<RunnerPlugin*> result;
QList<RunnerPlugin*> plugins = m_pluginManager->runnerPlugins();
foreach( RunnerPlugin* plugin, plugins ) {
if ( !plugin->supports( capability ) ) {
continue;
}
if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) {
continue;
}
if ( !plugin->canWork( capability ) ) {
continue;
}
if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) )
{
continue;
}
result << plugin;
}
return result;
}
void MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task )
{
m_searchTasks.removeAll( task );
if ( m_searchTasks.isEmpty() ) {
emit q->searchFinished( m_lastSearchTerm );
}
}
void MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task )
{
m_routingTasks.removeAll( task );
if ( m_routingTasks.isEmpty() && m_routingResult.isEmpty() ) {
emit q->routeRetrieved( 0 );
}
}
MarbleRunnerManager::MarbleRunnerManager( PluginManager* pluginManager, QObject *parent )
: QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) )
{
if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) {
QThreadPool::globalInstance()->setMaxThreadCount( 4 );
}
}
MarbleRunnerManager::~MarbleRunnerManager()
{
delete d;
}
void MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates )
{
d->m_reverseGeocodingResults.removeAll( coordinates );
QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::ReverseGeocoding );
foreach( RunnerPlugin* plugin, plugins ) {
MarbleAbstractRunner* runner = plugin->newRunner();
runner->setParent( this );
connect( runner, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark ) ),
this, SLOT( addReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) );
runner->setModel( d->m_marbleModel );
QThreadPool::globalInstance()->start( new ReverseGeocodingTask( runner, coordinates ) );
}
if ( plugins.isEmpty() ) {
emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() );
}
}
void MarbleRunnerManager::findPlacemarks( const QString &searchTerm )
{
if ( searchTerm == d->m_lastSearchTerm ) {
emit searchResultChanged( d->m_model );
emit searchFinished( searchTerm );
return;
}
d->m_lastSearchTerm = searchTerm;
d->m_searchTasks.clear();
d->m_modelMutex.lock();
d->m_model->removePlacemarks( "MarbleRunnerManager", 0, d->m_placemarkContainer.size() );
qDeleteAll( d->m_placemarkContainer );
d->m_placemarkContainer.clear();
d->m_modelMutex.unlock();
emit searchResultChanged( d->m_model );
if ( searchTerm.trimmed().isEmpty() ) {
emit searchFinished( searchTerm );
return;
}
QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Search );
foreach( RunnerPlugin* plugin, plugins ) {
MarbleAbstractRunner* runner = plugin->newRunner();
runner->setParent( this );
connect( runner, SIGNAL( searchFinished( QVector<GeoDataPlacemark*> ) ),
this, SLOT( addSearchResult( QVector<GeoDataPlacemark*> ) ) );
runner->setModel( d->m_marbleModel );
SearchTask* task = new SearchTask( runner, searchTerm );
connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) );
d->m_searchTasks << task;
QThreadPool::globalInstance()->start( task );
}
}
void MarbleRunnerManager::addSearchResult( QVector<GeoDataPlacemark*> result )
{
mDebug() << "Runner reports" << result.size() << " search results";
if( result.isEmpty() )
return;
d->m_modelMutex.lock();
int start = d->m_placemarkContainer.size();
d->m_placemarkContainer << result;
d->m_model->addPlacemarks( start, result.size() );
d->m_modelMutex.unlock();
emit searchResultChanged( d->m_model );
emit searchResultChanged( d->m_placemarkContainer );
}
void MarbleRunnerManager::setModel( MarbleModel * model )
{
// TODO: Terminate runners which are making use of the map.
d->m_marbleModel = model;
}
void MarbleRunnerManager::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark )
{
if ( !d->m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) {
d->m_reverseGeocodingResults.push_back( coordinates );
emit reverseGeocodingFinished( coordinates, placemark );
}
}
void MarbleRunnerManager::retrieveRoute( RouteRequest *request )
{
RoutingProfile profile = request->routingProfile();
d->m_routingTasks.clear();
d->m_routingResult.clear();
d->m_routeRequest = request;
QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Routing );
bool started = false;
foreach( RunnerPlugin* plugin, plugins ) {
if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) {
continue;
}
started = true;
MarbleAbstractRunner* runner = plugin->newRunner();
runner->setParent( this );
connect( runner, SIGNAL( routeCalculated( GeoDataDocument* ) ),
this, SLOT( addRoutingResult( GeoDataDocument* ) ) );
runner->setModel( d->m_marbleModel );
RoutingTask* task = new RoutingTask( runner, request );
d->m_routingTasks << task;
connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) );
QThreadPool::globalInstance()->start( task );
}
if ( !started ) {
mDebug() << "No routing plugins found, cannot retrieve a route";
d->cleanupRoutingTask( 0 );
}
}
void MarbleRunnerManager::addRoutingResult( GeoDataDocument* route )
{
if ( route ) {
d->m_routingResult.push_back( route );
emit routeRetrieved( route );
}
}
}
#include "MarbleRunnerManager.moc"
<commit_msg>Set a parent on the model to prevent deletion by QML listviews.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Henry de Valence <hdevalence@gmail.com>
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
#include "MarbleRunnerManager.h"
#include "MarblePlacemarkModel.h"
#include "MarbleDebug.h"
#include "MarbleModel.h"
#include "Planet.h"
#include "GeoDataPlacemark.h"
#include "PluginManager.h"
#include "RunnerPlugin.h"
#include "RunnerTask.h"
#include "routing/RouteRequest.h"
#include "routing/RoutingProfilesModel.h"
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QVector>
#include <QtCore/QThreadPool>
#include <QtCore/QTimer>
namespace Marble
{
class MarbleModel;
class MarbleRunnerManagerPrivate
{
public:
MarbleRunnerManager* q;
QString m_lastSearchTerm;
QMutex m_modelMutex;
MarbleModel * m_marbleModel;
MarblePlacemarkModel *m_model;
QVector<GeoDataPlacemark*> m_placemarkContainer;
QVector<GeoDataDocument*> m_routingResult;
QList<GeoDataCoordinates> m_reverseGeocodingResults;
RouteRequest* m_routeRequest;
PluginManager* m_pluginManager;
MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager );
~MarbleRunnerManagerPrivate();
QList<RunnerPlugin*> plugins( RunnerPlugin::Capability capability );
QList<RunnerTask*> m_searchTasks;
QList<RunnerTask*> m_routingTasks;
void cleanupSearchTask( RunnerTask* task );
void cleanupRoutingTask( RunnerTask* task );
};
MarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager ) :
q( parent ),
m_marbleModel( 0 ),
m_model( new MarblePlacemarkModel( parent ) ),
m_routeRequest( 0 ),
m_pluginManager( pluginManager )
{
m_model->setPlacemarkContainer( &m_placemarkContainer );
qRegisterMetaType<GeoDataPlacemark>( "GeoDataPlacemark" );
qRegisterMetaType<GeoDataCoordinates>( "GeoDataCoordinates" );
qRegisterMetaType<QVector<GeoDataPlacemark*> >( "QVector<GeoDataPlacemark*>" );
}
MarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate()
{
// nothing to do
}
QList<RunnerPlugin*> MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability )
{
QList<RunnerPlugin*> result;
QList<RunnerPlugin*> plugins = m_pluginManager->runnerPlugins();
foreach( RunnerPlugin* plugin, plugins ) {
if ( !plugin->supports( capability ) ) {
continue;
}
if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) {
continue;
}
if ( !plugin->canWork( capability ) ) {
continue;
}
if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) )
{
continue;
}
result << plugin;
}
return result;
}
void MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task )
{
m_searchTasks.removeAll( task );
if ( m_searchTasks.isEmpty() ) {
emit q->searchFinished( m_lastSearchTerm );
}
}
void MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task )
{
m_routingTasks.removeAll( task );
if ( m_routingTasks.isEmpty() && m_routingResult.isEmpty() ) {
emit q->routeRetrieved( 0 );
}
}
MarbleRunnerManager::MarbleRunnerManager( PluginManager* pluginManager, QObject *parent )
: QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) )
{
if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) {
QThreadPool::globalInstance()->setMaxThreadCount( 4 );
}
}
MarbleRunnerManager::~MarbleRunnerManager()
{
delete d;
}
void MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates )
{
d->m_reverseGeocodingResults.removeAll( coordinates );
QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::ReverseGeocoding );
foreach( RunnerPlugin* plugin, plugins ) {
MarbleAbstractRunner* runner = plugin->newRunner();
runner->setParent( this );
connect( runner, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark ) ),
this, SLOT( addReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) );
runner->setModel( d->m_marbleModel );
QThreadPool::globalInstance()->start( new ReverseGeocodingTask( runner, coordinates ) );
}
if ( plugins.isEmpty() ) {
emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() );
}
}
void MarbleRunnerManager::findPlacemarks( const QString &searchTerm )
{
if ( searchTerm == d->m_lastSearchTerm ) {
emit searchResultChanged( d->m_model );
emit searchFinished( searchTerm );
return;
}
d->m_lastSearchTerm = searchTerm;
d->m_searchTasks.clear();
d->m_modelMutex.lock();
d->m_model->removePlacemarks( "MarbleRunnerManager", 0, d->m_placemarkContainer.size() );
qDeleteAll( d->m_placemarkContainer );
d->m_placemarkContainer.clear();
d->m_modelMutex.unlock();
emit searchResultChanged( d->m_model );
if ( searchTerm.trimmed().isEmpty() ) {
emit searchFinished( searchTerm );
return;
}
QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Search );
foreach( RunnerPlugin* plugin, plugins ) {
MarbleAbstractRunner* runner = plugin->newRunner();
runner->setParent( this );
connect( runner, SIGNAL( searchFinished( QVector<GeoDataPlacemark*> ) ),
this, SLOT( addSearchResult( QVector<GeoDataPlacemark*> ) ) );
runner->setModel( d->m_marbleModel );
SearchTask* task = new SearchTask( runner, searchTerm );
connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) );
d->m_searchTasks << task;
QThreadPool::globalInstance()->start( task );
}
}
void MarbleRunnerManager::addSearchResult( QVector<GeoDataPlacemark*> result )
{
mDebug() << "Runner reports" << result.size() << " search results";
if( result.isEmpty() )
return;
d->m_modelMutex.lock();
int start = d->m_placemarkContainer.size();
d->m_placemarkContainer << result;
d->m_model->addPlacemarks( start, result.size() );
d->m_modelMutex.unlock();
emit searchResultChanged( d->m_model );
emit searchResultChanged( d->m_placemarkContainer );
}
void MarbleRunnerManager::setModel( MarbleModel * model )
{
// TODO: Terminate runners which are making use of the map.
d->m_marbleModel = model;
}
void MarbleRunnerManager::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark )
{
if ( !d->m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) {
d->m_reverseGeocodingResults.push_back( coordinates );
emit reverseGeocodingFinished( coordinates, placemark );
}
}
void MarbleRunnerManager::retrieveRoute( RouteRequest *request )
{
RoutingProfile profile = request->routingProfile();
d->m_routingTasks.clear();
d->m_routingResult.clear();
d->m_routeRequest = request;
QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Routing );
bool started = false;
foreach( RunnerPlugin* plugin, plugins ) {
if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) {
continue;
}
started = true;
MarbleAbstractRunner* runner = plugin->newRunner();
runner->setParent( this );
connect( runner, SIGNAL( routeCalculated( GeoDataDocument* ) ),
this, SLOT( addRoutingResult( GeoDataDocument* ) ) );
runner->setModel( d->m_marbleModel );
RoutingTask* task = new RoutingTask( runner, request );
d->m_routingTasks << task;
connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) );
QThreadPool::globalInstance()->start( task );
}
if ( !started ) {
mDebug() << "No routing plugins found, cannot retrieve a route";
d->cleanupRoutingTask( 0 );
}
}
void MarbleRunnerManager::addRoutingResult( GeoDataDocument* route )
{
if ( route ) {
d->m_routingResult.push_back( route );
emit routeRetrieved( route );
}
}
}
#include "MarbleRunnerManager.moc"
<|endoftext|> |
<commit_before>// MFEM Example 1 - Parallel Version
//
// Compile with: make ex1p
//
// Sample runs: mpirun -np 4 ex1p -m ../data/square-disc.mesh
//
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "mpi.h"
#include "dmumps_c.h"
// #define JOB_INIT -1
// #define JOB_END -2
#define USE_COMM_WORLD -987654
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../data/star.mesh";
int order = 1;
bool static_cond = false;
bool visualization = true;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 4. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh mesh(mesh_file, 1, 1);
int dim = mesh.Dimension();
// 5. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels = 2;
for (int l = 0; l < ref_levels; l++)
{
mesh.UniformRefinement();
}
}
// 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh pmesh(MPI_COMM_WORLD, mesh);
mesh.Clear();
{
int par_ref_levels = 0;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh.UniformRefinement();
}
}
// 7. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec = new H1_FECollection(order, dim);
ParFiniteElementSpace fespace(&pmesh, fec);
HYPRE_Int size = fespace.GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
// 8. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh.bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh.bdr_attributes.Max());
ess_bdr = 1;
fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 9. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm b(&fespace);
ConstantCoefficient one(1.0);
b.AddDomainIntegrator(new DomainLFIntegrator(one));
b.Assemble();
// 10. Define the solution vector x as a parallel finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
ParGridFunction x(&fespace);
x = 0.0;
// 11. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
ParBilinearForm a(&fespace);
a.AddDomainIntegrator(new DiffusionIntegrator(one));
if (static_cond) { a.EnableStaticCondensation(); }
a.Assemble();
HypreParMatrix A;
Vector B, X;
a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
// 13. Solve the linear system A X = B.
// * With full assembly, use the BoomerAMG preconditioner from hypre.
// * With partial assembly, use Jacobi smoothing, for now.
HypreBoomerAMG *prec = new HypreBoomerAMG;
CGSolver cg(MPI_COMM_WORLD);
cg.SetRelTol(1e-12);
cg.SetMaxIter(2000);
cg.SetPrintLevel(1);
if (prec) { cg.SetPreconditioner(*prec); }
cg.SetOperator(A);
cg.Mult(B, X);
delete prec;
// 14. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a.RecoverFEMSolution(X, b, x);
// A.Threshold();
hypre_ParCSRMatrix * parcsr_op = (hypre_ParCSRMatrix *)const_cast<HypreParMatrix&>(A);
hypre_CSRMatrix *csr_op = hypre_MergeDiagAndOffd(parcsr_op);
int * Iptr = csr_op->i;
int * Jptr = csr_op->j;
double * data = csr_op->data;
int nnz = csr_op->num_nonzeros;
int I[nnz];
int J[nnz];
int n_loc = csr_op->num_rows;
int k = 0;
for (int i = 0; i<n_loc; i++)
{
for (int j = Iptr[i]; j<Iptr[i+1]; j++)
{
I[k] = i+fespace.GetMyTDofOffset()+1;
J[k] = Jptr[k]+1;
k++;
}
}
DMUMPS_STRUC_C id;
MUMPS_INT ierr;
int error = 0;
/* Initialize a MUMPS instance. Use MPI_COMM_WORLD */
id.comm_fortran=USE_COMM_WORLD;
id.job=-1; id.par=1; id.sym=0;
// Mumps init
dmumps_c(&id);
#define ICNTL(I) icntl[(I)-1] /* macro s.t. indices match documentation */
/* No outputs */
// id.ICNTL(1)=-1; id.ICNTL(2)=-1; id.ICNTL(3)=-1; id.ICNTL(4)=0;
id.ICNTL(5) = 0;
id.ICNTL(18) = 3;
id.ICNTL(20) = 0;
// Global number of rows/colums on the host
if (myid == 0) {id.n = A.GetGlobalNumRows();}
// on all procs
id.nnz_loc = nnz;
id.irn_loc = I;
id.jcn_loc = J;
id.a_loc = data;
id.job=1;
dmumps_c(&id);
id.job=2;
dmumps_c(&id);
Vector rhs;
if (myid == 0)
{
rhs.SetSize(A.GetGlobalNumRows());
rhs = 1.0;
id.rhs = rhs.GetData();
}
id.job=3;
dmumps_c(&id);
id.job=-2; // mumps finalize
dmumps_c(&id);
// a.RecoverFEMSolution(B, b, x);
// // 16. Send the solution by socket to a GLVis server.
// if (visualization)
// {
// char vishost[] = "localhost";
// int visport = 19916;
// socketstream sol_sock(vishost, visport);
// sol_sock << "parallel " << num_procs << " " << myid << "\n";
// sol_sock.precision(8);
// sol_sock << "solution\n" << pmesh << x << flush;
// }
// 17. Free the used memory.
delete fec;
MPI_Finalize();
return 0;
}
<commit_msg>distributed rhs and solution<commit_after>// MFEM Example 1 - Parallel Version
//
// Compile with: make ex1p
//
// Sample runs: mpirun -np 4 ex1p -m ../data/square-disc.mesh
//
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "mpi.h"
#include "dmumps_c.h"
// #define JOB_INIT -1
// #define JOB_END -2
#define USE_COMM_WORLD -987654
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../data/star.mesh";
int order = 1;
bool static_cond = false;
bool visualization = true;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 4. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh mesh(mesh_file, 1, 1);
int dim = mesh.Dimension();
// 5. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels = 2;
for (int l = 0; l < ref_levels; l++)
{
mesh.UniformRefinement();
}
}
// 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh pmesh(MPI_COMM_WORLD, mesh);
mesh.Clear();
{
int par_ref_levels = 0;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh.UniformRefinement();
}
}
// 7. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec = new H1_FECollection(order, dim);
ParFiniteElementSpace fespace(&pmesh, fec);
HYPRE_Int size = fespace.GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
// 8. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh.bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh.bdr_attributes.Max());
ess_bdr = 1;
fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 9. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm b(&fespace);
ConstantCoefficient one(1.0);
b.AddDomainIntegrator(new DomainLFIntegrator(one));
b.Assemble();
// 10. Define the solution vector x as a parallel finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
ParGridFunction x(&fespace);
x = 0.0;
// 11. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
ParBilinearForm a(&fespace);
a.AddDomainIntegrator(new DiffusionIntegrator(one));
if (static_cond) { a.EnableStaticCondensation(); }
a.Assemble();
HypreParMatrix A;
Vector B, X;
a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
// // 13. Solve the linear system A X = B.
// // * With full assembly, use the BoomerAMG preconditioner from hypre.
// // * With partial assembly, use Jacobi smoothing, for now.
// HypreBoomerAMG *prec = new HypreBoomerAMG;
// CGSolver cg(MPI_COMM_WORLD);
// cg.SetRelTol(1e-12);
// cg.SetMaxIter(2000);
// cg.SetPrintLevel(1);
// if (prec) { cg.SetPreconditioner(*prec); }
// cg.SetOperator(A);
// cg.Mult(B, X);
// delete prec;
// 14. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
// a.RecoverFEMSolution(X, b, x);
// A.Threshold();
hypre_ParCSRMatrix * parcsr_op = (hypre_ParCSRMatrix *)const_cast<HypreParMatrix&>(A);
hypre_CSRMatrix *csr_op = hypre_MergeDiagAndOffd(parcsr_op);
#if MFEM_HYPRE_VERSION >= 21600
hypre_CSRMatrixBigJtoJ(csr_op);
#endif
int * Iptr = csr_op->i;
int * Jptr = csr_op->j;
double * data = csr_op->data;
int nnz = csr_op->num_nonzeros;
int I[nnz];
int J[nnz];
int n_loc = csr_op->num_rows;
int k = 0;
for (int i = 0; i<n_loc; i++)
{
for (int j = Iptr[i]; j<Iptr[i+1]; j++)
{
I[k] = i+fespace.GetMyTDofOffset()+1;
J[k] = Jptr[k]+1;
k++;
}
}
DMUMPS_STRUC_C id;
MUMPS_INT ierr;
int error = 0;
/* Initialize a MUMPS instance. Use MPI_COMM_WORLD */
id.comm_fortran=USE_COMM_WORLD;
id.job=-1; id.par=1; id.sym=0;
// Mumps init
dmumps_c(&id);
#define ICNTL(I) icntl[(I)-1] /* macro s.t. indices match documentation */
#define INFO(I) info[(I)-1] /* macro s.t. indices match documentation */
/* No outputs */
// id.ICNTL(1)=-1; id.ICNTL(2)=-1; id.ICNTL(3)=-1; id.ICNTL(4)=0;
id.ICNTL(5) = 0;
id.ICNTL(18) = 3;
id.ICNTL(20) = 10; // distributed rhs
id.ICNTL(21) = 1; // distributed solution
// Global number of rows/colums on the host
if (myid == 0) {id.n = A.GetGlobalNumRows();}
// on all procs
id.nnz_loc = nnz;
id.irn_loc = I;
id.jcn_loc = J;
id.a_loc = data;
id.job=1;
dmumps_c(&id);
id.job=2;
dmumps_c(&id);
// local to global row map
int *irhs_loc = new int[n_loc];
for (int i = 0; i < n_loc; i++)
{
irhs_loc[i] = parcsr_op->first_row_index + i + 1; // 1-based indexing offset
}
id.rhs_loc = B.GetData();
id.nloc_rhs = n_loc;
id.lrhs_loc = n_loc;
id.irhs_loc = irhs_loc;
int num_pivots = id.INFO(23);
printf("num_pivots = %d\n", num_pivots);
id.lsol_loc = num_pivots;
id.sol_loc = X.GetData();
int *isol_loc = new int[num_pivots];
id.isol_loc = isol_loc;
// @TODO
// On exit from the solve phase, ISOL loc(i) contains the index of the
// variables for which the solution (in SOL loc) is available on the local
// processor.
id.job=3;
dmumps_c(&id);
id.job=-2; // mumps finalize
dmumps_c(&id);
a.RecoverFEMSolution(X, b, x);
// 16. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << pmesh << x << flush;
}
// 17. Free the used memory.
delete fec;
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>// $Id: elem_refinement.C,v 1.14 2005-05-03 23:22:24 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library 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
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "elem.h"
#include "mesh_refinement.h"
//--------------------------------------------------------------------
// Elem methods
/**
* The following functions only apply when
* AMR is enabled and thus are not present
* otherwise.
*/
#ifdef ENABLE_AMR
void Elem::refine (MeshRefinement& mesh_refinement)
{
assert (this->refinement_flag() == Elem::REFINE);
assert (this->active());
// Two big prime numbers less than
// sqrt(max_unsigned_int) for key creation.
const unsigned int bp1 = 65449;
const unsigned int bp2 = 48661;
// Create my children if necessary
if (!_children)
{
_children = new Elem*[this->n_children()];
for (unsigned int c=0; c<this->n_children(); c++)
{
_children[c] = Elem::build(this->type(), this).release();
_children[c]->set_refinement_flag(Elem::JUST_REFINED);
}
// Compute new nodal locations
// and asssign nodes to children
// Make these static. It is unlikely the
// sizes will change from call to call, so having these
// static should save on reallocations
std::vector<std::vector<Point> > p (this->n_children());
std::vector<std::vector<unsigned int> > keys (this->n_children());
std::vector<std::vector<Node*> > nodes(this->n_children());
// compute new nodal locations
for (unsigned int c=0; c<this->n_children(); c++)
{
p[c].resize (this->child(c)->n_nodes());
keys[c].resize (this->child(c)->n_nodes());
nodes[c].resize(this->child(c)->n_nodes());
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
// zero entries
p[c][nc].zero();
keys[c][nc] = 0;
nodes[c][nc] = NULL;
for (unsigned int n=0; n<this->n_nodes(); n++)
{
// The value from the embedding matrix
const float em_val = this->embedding_matrix(c,nc,n);
if (em_val != 0.)
{
p[c][nc].add_scaled (this->point(n), em_val);
// We may have found the node, in which case we
// won't need to look it up later.
if (em_val == 1.)
nodes[c][nc] = this->get_node(n);
// Otherwise build the key to look for the node
else
{
// An unsigned int associated with the
// address of the node n. We can't use the
// node number since they can change.
#if SIZEOF_INT == SIZEOF_VOID_P
// 32-bit machines
const unsigned int n_id =
reinterpret_cast<unsigned int>(this->get_node(n));
#elif SIZEOF_LONG_INT == SIZEOF_VOID_P
// 64-bit machines
// Another big prime number less than max_unsigned_int
// for key creation on 64-bit machines
const unsigned int bp3 = 4294967291;
const unsigned int n_id =
reinterpret_cast<long unsigned int>(this->get_node(n))%bp3;
#else
// Huh?
#error WHAT KIND OF CRAZY MACHINE IS THIS? CANNOT COMPILE
#endif
// Compute the key for this new node nc. This will
// be used to locate the node if it already exists
// in the mesh.
keys[c][nc] +=
(((static_cast<unsigned int>(em_val*100000.)%bp1) *
(n_id%bp1))%bp1)*bp2;
}
}
}
}
// assign nodes to children & add them to the mesh
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
if (nodes[c][nc] != NULL)
{
this->child(c)->set_node(nc) = nodes[c][nc];
}
else
{
this->child(c)->set_node(nc) =
mesh_refinement.add_point(p[c][nc],
keys[c][nc]);
}
}
mesh_refinement.add_elem (this->child(c));
}
}
else
{
for (unsigned int c=0; c<this->n_children(); c++)
{
assert(this->child(c)->subactive());
this->child(c)->set_refinement_flag(Elem::JUST_REFINED);
}
}
// Un-set my refinement flag now
this->set_refinement_flag(Elem::INACTIVE);
for (unsigned int c=0; c<this->n_children(); c++)
{
assert(this->child(c)->parent() == this);
assert(this->child(c)->active());
}
assert (this->ancestor());
}
void Elem::coarsen()
{
assert (this->refinement_flag() == Elem::COARSEN_INACTIVE);
assert (!this->active());
// We no longer delete children until MeshRefinement::contract()
// delete [] _children;
// _children = NULL;
for (unsigned int c=0; c<this->n_children(); c++)
{
assert (this->child(c)->refinement_flag() == Elem::COARSEN);
this->child(c)->set_refinement_flag(Elem::INACTIVE);
}
this->set_refinement_flag(Elem::JUST_COARSENED);
assert (this->active());
}
void Elem::contract()
{
// Subactive elements get deleted entirely, not contracted
assert (this->active());
// Active contracted elements no longer can have children
if (_children)
{
delete [] _children;
_children = NULL;
}
}
#endif // #ifdef ENABLE_AMR
<commit_msg><commit_after>// $Id: elem_refinement.C,v 1.15 2005-05-04 19:26:23 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library 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
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "elem.h"
#include "mesh_refinement.h"
//--------------------------------------------------------------------
// Elem methods
/**
* The following functions only apply when
* AMR is enabled and thus are not present
* otherwise.
*/
#ifdef ENABLE_AMR
void Elem::refine (MeshRefinement& mesh_refinement)
{
assert (this->refinement_flag() == Elem::REFINE);
assert (this->active());
// Two big prime numbers less than
// sqrt(max_unsigned_int) for key creation.
const unsigned int bp1 = 65449;
const unsigned int bp2 = 48661;
// Create my children if necessary
if (!_children)
{
_children = new Elem*[this->n_children()];
for (unsigned int c=0; c<this->n_children(); c++)
{
_children[c] = Elem::build(this->type(), this).release();
_children[c]->set_refinement_flag(Elem::JUST_REFINED);
}
// Compute new nodal locations
// and asssign nodes to children
// Make these static. It is unlikely the
// sizes will change from call to call, so having these
// static should save on reallocations
std::vector<std::vector<Point> > p (this->n_children());
std::vector<std::vector<unsigned int> > keys (this->n_children());
std::vector<std::vector<Node*> > nodes(this->n_children());
// compute new nodal locations
for (unsigned int c=0; c<this->n_children(); c++)
{
p[c].resize (this->child(c)->n_nodes());
keys[c].resize (this->child(c)->n_nodes());
nodes[c].resize(this->child(c)->n_nodes());
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
// zero entries
p[c][nc].zero();
keys[c][nc] = 0;
nodes[c][nc] = NULL;
for (unsigned int n=0; n<this->n_nodes(); n++)
{
// The value from the embedding matrix
const float em_val = this->embedding_matrix(c,nc,n);
if (em_val != 0.)
{
p[c][nc].add_scaled (this->point(n), em_val);
// We may have found the node, in which case we
// won't need to look it up later.
if (em_val == 1.)
nodes[c][nc] = this->get_node(n);
// Otherwise build the key to look for the node
else
{
// An unsigned int associated with the
// address of the node n. We can't use the
// node number since they can change.
#if SIZEOF_INT == SIZEOF_VOID_P
// 32-bit machines
const unsigned int n_id =
reinterpret_cast<unsigned int>(this->get_node(n));
#elif SIZEOF_LONG_INT == SIZEOF_VOID_P
// 64-bit machines
// Another big prime number less than max_unsigned_int
// for key creation on 64-bit machines
const unsigned int bp3 = 4294967291;
const unsigned int n_id =
reinterpret_cast<long unsigned int>(this->get_node(n))%bp3;
#else
// Huh?
#error WHAT KIND OF CRAZY MACHINE IS THIS? CANNOT COMPILE
#endif
// Compute the key for this new node nc. This will
// be used to locate the node if it already exists
// in the mesh.
keys[c][nc] +=
(((static_cast<unsigned int>(em_val*100000.)%bp1) *
(n_id%bp1))%bp1)*bp2;
}
}
}
}
// assign nodes to children & add them to the mesh
for (unsigned int nc=0; nc<this->child(c)->n_nodes(); nc++)
{
if (nodes[c][nc] != NULL)
{
this->child(c)->set_node(nc) = nodes[c][nc];
}
else
{
this->child(c)->set_node(nc) =
mesh_refinement.add_point(p[c][nc],
keys[c][nc]);
}
}
mesh_refinement.add_elem (this->child(c));
}
}
else
{
for (unsigned int c=0; c<this->n_children(); c++)
{
assert(this->child(c)->subactive());
this->child(c)->set_refinement_flag(Elem::JUST_REFINED);
}
}
// Un-set my refinement flag now
this->set_refinement_flag(Elem::INACTIVE);
for (unsigned int c=0; c<this->n_children(); c++)
{
assert(this->child(c)->parent() == this);
assert(this->child(c)->active());
}
assert (this->ancestor());
}
void Elem::coarsen()
{
assert (this->refinement_flag() == Elem::COARSEN_INACTIVE);
assert (!this->active());
// We no longer delete children until MeshRefinement::contract()
// delete [] _children;
// _children = NULL;
for (unsigned int c=0; c<this->n_children(); c++)
{
assert (this->child(c)->refinement_flag() == Elem::COARSEN);
this->child(c)->set_refinement_flag(Elem::INACTIVE);
}
this->set_refinement_flag(Elem::JUST_COARSENED);
assert (this->active());
}
void Elem::contract()
{
// Subactive elements get deleted entirely, not contracted
assert (this->active());
// Active contracted elements no longer can have children
if (_children)
{
delete [] _children;
_children = NULL;
}
if (this->refinement_flag() == Elem::JUST_COARSENED)
this->set_refinement_flag(Elem::DO_NOTHING);
}
#endif // #ifdef ENABLE_AMR
<|endoftext|> |
<commit_before>/* * This file is part of meego-im-framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "inputcontextdbusaddress.h"
#ifdef MALIIT_USE_GIO_API
#include <gio/gio.h>
#else
#include <glib-object.h>
#include <dbus/dbus-glib.h>
#endif
#include <tr1/memory>
#include <tr1/functional>
#include <QDebug>
/* For glib < 2.30 */
#ifndef G_VALUE_INIT
#define G_VALUE_INIT { 0, { { 0 } } }
#endif
namespace {
const char * const MaliitServerName = "org.maliit.server";
const char * const MaliitServerObjectPath = "/org/maliit/server/address";
const char * const MaliitServerInterface = "org.maliit.Server.Address";
const char * const MaliitServerAddressProperty = "address";
#ifndef MALIIT_USE_GIO_API
const char * const DBusPropertiesInterface = "org.freedesktop.DBus.Properties";
const char * const DBusPropertiesGetMethod = "Get";
#endif
struct SafeUnref
{
#ifdef MALIIT_USE_GIO_API
static inline void cleanup(GDBusProxy *pointer)
{
g_object_unref(pointer);
}
static inline void cleanup(GVariant *pointer)
{
g_variant_unref(pointer);
}
#else
static inline void cleanup(DBusGConnection *pointer)
{
dbus_g_connection_unref(pointer);
}
static inline void cleanup(DBusGProxy *pointer)
{
g_object_unref(pointer);
}
#endif
};
}
namespace Maliit {
namespace InputContext {
namespace DBus {
Address::Address()
{
}
#ifdef MALIIT_USE_GIO_API
const std::string Address::get() const
{
GDBusProxyFlags flags = G_DBUS_PROXY_FLAGS_NONE;
#if defined(NO_SERVER_DBUS_ACTIVATION)
flags = G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START;
#endif
GError *error = NULL;
QScopedPointer<GDBusProxy, SafeUnref>
proxy(g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SESSION,
flags,
0,
MaliitServerName,
MaliitServerObjectPath,
MaliitServerInterface,
0, &error));
if (proxy.isNull()) {
qWarning() << __PRETTY_FUNCTION__ << error->message;
g_error_free(error);
return std::string();
}
QScopedPointer<GVariant, SafeUnref>
address(g_dbus_proxy_get_cached_property(proxy.data(),
MaliitServerAddressProperty));
if (address.isNull()) {
return std::string();
}
std::string result(g_variant_get_string(address.data(), 0));
return result;
}
#else
const std::string Address::get() const
{
GValue value = G_VALUE_INIT;
GError *error = NULL;
QScopedPointer<DBusGConnection, SafeUnref>
connection(dbus_g_bus_get(DBUS_BUS_SESSION, &error));
if (connection.isNull()) {
qWarning() << __PRETTY_FUNCTION__ << error->message;
g_error_free(error);
return std::string();
}
QScopedPointer<DBusGProxy, SafeUnref>
proxy(dbus_g_proxy_new_for_name(connection.data(),
MaliitServerName,
MaliitServerObjectPath,
DBusPropertiesInterface));
if (!dbus_g_proxy_call(proxy.data(),
DBusPropertiesGetMethod,
&error,
G_TYPE_STRING, MaliitServerInterface,
G_TYPE_STRING, MaliitServerAddressProperty,
G_TYPE_INVALID,
G_TYPE_VALUE, &value, G_TYPE_INVALID)) {
qWarning() << __PRETTY_FUNCTION__ << error->message;
g_error_free(error);
return std::string();
}
std::string result(g_value_get_string(&value));
g_value_unset(&value);
return result;
}
#endif
} // namespace DBus
} // namespace InputContext
} // namespace Maliit
<commit_msg>Check for NULL pointers in custom dbus connection deleter<commit_after>/* * This file is part of meego-im-framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "inputcontextdbusaddress.h"
#ifdef MALIIT_USE_GIO_API
#include <gio/gio.h>
#else
#include <glib-object.h>
#include <dbus/dbus-glib.h>
#endif
#include <tr1/memory>
#include <tr1/functional>
#include <QDebug>
/* For glib < 2.30 */
#ifndef G_VALUE_INIT
#define G_VALUE_INIT { 0, { { 0 } } }
#endif
namespace {
const char * const MaliitServerName = "org.maliit.server";
const char * const MaliitServerObjectPath = "/org/maliit/server/address";
const char * const MaliitServerInterface = "org.maliit.Server.Address";
const char * const MaliitServerAddressProperty = "address";
#ifndef MALIIT_USE_GIO_API
const char * const DBusPropertiesInterface = "org.freedesktop.DBus.Properties";
const char * const DBusPropertiesGetMethod = "Get";
#endif
struct SafeUnref
{
#ifdef MALIIT_USE_GIO_API
static inline void cleanup(GDBusProxy *pointer)
{
if (pointer) {
g_object_unref(pointer);
}
}
static inline void cleanup(GVariant *pointer)
{
if (pointer) {
g_variant_unref(pointer);
}
}
#else
static inline void cleanup(DBusGConnection *pointer)
{
if (pointer) {
dbus_g_connection_unref(pointer);
}
}
static inline void cleanup(DBusGProxy *pointer)
{
if (pointer) {
g_object_unref(pointer);
}
}
#endif
};
}
namespace Maliit {
namespace InputContext {
namespace DBus {
Address::Address()
{
}
#ifdef MALIIT_USE_GIO_API
const std::string Address::get() const
{
GDBusProxyFlags flags = G_DBUS_PROXY_FLAGS_NONE;
#if defined(NO_SERVER_DBUS_ACTIVATION)
flags = G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START;
#endif
GError *error = NULL;
QScopedPointer<GDBusProxy, SafeUnref>
proxy(g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SESSION,
flags,
0,
MaliitServerName,
MaliitServerObjectPath,
MaliitServerInterface,
0, &error));
if (proxy.isNull()) {
qWarning() << __PRETTY_FUNCTION__ << error->message;
g_error_free(error);
return std::string();
}
QScopedPointer<GVariant, SafeUnref>
address(g_dbus_proxy_get_cached_property(proxy.data(),
MaliitServerAddressProperty));
if (address.isNull()) {
return std::string();
}
std::string result(g_variant_get_string(address.data(), 0));
return result;
}
#else
const std::string Address::get() const
{
GValue value = G_VALUE_INIT;
GError *error = NULL;
QScopedPointer<DBusGConnection, SafeUnref>
connection(dbus_g_bus_get(DBUS_BUS_SESSION, &error));
if (connection.isNull()) {
qWarning() << __PRETTY_FUNCTION__ << error->message;
g_error_free(error);
return std::string();
}
QScopedPointer<DBusGProxy, SafeUnref>
proxy(dbus_g_proxy_new_for_name(connection.data(),
MaliitServerName,
MaliitServerObjectPath,
DBusPropertiesInterface));
if (!dbus_g_proxy_call(proxy.data(),
DBusPropertiesGetMethod,
&error,
G_TYPE_STRING, MaliitServerInterface,
G_TYPE_STRING, MaliitServerAddressProperty,
G_TYPE_INVALID,
G_TYPE_VALUE, &value, G_TYPE_INVALID)) {
qWarning() << __PRETTY_FUNCTION__ << error->message;
g_error_free(error);
return std::string();
}
std::string result(g_value_get_string(&value));
g_value_unset(&value);
return result;
}
#endif
} // namespace DBus
} // namespace InputContext
} // namespace Maliit
<|endoftext|> |
<commit_before>/*
* 1671. Anansi's Cobweb
* Time limit: 1.0 second
* Memory limit: 64 MB
*
* [Description]
* Usatiy-Polosatiy XIII decided to destroy Anansi's home — his cobweb. The
* cobweb consists of N nodes, some of which are connected by threads. Let
* us say that two nodes belong to the same piece if it is possible to get
* from one node to the other by threads. Usatiy-Polosatiy has already
* decided which threads and in what order he would tear and now wants to
* know the number of pieces in cobweb after each of his actions.
*
* [Input]
* The first line contains integers N and M — the number of nodes and threads
* in the cobweb, respectively(2 ≤ N ≤ 100000; 1 ≤ M ≤ 100000). Each of the
* next M lines contains two different integers — the 1-based indices of nodes
* connected by current thread. The threads are numbered from 1 to M in the
* order of description. Next line contains an integer Q which denotes the
* quantity of threads Usatiy-Polosatiy wants to tear (1 ≤ Q ≤ M). The last
* line contains numbers of these threads — different integers separated by
* spaces.
*
* [Output]
* Output Q integers — the number of pieces in Anansi's cobweb after each of
* Usatiy-Polosatiy's action. Separate numbers with single spaces.
*/
#include <cstdio>
#include <cstdlib>
#include <cinttypes>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
// Get a single input from stdin
template<typename T>
static void get_single_input(T& x)
{
cin >> x;
}
// Get a line input from stdin
// Add the values as elements in Container
template<typename Container>
static void get_inputs(Container& c)
{
typedef typename Container::value_type T;
string line;
while (getline(cin, line))
{
istringstream input(line);
T x;
while (input >> x)
{
c.push_back(x);
}
}
}
struct NullType
{
};
class Vertex
{
public:
typedef std::map<uint32_t, uint32_t> NeighbourMap;
typedef std::list<uint32_t> NeighbourList;
Vertex() : id_(0) {}
explicit Vertex(uint32_t id) : id_(id) {}
Vertex(const Vertex& other)
: id_(other.id_)
{}
~Vertex() {}
void SetId(uint32_t id)
{
id_ = id;
}
uint32_t GetId() const
{
return id_;
}
int AddNeighbour(uint32_t id, uint32_t weight = 0)
{
//if (neighbours_.find(id) != neighbours_.end()) return -1;
neighbours_[id] = weight;
return 0;
}
int RemoveNeighbour(uint32_t id)
{
//if (neighbours_.find(id) == neighbours_.end()) return -1;
neighbours_.erase(id);
return 0;
}
void GetNeighbours(NeighbourList& l)
{
l.clear();
for (NeighbourMap::iterator it = neighbours_.begin();
it != neighbours_.end();
++it)
{
l.push_back(it->first);
}
}
void GetNeighbours(NeighbourMap& m) const
{
m = neighbours_;
}
uint32_t GetNeighbourWeight(uint32_t id)
{
return neighbours_[id];
}
Vertex& operator=(const Vertex& other)
{
if (this != &other)
{
id_ = other.id_;
}
}
private:
uint32_t id_;
NeighbourMap neighbours_;
};
class Graph
{
public:
typedef std::map<uint32_t, Vertex> VertexMap;
Graph() : id_gen_(0) {}
~Graph() {}
inline int AddVertex()
{
return AddVertex(id_gen_++);
}
int AddVertex(uint32_t id)
{
//if (vertices_.find(id) != vertices_.end()) return -1;
Vertex v(id);
vertices_[id] = v;
return 0;
}
Vertex GetVertex(uint32_t id)
{
return vertices_[id];
}
void GetVertices(VertexMap& m)
{
m = vertices_;
}
void DumpVertices()
{
std::cout << "Graph vertices: ";
for (typename VertexMap::iterator it = vertices_.begin();
it != vertices_.end();
++it)
{
std::cout << it->first << ' ';
}
std::cout << endl;
}
int AddEdge(uint32_t from_id, uint32_t to_id, uint32_t weight = 0)
{
/*
if (vertices_.find(from_id) == vertices_.end() ||
vertices_.find(to_id) == vertices_.end())
{
return -1;
}
*/
return vertices_[from_id].AddNeighbour(to_id, weight);
}
int RemoveEdge(uint32_t from_id, uint32_t to_id)
{
/*
if (vertices_.find(from_id) == vertices_.end() ||
vertices_.find(to_id) == vertices_.end())
{
return -1;
}
*/
return vertices_[from_id].RemoveNeighbour(to_id);
}
void DumpEdges()
{
std::cout << "Graph edges: " << std::endl;
for (typename VertexMap::iterator it = vertices_.begin();
it != vertices_.end();
++it)
{
std::cout << "from: " << it->first << ", to: ";
std::list<uint32_t> n;
it->second.GetNeighbours(n);
for (std::list<uint32_t>::iterator it = n.begin(); it != n.end(); ++it)
{
std::cout << *it << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void DFS()
{
cc_count_ = 0;
std::vector<bool> visited(vertices_.size() + 1, false);
std::stack<uint32_t> visit_stack;
for (typename VertexMap::iterator it = vertices_.begin();
it != vertices_.end();
++it)
{
/*
if (std::find(visited.begin(), visited.end(), it->first) != visited.end())
{
continue;
}
*/
if (visited[it->first]) continue;
++cc_count_;
//std::cout << "unvisited node found: " << it->first << std::endl;
//visited.push_back(it->first);
visited[it->first] = true;
visit_stack.push(it->first);
std::list<uint32_t> neighbours;
uint32_t vid;
bool all_neighbours_visited;
while (!visit_stack.empty())
{
vid = visit_stack.top();
vertices_[vid].GetNeighbours(neighbours);
/*
std::cout << "neighbours of: " << vid << std::endl;
for (std::list<uint32_t>::iterator it = neighbours.begin();
it != neighbours.end(); ++it)
{
std::cout << *it << ' ';
}
std::cout << std::endl;
*/
all_neighbours_visited = true;
for (std::list<uint32_t>::iterator it = neighbours.begin();
it != neighbours.end();
++it)
{
//if (std::find(visited.begin(), visited.end(), *it) == visited.end())
if (!visited[*it])
{
all_neighbours_visited = false;
//visited.push_back(*it);
visited[*it] = true;
visit_stack.push(*it);
break;
}
}
if (all_neighbours_visited)
{
visit_stack.pop();
}
}
}
}
uint32_t GetConnectedComponentCount()
{
DFS();
return cc_count_;
}
private:
uint32_t id_gen_;
VertexMap vertices_;
uint32_t cc_count_; // Connected Component Count
};
static void get_n_m(uint32_t& n, uint32_t& m)
{
string line;
getline(cin, line);
istringstream input(line);
input >> n;
input >> m;
}
static void add_vertices(Graph& g, uint32_t n)
{
do
{
g.AddVertex(n--);
}
while (n);
}
template<typename Seq>
static void get_edges(Seq& edges, uint32_t m)
{
typedef typename Seq::value_type ValueType;
while (m--)
{
string line = "";
getline(cin, line);
istringstream input(line);
ValueType u, v;
input >> u;
input >> v;
edges.push_back(u);
edges.push_back(v);
}
}
template<typename Seq>
static void add_edges(Graph& g, Seq& edges)
{
size_t m = edges.size();
typename Seq::iterator from = edges.begin();
typename Seq::iterator to = from + 1;
while (m)
{
//cout << "Add edge from " << *from << " to " << *to << endl;
g.AddEdge(*from, *to);
g.AddEdge(*to, *from);
from += 2;
to += 2;
m -= 2;
}
}
int main()
{
uint32_t n, m;
get_n_m(n, m);
Graph g;
add_vertices(g, n);
//g.DumpVertices();
vector<uint32_t> edges;
get_edges(edges, m);
/*
cout << "origin edges: " << endl;
for (vector<uint32_t>::iterator it = edges.begin(); it != edges.end(); ++it)
{
cout << *it << ' ';
}
cout << endl;
*/
add_edges(g, edges);
//g.DumpEdges();
uint32_t q;
get_single_input(q);
list<uint32_t> threads;
get_inputs(threads);
list<uint32_t>::iterator it = threads.begin();
while (q--)
{
uint32_t from = edges[2 * (*it - 1)];
uint32_t to = edges[2 * (*it - 1) + 1];
g.RemoveEdge(from, to);
g.RemoveEdge(to, from);
uint32_t c = g.GetConnectedComponentCount();
cout << c;
if (q)
{
cout << ' ';
}
else
{
cout << endl;
}
++it;
}
return 0;
}
<commit_msg>TLE12 1671 using DSU<commit_after>/*
* 1671. Anansi's Cobweb
* Time limit: 1.0 second
* Memory limit: 64 MB
*
* [Description]
* Usatiy-Polosatiy XIII decided to destroy Anansi's home — his cobweb. The
* cobweb consists of N nodes, some of which are connected by threads. Let
* us say that two nodes belong to the same piece if it is possible to get
* from one node to the other by threads. Usatiy-Polosatiy has already
* decided which threads and in what order he would tear and now wants to
* know the number of pieces in cobweb after each of his actions.
*
* [Input]
* The first line contains integers N and M — the number of nodes and threads
* in the cobweb, respectively(2 ≤ N ≤ 100000; 1 ≤ M ≤ 100000). Each of the
* next M lines contains two different integers — the 1-based indices of nodes
* connected by current thread. The threads are numbered from 1 to M in the
* order of description. Next line contains an integer Q which denotes the
* quantity of threads Usatiy-Polosatiy wants to tear (1 ≤ Q ≤ M). The last
* line contains numbers of these threads — different integers separated by
* spaces.
*
* [Output]
* Output Q integers — the number of pieces in Anansi's cobweb after each of
* Usatiy-Polosatiy's action. Separate numbers with single spaces.
*/
#include <cstdio>
#include <cstdlib>
#include <cinttypes>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
// Get a single input from stdin
template<typename T>
static void get_single_input(T& x)
{
cin >> x;
}
// Get a line input from stdin
// Add the values as elements in Container
template<typename Container>
static void get_inputs(Container& c)
{
typedef typename Container::value_type T;
string line;
while (getline(cin, line))
{
istringstream input(line);
T x;
while (input >> x)
{
c.push_back(x);
}
}
}
class Vertex
{
public:
typedef std::map<uint32_t, uint32_t> NeighbourMap;
typedef std::vector<uint32_t> NeighbourList;
Vertex() : id_(0) {}
explicit Vertex(uint32_t id) : id_(id) {}
Vertex(const Vertex& other)
: id_(other.id_), neighbours_(other.neighbours_)
{}
~Vertex() {}
void SetId(uint32_t id)
{
id_ = id;
}
uint32_t GetId() const
{
return id_;
}
int AddNeighbour(uint32_t id, uint32_t weight = 0)
{
//if (neighbours_.find(id) != neighbours_.end()) return -1;
neighbours_[id] = weight;
return 0;
}
int RemoveNeighbour(uint32_t id)
{
//if (neighbours_.find(id) == neighbours_.end()) return -1;
neighbours_.erase(id);
return 0;
}
void GetNeighbours(NeighbourList& l)
{
l.clear();
l.reserve(neighbours_.size());
for (NeighbourMap::iterator it = neighbours_.begin();
it != neighbours_.end();
++it)
{
l.push_back(it->first);
}
}
void GetNeighbours(NeighbourMap& m) const
{
m = neighbours_;
}
uint32_t GetNeighbourWeight(uint32_t id)
{
return neighbours_[id];
}
Vertex& operator=(const Vertex& other)
{
if (this != &other)
{
id_ = other.id_;
neighbours_ = other.neighbours_;
}
}
bool operator<(const Vertex& other) const
{
return id_ < other.id_;
}
bool operator==(const Vertex& other) const
{
return id_ == other.id_;
}
private:
uint32_t id_;
NeighbourMap neighbours_;
};
struct Edge
{
Edge() : from(0), to(0), weight(0) {}
Edge(uint32_t f, uint32_t t, uint32_t w) : from(f), to(t), weight(w) {}
Edge(const Edge& other) : from(other.from), to(other.to), weight(other.weight) {}
Edge& operator=(const Edge& other)
{
if (this != &other)
{
from = other.from;
to = other.to;
weight = other.weight;
}
return *this;
}
uint32_t from;
uint32_t to;
uint32_t weight;
};
class Graph
{
public:
typedef std::map<uint32_t, Vertex> VertexMap;
typedef typename VertexMap::iterator VertexIter;
typedef std::vector<Vertex> VertexList;
typedef std::vector<Edge> EdgeList;
Graph() : id_gen_(0) {}
~Graph() {}
inline int AddVertex()
{
return AddVertex(id_gen_++);
}
int AddVertex(uint32_t id)
{
//if (vertices_.find(id) != vertices_.end()) return -1;
Vertex v(id);
vertices_[id] = v;
return 0;
}
Vertex GetVertex(uint32_t id)
{
return vertices_[id];
}
void GetVertices(VertexMap& m)
{
m = vertices_;
}
void GetVertices(VertexList& l)
{
for (VertexIter it = vertices_.begin(); it != vertices_.end(); ++it)
{
l.push_back(it->second);
}
}
void DumpVertices()
{
std::cout << "Graph vertices: ";
for (VertexIter it = vertices_.begin(); it != vertices_.end(); ++it)
{
std::cout << it->first << ' ';
}
std::cout << endl;
}
int AddEdge(uint32_t from_id, uint32_t to_id, uint32_t weight = 0)
{
/*
if (vertices_.find(from_id) == vertices_.end() ||
vertices_.find(to_id) == vertices_.end())
{
return -1;
}
*/
return vertices_[from_id].AddNeighbour(to_id, weight);
}
int RemoveEdge(uint32_t from_id, uint32_t to_id)
{
/*
if (vertices_.find(from_id) == vertices_.end() ||
vertices_.find(to_id) == vertices_.end())
{
return -1;
}
*/
return vertices_[from_id].RemoveNeighbour(to_id);
}
void GetEdges(EdgeList& l)
{
for (VertexIter it = vertices_.begin(); it != vertices_.end(); ++it)
{
Vertex::NeighbourMap m;
it->second.GetNeighbours(m);
for (Vertex::NeighbourMap::iterator nit = m.begin(); nit != m.end(); ++nit)
{
uint32_t from = it->second.GetId();
uint32_t to = nit->first;
uint32_t weight = nit->second;
Edge e(from, to, weight);
l.push_back(e);
}
}
}
void DumpEdges()
{
std::cout << "Graph edges: " << std::endl;
for (VertexIter it = vertices_.begin(); it != vertices_.end(); ++it)
{
std::cout << "from: " << it->first << ", to: ";
Vertex::NeighbourList neighbours;
it->second.GetNeighbours(neighbours);
for (Vertex::NeighbourList::iterator it = neighbours.begin();
it != neighbours.end();
++it)
{
std::cout << *it << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void DFS()
{
cc_count_ = 0;
std::vector<bool> visited(vertices_.size() + 1, false);
std::stack<uint32_t> visit_stack;
for (VertexIter it = vertices_.begin(); it != vertices_.end(); ++it)
{
if (visited[it->first]) continue;
++cc_count_;
visited[it->first] = true;
visit_stack.push(it->first);
Vertex::NeighbourList neighbours;
uint32_t vid;
bool all_neighbours_visited;
while (!visit_stack.empty())
{
vid = visit_stack.top();
vertices_[vid].GetNeighbours(neighbours);
all_neighbours_visited = true;
for (Vertex::NeighbourList::iterator it = neighbours.begin();
it != neighbours.end();
++it)
{
if (!visited[*it])
{
all_neighbours_visited = false;
visited[*it] = true;
visit_stack.push(*it);
break;
}
}
if (all_neighbours_visited)
{
visit_stack.pop();
}
}
}
}
uint32_t GetConnectedComponentCount()
{
DFS();
return cc_count_;
}
private:
uint32_t id_gen_;
VertexMap vertices_;
uint32_t cc_count_; // Connected Component Count
};
template<typename Rank, typename Parent>
class DisjointSet
{
public:
DisjointSet(Rank r, Parent p) : rank_(r), parent_(p) {}
~DisjointSet() {}
DisjointSet(const DisjointSet& other)
: rank_(other.rank_),
parent_(other.parent_)
{}
template<typename Element>
void MakeSet(Element x)
{
parent_[x] = x;
typedef typename Rank::value_type::second_type R;
rank_[x] = R();
}
template<typename Element>
void LinkSet(Element x, Element y)
{
if (x == y) return;
if (rank_[x] > rank_[y])
{
parent_[y] = x;
}
else if (rank_[y] > rank_[x])
{
parent_[x] = y;
}
else
{
parent_[y] = x;
++rank_[x];
}
}
template<typename Element>
void UnionSet(Element x, Element y)
{
LinkSet(FindSet(x), FindSet(y));
}
template<typename Element>
Element FindSet(Element x)
{
typedef std::list<Element> ElementList;
ElementList l;
while (!(parent_[x] == x))
{
l.push_back(x);
x = parent_[x];
}
for (typename ElementList::iterator it = l.begin();
it != l.end();
++it)
{
parent_[*it] = x;
}
return x;
}
template<typename ElementIterator>
std::size_t CountSet(ElementIterator first, ElementIterator last)
{
std::size_t count = 0;
for (; first != last; ++first)
{
if (parent_[*first] == *first)
{
++count;
}
}
return count;
}
private:
Rank rank_;
Parent parent_;
};
static void get_n_m(uint32_t& n, uint32_t& m)
{
string line;
getline(cin, line);
istringstream input(line);
input >> n;
input >> m;
}
static void add_vertices(Graph& g, uint32_t n)
{
do
{
g.AddVertex(n--);
}
while (n);
}
template<typename Seq>
static void get_edges(Seq& edges, uint32_t m)
{
typedef typename Seq::value_type ValueType;
edges.reserve(m * 2);
while (m--)
{
string line = "";
getline(cin, line);
istringstream input(line);
ValueType u, v;
input >> u;
input >> v;
edges.push_back(u);
edges.push_back(v);
}
}
template<typename Seq>
static void add_edges(Graph& g, Seq& edges)
{
size_t m = edges.size();
typename Seq::iterator from = edges.begin();
typename Seq::iterator to = from + 1;
while (m)
{
//cout << "Add edge from " << *from << " to " << *to << endl;
g.AddEdge(*from, *to);
g.AddEdge(*to, *from);
from += 2;
to += 2;
m -= 2;
}
}
int main()
{
// setup the graph
uint32_t n, m;
get_n_m(n, m);
Graph g;
add_vertices(g, n);
//g.DumpVertices();
vector<uint32_t> edges;
get_edges(edges, m);
add_edges(g, edges);
//g.DumpEdges();
uint32_t q;
get_single_input(q);
list<uint32_t> threads;
get_inputs(threads);
// jump to last state
for (list<uint32_t>::iterator it = threads.begin();
it != threads.end();
++it)
{
uint32_t from = edges[2 * (*it - 1)];
uint32_t to = edges[2 * (*it - 1) + 1];
g.RemoveEdge(from, to);
g.RemoveEdge(to, from);
}
// setup the disjoint set with last state
typedef std::map<Vertex, uint32_t> Rank;
typedef std::map<Vertex, Vertex> Parent;
Rank r;
Parent p;
DisjointSet<Rank, Parent> dset(r, p);
Graph::VertexList vertices;
g.GetVertices(vertices);
for (Graph::VertexList::iterator it = vertices.begin();
it != vertices.end();
++it)
{
dset.MakeSet(*it);
}
Graph::EdgeList graph_edges;
g.GetEdges(graph_edges);
for (Graph::EdgeList::iterator it = graph_edges.begin();
it != graph_edges.end();
++it)
{
dset.UnionSet(g.GetVertex(it->from), g.GetVertex(it->to));
}
// calculate the connected component in reverse order
stack<size_t> pieces;
size_t c = dset.CountSet(vertices.begin(), vertices.end());
pieces.push(c);
for (list<uint32_t>::reverse_iterator it = threads.rbegin();
it != threads.rend();
++it)
{
uint32_t from = edges[2 * (*it - 1)];
uint32_t to = edges[2 * (*it - 1) + 1];
dset.UnionSet(g.GetVertex(from), g.GetVertex(to));
c = dset.CountSet(vertices.begin(), vertices.end());
pieces.push(c);
}
// first one is not needed
pieces.pop();
while (!pieces.empty())
{
size_t piece = pieces.top();
pieces.pop();
cout << piece;
if (!pieces.empty())
cout << ' ';
else
cout << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "php_module.h"
namespace kroll
{
PHPEvaluator::PHPEvaluator()
: StaticBoundObject("PHPEvaluator")
{
/**
* @tiapi(method=True,name=PHP.evaluate,since=0.7) Evaluates a string as PHP code
* @tiarg(for=PHP.evaluate,name=mimeType,type=String) Code mime type (normally "text/php")
* @tiarg(for=PHP.evaluate,name=code,type=String) PHP script code
* @tiarg(for=PHP.evaluate,name=scope,type=Object) global variable scope
* @tiresult(for=PHP.evaluate,type=any) result of the evaluation
*/
SetMethod("evaluate", &PHPEvaluator::Evaluate);
/**
* @tiapi(method=True,name=PHP.preprocess,since=0.7) Runs a string+URL through preprocessing
* @tiarg(for=PHP.preprocess,name=url,type=String) URL used to load this resource
* @tiarg(for=PHP.preprocess,name=code,type=String) PHP script code
* @tiresult(for=PHP.preprocess,type=String) result of the evaluation
*/
SetMethod("preprocess", &PHPEvaluator::Preprocess);
}
void PHPEvaluator::Evaluate(const ValueList& args, SharedValue result)
{
TSRMLS_FETCH();
if (args.size() != 3
|| !args.at(1)->IsString()
|| !args.at(2)->IsObject())
{
return;
}
const char* code = args[1]->ToString();
SharedKObject windowGlobal = args.at(2)->ToObject();
const char* name = "<embedded PHP>";
SharedValue kv = Value::Undefined;
std::string contextName = CreateContextName();
std::ostringstream codeString, callString;
codeString << "function " << contextName << "() {\n";
codeString << " global $Titanium, $window, $document;\n";
codeString << code;
codeString << " foreach (get_defined_vars() as $var=>$val) {\n";
codeString << " if ($var != 'Titanium' && $var != 'window' && $var != 'document') {\n";
codeString << " $window->$var = $val;\n";
codeString << " }\n";
codeString << " }\n ";
codeString << " $__fns = get_defined_functions();\n";
codeString << " if (array_key_exists(\"user\", $__fns)) {\n";
codeString << " foreach($__fns[\"user\"] as $fname) {\n";
codeString << " if ($fname != \"" << contextName << "\" && !$window->$fname) {";
codeString << " krollAddFunction($window, $fname);\n";
codeString << " }\n";
codeString << " }\n";
codeString << " }\n";
//kroll_populate_context($window);\n";
codeString << "};\n";
codeString << contextName << "();";
zend_first_try {
/* This seems to be needed to make PHP actually give us errors at parse/compile time
* See: main/main.c line 969 */
PG(during_request_startup) = 0;
zval *windowValue = PHPUtils::ToPHPValue(args.at(2));
ZEND_SET_SYMBOL(&EG(symbol_table), "window", windowValue);
SharedValue document = windowGlobal->Get("document");
zval *documentValue = PHPUtils::ToPHPValue(document);
ZEND_SET_SYMBOL(&EG(symbol_table), "document", documentValue);
zend_eval_string((char *) codeString.str().c_str(), NULL, (char *) name TSRMLS_CC);
} zend_catch {
} zend_end_try();
result->SetValue(kv);
}
void PHPEvaluator::FillServerVars(Poco::URI& uri, SharedKObject headers, std::string& httpMethod TSRMLS_DC)
{
// Fill $_SERVER with HTTP headers
zval *SERVER;
array_init(SERVER);
//if (zend_hash_find(&EG(symbol_table), "_SERVER", sizeof("_SERVER"), (void**)&SERVER) == SUCCESS)
//{
SharedStringList headerNames = headers->GetPropertyNames();
for (size_t i = 0; i < headerNames->size(); i++)
{
//zval *headerValue;
const char *headerName = headerNames->at(i)->c_str();
const char *headerValue = headers->GetString(headerName).c_str();
//ALLOC_INIT_ZVAL(headerValue);
//ZVAL_STRING(headerValue, (char*)headers->GetString(headerName).c_str(), 1);
add_assoc_stringl(SERVER, (char *) headerName, (char *) headerValue, strlen(headerValue), 1);
//zend_hash_add(Z_ARRVAL_P(SERVER), (char*)headerName, strlen(headerName)+1, &headerValue, sizeof(zval*), NULL);
//ZEND_SET_SYMBOL(Z_ARRVAL_P(SERVER), (char*)headerName, headerValue);
}
ZEND_SET_SYMBOL(&EG(symbol_table), (char *)"_SERVER", SERVER);
//}
// Fill $_GET with query string parameters
zval *GET;
if (zend_hash_find(&EG(symbol_table), "_GET", sizeof("_GET"), (void**)&GET) == SUCCESS)
{
std::string queryString = uri.getQuery();
Poco::StringTokenizer tokens(uri.getQuery(), "&=");
for (Poco::StringTokenizer::Iterator iter = tokens.begin();
iter != tokens.end(); iter++)
{
std::string key = *iter;
std::string value = *(++iter);
zval *val;
ALLOC_INIT_ZVAL(val);
ZVAL_STRING(val, (char*)value.c_str(), 1);
zend_hash_add(Z_ARRVAL_P(GET), (char*)key.c_str(), key.size()+1, &val, sizeof(zval*), NULL);
}
}
// TODO: Fill $_POST, $_REQUEST
}
void PHPEvaluator::Preprocess(const ValueList& args, SharedValue result)
{
args.VerifyException("s o s s", "preprocess");
std::string url = args.GetString(0);
Poco::URI uri(url);
SharedKObject headers = args.GetObject(1);
std::string httpMethod = args.GetString(2);
std::string path = args.GetString(3);
TSRMLS_FETCH();
PHPModule::SetBuffering(true);
zend_first_try {
/* This seems to be needed to make PHP actually give us errors at parse/compile time
* See: main/main.c line 969 */
PG(during_request_startup) = 0;
FillServerVars(uri, headers, httpMethod TSRMLS_CC);
zend_file_handle script;
script.type = ZEND_HANDLE_FP;
script.filename = (char*)path.c_str();
script.opened_path = NULL;
script.free_filename = 0;
script.handle.fp = fopen(script.filename, "rb");
php_execute_script(&script TSRMLS_CC);
//zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p);
//zend_eval_string((char *) code.c_str(), NULL, (char *) url.c_str() TSRMLS_CC);
} zend_catch {
} zend_end_try();
result->SetString(PHPModule::GetBuffer().str());
PHPModule::SetBuffering(false);
}
std::string PHPEvaluator::CreateContextName()
{
std::ostringstream contextName;
contextName << "_kroll_context_" << rand();
return contextName.str();
}
}
<commit_msg>build fix for osx<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "php_module.h"
namespace kroll
{
PHPEvaluator::PHPEvaluator()
: StaticBoundObject("PHPEvaluator")
{
/**
* @tiapi(method=True,name=PHP.evaluate,since=0.7) Evaluates a string as PHP code
* @tiarg(for=PHP.evaluate,name=mimeType,type=String) Code mime type (normally "text/php")
* @tiarg(for=PHP.evaluate,name=code,type=String) PHP script code
* @tiarg(for=PHP.evaluate,name=scope,type=Object) global variable scope
* @tiresult(for=PHP.evaluate,type=any) result of the evaluation
*/
SetMethod("evaluate", &PHPEvaluator::Evaluate);
/**
* @tiapi(method=True,name=PHP.preprocess,since=0.7) Runs a string+URL through preprocessing
* @tiarg(for=PHP.preprocess,name=url,type=String) URL used to load this resource
* @tiarg(for=PHP.preprocess,name=code,type=String) PHP script code
* @tiresult(for=PHP.preprocess,type=String) result of the evaluation
*/
SetMethod("preprocess", &PHPEvaluator::Preprocess);
}
void PHPEvaluator::Evaluate(const ValueList& args, SharedValue result)
{
TSRMLS_FETCH();
if (args.size() != 3
|| !args.at(1)->IsString()
|| !args.at(2)->IsObject())
{
return;
}
const char* code = args[1]->ToString();
SharedKObject windowGlobal = args.at(2)->ToObject();
const char* name = "<embedded PHP>";
SharedValue kv = Value::Undefined;
std::string contextName = CreateContextName();
std::ostringstream codeString, callString;
codeString << "function " << contextName << "() {\n";
codeString << " global $Titanium, $window, $document;\n";
codeString << code;
codeString << " foreach (get_defined_vars() as $var=>$val) {\n";
codeString << " if ($var != 'Titanium' && $var != 'window' && $var != 'document') {\n";
codeString << " $window->$var = $val;\n";
codeString << " }\n";
codeString << " }\n ";
codeString << " $__fns = get_defined_functions();\n";
codeString << " if (array_key_exists(\"user\", $__fns)) {\n";
codeString << " foreach($__fns[\"user\"] as $fname) {\n";
codeString << " if ($fname != \"" << contextName << "\" && !$window->$fname) {";
codeString << " krollAddFunction($window, $fname);\n";
codeString << " }\n";
codeString << " }\n";
codeString << " }\n";
//kroll_populate_context($window);\n";
codeString << "};\n";
codeString << contextName << "();";
zend_first_try {
/* This seems to be needed to make PHP actually give us errors at parse/compile time
* See: main/main.c line 969 */
PG(during_request_startup) = 0;
zval *windowValue = PHPUtils::ToPHPValue(args.at(2));
ZEND_SET_SYMBOL(&EG(symbol_table), "window", windowValue);
SharedValue document = windowGlobal->Get("document");
zval *documentValue = PHPUtils::ToPHPValue(document);
ZEND_SET_SYMBOL(&EG(symbol_table), "document", documentValue);
zend_eval_string((char *) codeString.str().c_str(), NULL, (char *) name TSRMLS_CC);
} zend_catch {
} zend_end_try();
result->SetValue(kv);
}
void PHPEvaluator::FillServerVars(Poco::URI& uri, SharedKObject headers, std::string& httpMethod TSRMLS_DC)
{
// Fill $_SERVER with HTTP headers
zval *SERVER;
array_init(SERVER);
//if (zend_hash_find(&EG(symbol_table), "_SERVER", sizeof("_SERVER"), (void**)&SERVER) == SUCCESS)
//{
SharedStringList headerNames = headers->GetPropertyNames();
for (size_t i = 0; i < headerNames->size(); i++)
{
//zval *headerValue;
const char *headerName = headerNames->at(i)->c_str();
const char *headerValue = headers->GetString(headerName).c_str();
//ALLOC_INIT_ZVAL(headerValue);
//ZVAL_STRING(headerValue, (char*)headers->GetString(headerName).c_str(), 1);
add_assoc_stringl(SERVER, (char *) headerName, (char *) headerValue, strlen(headerValue), 1);
//zend_hash_add(Z_ARRVAL_P(SERVER), (char*)headerName, strlen(headerName)+1, &headerValue, sizeof(zval*), NULL);
//ZEND_SET_SYMBOL(Z_ARRVAL_P(SERVER), (char*)headerName, headerValue);
}
ZEND_SET_SYMBOL(&EG(symbol_table), (char *)"_SERVER", SERVER);
//}
// Fill $_GET with query string parameters
zval *GET;
if (zend_hash_find(&EG(symbol_table), "_GET", sizeof("_GET"), (void**)&GET) == SUCCESS)
{
std::string queryString = uri.getQuery();
Poco::StringTokenizer tokens(uri.getQuery(), "&=");
for (Poco::StringTokenizer::Iterator iter = tokens.begin();
iter != tokens.end(); iter++)
{
std::string key = *iter;
std::string value = *(++iter);
zval *val;
ALLOC_INIT_ZVAL(val);
ZVAL_STRING(val, (char*)value.c_str(), 1);
zend_hash_add(Z_ARRVAL_P(GET), (char*)key.c_str(), key.size()+1, &val, sizeof(zval*), NULL);
}
}
// TODO: Fill $_POST, $_REQUEST
}
void PHPEvaluator::Preprocess(const ValueList& args, SharedValue result)
{
args.VerifyException("s o s s", "preprocess");
std::string url = args.GetString(0);
Poco::URI uri(url);
SharedKObject headers = args.GetObject(1);
std::string httpMethod = args.GetString(2);
std::string path = args.GetString(3);
TSRMLS_FETCH();
PHPModule::SetBuffering(true);
zend_first_try {
/* This seems to be needed to make PHP actually give us errors at parse/compile time
* See: main/main.c line 969 */
PG(during_request_startup) = 0;
FillServerVars(uri, headers, httpMethod TSRMLS_CC);
zend_file_handle script;
script.type = ZEND_HANDLE_FP;
script.filename = (char*)path.c_str();
script.opened_path = NULL;
script.free_filename = 0;
script.handle.fp = fopen(script.filename, "rb");
php_execute_script(&script TSRMLS_CC);
//zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p);
//zend_eval_string((char *) code.c_str(), NULL, (char *) url.c_str() TSRMLS_CC);
} zend_catch {
} zend_end_try();
result->SetString(PHPModule::GetBuffer().str().c_str());
PHPModule::SetBuffering(false);
}
std::string PHPEvaluator::CreateContextName()
{
std::ostringstream contextName;
contextName << "_kroll_context_" << rand();
return contextName.str();
}
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Nico Blodow (blodow@cs.tum.edu)
*/
#include <pcl/io/kinect_grabber.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/shared_ptr.hpp>
#include <pcl/visualization/cloud_viewer.h>
#include <iostream>
//pcl_visualization::CloudViewer viewer ("Simple Kinect Viewer");
class SimpleKinectViewer
{
public:
SimpleKinectViewer () : viewer ("KinectGrabber"), init_(false) {}
void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
//boost::mutex::scoped_lock (mutex_);
//cloud_ = cloud;
if (!viewer.wasStopped())
viewer.showCloud (*cloud);
}
void viz_cb (pcl_visualization::PCLVisualizer& viz)
{
if (!init_)
{
viz.setBackgroundColor (1,1,1);
init_ = true;
}
else
viz.removePointCloud ("KinectCloud");
boost::mutex::scoped_lock (mutex_);
if (cloud_)
viz.addPointCloud (*cloud_, "KinectCloud");
}
void run ()
{
pcl::Grabber* interface = new pcl::OpenNIGrabber();
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleKinectViewer::cloud_cb_, this, _1);
boost::signals2::connection c = interface->registerCallback (f);
boost::function1<void, pcl_visualization::PCLVisualizer&> fn = boost::bind (&SimpleKinectViewer::viz_cb, this, _1);
//viewer.runOnVisualizationThread (fn, "viz_cb");
interface->start ();
while (!viewer.wasStopped())
{
}
interface->stop ();
}
pcl_visualization::CloudViewer viewer;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud_;
bool init_;
};
int main ()
{
SimpleKinectViewer v;
v.run ();
return 0;
}
<commit_msg>"..."<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Nico Blodow (blodow@cs.tum.edu)
*/
#include <pcl/io/kinect_grabber.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/shared_ptr.hpp>
#include <pcl/visualization/cloud_viewer.h>
#include <iostream>
//pcl_visualization::CloudViewer viewer ("Simple Kinect Viewer");
class SimpleKinectViewer
{
public:
SimpleKinectViewer () : viewer ("KinectGrabber"), init_(false) {}
void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
//boost::mutex::scoped_lock lock(mutex_);
//cloud_ = cloud;
if (!viewer.wasStopped())
viewer.showCloud (*cloud);
}
void viz_cb (pcl_visualization::PCLVisualizer& viz)
{
if (!init_)
{
viz.setBackgroundColor (1,1,1);
init_ = true;
}
else
viz.removePointCloud ("KinectCloud");
boost::mutex::scoped_lock lock(mutex_);
if (cloud_)
viz.addPointCloud (*cloud_, "KinectCloud");
}
void run ()
{
pcl::Grabber* interface = new pcl::OpenNIGrabber();
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleKinectViewer::cloud_cb_, this, _1);
boost::signals2::connection c = interface->registerCallback (f);
boost::function1<void, pcl_visualization::PCLVisualizer&> fn = boost::bind (&SimpleKinectViewer::viz_cb, this, _1);
//viewer.runOnVisualizationThread (fn, "viz_cb");
interface->start ();
while (!viewer.wasStopped())
{
}
interface->stop ();
}
pcl_visualization::CloudViewer viewer;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud_;
bool init_;
};
int main ()
{
SimpleKinectViewer v;
v.run ();
return 0;
}
<|endoftext|> |
<commit_before>/*
SPI.cpp - SPI library for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SPI.h"
#include "HardwareSerial.h"
typedef union {
uint32_t regValue;
struct {
unsigned regL :6;
unsigned regH :6;
unsigned regN :6;
unsigned regPre :13;
unsigned regEQU :1;
};
} spiClk_t;
SPIClass SPI;
SPIClass::SPIClass() {
}
void SPIClass::begin() {
pinMode(SCK, SPECIAL); ///< GPIO14
pinMode(MISO, SPECIAL); ///< GPIO12
pinMode(MOSI, SPECIAL); ///< GPIO13
SPI1C = 0;
setFrequency(1000000); ///< 1MHz
SPI1U = SPIUMOSI | SPIUDUPLEX | SPIUSSE;
SPI1U1 = (7 << SPILMOSI) | (7 << SPILMISO);
SPI1C1 = 0;
}
void SPIClass::end() {
pinMode(SCK, INPUT);
pinMode(MISO, INPUT);
pinMode(MOSI, INPUT);
}
void SPIClass::beginTransaction(SPISettings settings) {
setFrequency(settings._clock);
setBitOrder(settings._bitOrder);
setDataMode(settings._dataMode);
}
void SPIClass::endTransaction() {
}
void SPIClass::setDataMode(uint8_t dataMode) {
/**
SPI_MODE0 0x00 - CPOL: 0 CPHA: 0
SPI_MODE1 0x01 - CPOL: 0 CPHA: 1
SPI_MODE2 0x10 - CPOL: 1 CPHA: 0
SPI_MODE3 0x11 - CPOL: 1 CPHA: 1
*/
bool CPOL = (dataMode & 0x10); ///< CPOL (Clock Polarity)
bool CPHA = (dataMode & 0x01); ///< CPHA (Clock Phase)
if(CPHA) {
SPI1U |= (SPIUSME);
} else {
SPI1U &= ~(SPIUSME);
}
if(CPOL) {
//todo How set CPOL???
}
}
void SPIClass::setBitOrder(uint8_t bitOrder) {
if(bitOrder == MSBFIRST) {
SPI1C &= ~(SPICWBO | SPICRBO);
} else {
SPI1C |= (SPICWBO | SPICRBO);
}
}
/**
* calculate the Frequency based on the register value
* @param reg
* @return
*/
static uint32_t ClkRegToFreq(spiClk_t * reg) {
return (F_CPU / ((reg->regPre + 1) * (reg->regN + 1)));
}
void SPIClass::setFrequency(uint32_t freq) {
static uint32_t lastSetFrequency = 0;
static uint32_t lastSetRegister = 0;
if(freq >= F_CPU) {
setClockDivider(0x80000000);
return;
}
if(lastSetFrequency == freq && lastSetRegister == SPI1CLK) {
// do nothing (speed optimization)
return;
}
const spiClk_t minFreqReg = { 0x7FFFF000 };
uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg);
if(freq < minFreq) {
freq = minFreq;
}
uint8_t calN = 1;
spiClk_t bestReg = { 0 };
int32_t bestFreq = 0;
// find the best match
while(calN <= 0x3F) { // 0x3F max for N
spiClk_t reg = { 0 };
int32_t calFreq;
int32_t calPre;
int8_t calPreVari = -2;
reg.regN = calN;
while(calPreVari++ <= 1) { // test different variants for Pre (we calculate in int so we miss the decimals, testing is the easyest and fastest way)
calPre = (((F_CPU / (reg.regN + 1)) / freq) - 1) + calPreVari;
if(calPre > 0x1FFF) {
reg.regPre = 0x1FFF; // 8191
} else if(calPre <= 0) {
reg.regPre = 0;
} else {
reg.regPre = calPre;
}
reg.regL = ((reg.regN + 1) / 2);
// reg.regH = (reg.regN - reg.regL);
// test calculation
calFreq = ClkRegToFreq(®);
//os_printf("-----[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d = %d\n", reg.regValue, freq, reg.regEQU, reg.regPre, reg.regN, reg.regH, reg.regL, calFreq);
if(calFreq == (int32_t) freq) {
// accurate match use it!
memcpy(&bestReg, ®, sizeof(bestReg));
break;
} else if(calFreq < (int32_t) freq) {
// never go over the requested frequency
if(abs(freq - calFreq) < abs(freq - bestFreq)) {
bestFreq = calFreq;
memcpy(&bestReg, ®, sizeof(bestReg));
}
}
}
if(calFreq == (int32_t) freq) {
// accurate match use it!
break;
}
calN++;
}
// os_printf("[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d\t - Real Frequency: %d\n", bestReg.regValue, freq, bestReg.regEQU, bestReg.regPre, bestReg.regN, bestReg.regH, bestReg.regL, ClkRegToFreq(&bestReg));
setClockDivider(bestReg.regValue);
lastSetRegister = SPI1CLK;
lastSetFrequency = freq;
}
void SPIClass::setClockDivider(uint32_t clockDiv) {
if(clockDiv == 0x80000000) {
GPMUX |= (1 << 9); // Set bit 9 if sysclock required
} else {
GPMUX &= ~(1 << 9);
}
SPI1CLK = clockDiv;
}
uint8_t SPIClass::transfer(uint8_t data) {
while(SPI1CMD & SPIBUSY)
;
SPI1W0 = data;
SPI1CMD |= SPIBUSY;
while(SPI1CMD & SPIBUSY)
;
return (uint8_t) (SPI1W0 & 0xff);
}
uint16_t SPIClass::transfer16(uint16_t data) {
union {
uint16_t val;
struct {
uint8_t lsb;
uint8_t msb;
};
} in, out;
in.val = data;
if((SPI1C & (SPICWBO | SPICRBO))) {
//MSBFIRST
out.msb = transfer(in.msb);
out.lsb = transfer(in.lsb);
} else {
//LSBFIRST
out.lsb = transfer(in.lsb);
out.msb = transfer(in.msb);
}
return out.val;
}
<commit_msg>some speed optimizations<commit_after>/*
SPI.cpp - SPI library for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SPI.h"
#include "HardwareSerial.h"
typedef union {
uint32_t regValue;
struct {
unsigned regL :6;
unsigned regH :6;
unsigned regN :6;
unsigned regPre :13;
unsigned regEQU :1;
};
} spiClk_t;
SPIClass SPI;
SPIClass::SPIClass() {
}
void SPIClass::begin() {
pinMode(SCK, SPECIAL); ///< GPIO14
pinMode(MISO, SPECIAL); ///< GPIO12
pinMode(MOSI, SPECIAL); ///< GPIO13
SPI1C = 0;
setFrequency(1000000); ///< 1MHz
SPI1U = SPIUMOSI | SPIUDUPLEX | SPIUSSE;
SPI1U1 = (7 << SPILMOSI) | (7 << SPILMISO);
SPI1C1 = 0;
}
void SPIClass::end() {
pinMode(SCK, INPUT);
pinMode(MISO, INPUT);
pinMode(MOSI, INPUT);
}
void SPIClass::beginTransaction(SPISettings settings) {
setFrequency(settings._clock);
setBitOrder(settings._bitOrder);
setDataMode(settings._dataMode);
}
void SPIClass::endTransaction() {
}
void SPIClass::setDataMode(uint8_t dataMode) {
/**
SPI_MODE0 0x00 - CPOL: 0 CPHA: 0
SPI_MODE1 0x01 - CPOL: 0 CPHA: 1
SPI_MODE2 0x10 - CPOL: 1 CPHA: 0
SPI_MODE3 0x11 - CPOL: 1 CPHA: 1
*/
bool CPOL = (dataMode & 0x10); ///< CPOL (Clock Polarity)
bool CPHA = (dataMode & 0x01); ///< CPHA (Clock Phase)
if(CPHA) {
SPI1U |= (SPIUSME);
} else {
SPI1U &= ~(SPIUSME);
}
if(CPOL) {
//todo How set CPOL???
}
}
void SPIClass::setBitOrder(uint8_t bitOrder) {
if(bitOrder == MSBFIRST) {
SPI1C &= ~(SPICWBO | SPICRBO);
} else {
SPI1C |= (SPICWBO | SPICRBO);
}
}
/**
* calculate the Frequency based on the register value
* @param reg
* @return
*/
static uint32_t ClkRegToFreq(spiClk_t * reg) {
return (F_CPU / ((reg->regPre + 1) * (reg->regN + 1)));
}
void SPIClass::setFrequency(uint32_t freq) {
static uint32_t lastSetFrequency = 0;
static uint32_t lastSetRegister = 0;
if(freq >= F_CPU) {
setClockDivider(0x80000000);
return;
}
if(lastSetFrequency == freq && lastSetRegister == SPI1CLK) {
// do nothing (speed optimization)
return;
}
const spiClk_t minFreqReg = { 0x7FFFF000 };
uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg);
if(freq < minFreq) {
// use minimum possible clock
setClockDivider(minFreqReg.regValue);
lastSetRegister = SPI1CLK;
lastSetFrequency = freq;
return;
}
uint8_t calN = 1;
spiClk_t bestReg = { 0 };
int32_t bestFreq = 0;
// find the best match
while(calN <= 0x3F) { // 0x3F max for N
spiClk_t reg = { 0 };
int32_t calFreq;
int32_t calPre;
int8_t calPreVari = -2;
reg.regN = calN;
while(calPreVari++ <= 1) { // test different variants for Pre (we calculate in int so we miss the decimals, testing is the easyest and fastest way)
calPre = (((F_CPU / (reg.regN + 1)) / freq) - 1) + calPreVari;
if(calPre > 0x1FFF) {
reg.regPre = 0x1FFF; // 8191
} else if(calPre <= 0) {
reg.regPre = 0;
} else {
reg.regPre = calPre;
}
reg.regL = ((reg.regN + 1) / 2);
// reg.regH = (reg.regN - reg.regL);
// test calculation
calFreq = ClkRegToFreq(®);
//os_printf("-----[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d = %d\n", reg.regValue, freq, reg.regEQU, reg.regPre, reg.regN, reg.regH, reg.regL, calFreq);
if(calFreq == (int32_t) freq) {
// accurate match use it!
memcpy(&bestReg, ®, sizeof(bestReg));
break;
} else if(calFreq < (int32_t) freq) {
// never go over the requested frequency
if(abs(freq - calFreq) < abs(freq - bestFreq)) {
bestFreq = calFreq;
memcpy(&bestReg, ®, sizeof(bestReg));
}
}
}
if(calFreq == (int32_t) freq) {
// accurate match use it!
break;
}
calN++;
}
// os_printf("[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d\t - Real Frequency: %d\n", bestReg.regValue, freq, bestReg.regEQU, bestReg.regPre, bestReg.regN, bestReg.regH, bestReg.regL, ClkRegToFreq(&bestReg));
setClockDivider(bestReg.regValue);
lastSetRegister = SPI1CLK;
lastSetFrequency = freq;
}
void SPIClass::setClockDivider(uint32_t clockDiv) {
if(clockDiv == 0x80000000) {
GPMUX |= (1 << 9); // Set bit 9 if sysclock required
} else {
GPMUX &= ~(1 << 9);
}
SPI1CLK = clockDiv;
}
uint8_t SPIClass::transfer(uint8_t data) {
while(SPI1CMD & SPIBUSY)
;
SPI1W0 = data;
SPI1CMD |= SPIBUSY;
while(SPI1CMD & SPIBUSY)
;
return (uint8_t) (SPI1W0 & 0xff);
}
uint16_t SPIClass::transfer16(uint16_t data) {
union {
uint16_t val;
struct {
uint8_t lsb;
uint8_t msb;
};
} in, out;
in.val = data;
if((SPI1C & (SPICWBO | SPICRBO))) {
//MSBFIRST
out.msb = transfer(in.msb);
out.lsb = transfer(in.lsb);
} else {
//LSBFIRST
out.lsb = transfer(in.lsb);
out.msb = transfer(in.msb);
}
return out.val;
}
<|endoftext|> |
<commit_before>#include <cmd_quest_pass_handler.h>
#include <runtasks.h>
#include <log.h>
#include <QJsonArray>
#include <QCryptographicHash>
CmdQuestPassHandler::CmdQuestPassHandler(){
m_vInputs.push_back(CmdInputDef("questid").integer_().required().description("Quest ID"));
m_vInputs.push_back(CmdInputDef("answer").string_().required().description("Answer"));
TAG = "CmdQuestPassHandler";
}
QString CmdQuestPassHandler::cmd(){
return "quest_pass";
}
bool CmdQuestPassHandler::accessUnauthorized(){
return false;
}
bool CmdQuestPassHandler::accessUser(){
return true;
}
bool CmdQuestPassHandler::accessTester(){
return true;
}
bool CmdQuestPassHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdQuestPassHandler::inputs(){
return m_vInputs;
};
QString CmdQuestPassHandler::description(){
return "Update the quest info";
}
QStringList CmdQuestPassHandler::errors(){
QStringList list;
return list;
}
void CmdQuestPassHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
QJsonObject jsonData;
jsonData["cmd"] = QJsonValue(cmd());
QSqlDatabase db = *(pWebSocketServer->database());
IUserToken *pUserToken = pWebSocketServer->getUserToken(pClient);
int nUserID = 0;
QString sNick = "";
if(pUserToken != NULL) {
nUserID = pUserToken->userid();
sNick = pUserToken->nick();
}
int nQuestID = obj["questid"].toInt();
QString sUserAnswer = obj["answer"].toString().trimmed();
QString sState = "";
QString sQuestAnswer = "";
QString sQuestName = "";
{
QSqlQuery query(db);
query.prepare("SELECT * FROM quest WHERE idquest = :questid");
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
sState = record.value("state").toString();
sQuestAnswer = record.value("answer").toString().trimmed();
sQuestName = record.value("name").toString().trimmed();
}else{
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest not found"));
return;
}
}
// check passed quest
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests WHERE questid = :questid AND userid = :userid");
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest already passed"));
return;
}
}
}
// check answer
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests_answers WHERE user_answer = :user_asnwer AND questid = :questid AND userid = :userid");
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Your already try this answer."));
return;
}
}
}
bool bPassed = sQuestAnswer.toUpper() == sUserAnswer.toUpper();
QString sPassed = bPassed ? "Yes" : "No";
// insert to user tries
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests_answers(userid, questid, user_answer, quest_answer, passed, levenshtein, dt) "
"VALUES(:userid, :questid, :user_answer, :quest_answer, :passed, :levenshtein, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":quest_answer", sQuestAnswer);
query.bindValue(":passed", sPassed);
query.bindValue(":levenshtein", 1000);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
if(!bPassed){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Answer incorrect"));
return;
}
// insert to user passed quests
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests(userid, questid, dt_passed) "
"VALUES(:userid, :questid, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
RunTasks::AddPublicEvents(pWebSocketServer, "quests", "User #" + QString::number(nUserID) + " " + sNick
+ " passed quest #" + QString::number(nQuestID) + " " + sQuestName);
RunTasks::UpdateUserRating(pWebSocketServer, nUserID);
RunTasks::UpdateQuestSolved(pWebSocketServer, nQuestID);
jsonData["result"] = QJsonValue("DONE");
jsonData["m"] = QJsonValue(m);
pWebSocketServer->sendMessage(pClient, jsonData);
}
<commit_msg>Added restriction that game ended<commit_after>#include <cmd_quest_pass_handler.h>
#include <runtasks.h>
#include <log.h>
#include <QJsonArray>
#include <QCryptographicHash>
CmdQuestPassHandler::CmdQuestPassHandler(){
m_vInputs.push_back(CmdInputDef("questid").integer_().required().description("Quest ID"));
m_vInputs.push_back(CmdInputDef("answer").string_().required().description("Answer"));
TAG = "CmdQuestPassHandler";
}
QString CmdQuestPassHandler::cmd(){
return "quest_pass";
}
bool CmdQuestPassHandler::accessUnauthorized(){
return false;
}
bool CmdQuestPassHandler::accessUser(){
return true;
}
bool CmdQuestPassHandler::accessTester(){
return true;
}
bool CmdQuestPassHandler::accessAdmin(){
return true;
}
const QVector<CmdInputDef> &CmdQuestPassHandler::inputs(){
return m_vInputs;
};
QString CmdQuestPassHandler::description(){
return "Update the quest info";
}
QStringList CmdQuestPassHandler::errors(){
QStringList list;
return list;
}
void CmdQuestPassHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){
QJsonObject jsonData;
jsonData["cmd"] = QJsonValue(cmd());
QSqlDatabase db = *(pWebSocketServer->database());
IUserToken *pUserToken = pWebSocketServer->getUserToken(pClient);
int nUserID = 0;
QString sNick = "";
if(pUserToken != NULL) {
nUserID = pUserToken->userid();
sNick = pUserToken->nick();
}
int nQuestID = obj["questid"].toInt();
QString sUserAnswer = obj["answer"].toString().trimmed();
QString sState = "";
QString sQuestAnswer = "";
QString sQuestName = "";
int nGameID = 0;
{
QSqlQuery query(db);
query.prepare("SELECT * FROM quest WHERE idquest = :questid");
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
sState = record.value("state").toString();
sQuestAnswer = record.value("answer").toString().trimmed();
sQuestName = record.value("name").toString().trimmed();
nGameID = record.value("gameid").toInt();
}else{
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest not found"));
return;
}
}
{
QSqlQuery query(db);
query.prepare("SELECT * FROM games WHERE id = :gameid AND date_stop > NOW()");
query.bindValue(":gameid", nGameID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (!query.next()) {
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Game ended"));
return;
}
}
// check passed quest
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests WHERE questid = :questid AND userid = :userid");
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Quest already passed"));
return;
}
}
}
// check answer
{
QSqlQuery query(db);
query.prepare("SELECT COUNT(*) as cnt FROM users_quests_answers WHERE user_answer = :user_asnwer AND questid = :questid AND userid = :userid");
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":questid", nQuestID);
query.bindValue(":userid", nUserID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
if (query.next()) {
QSqlRecord record = query.record();
if(record.value("cnt").toInt() > 0){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(404, "Your already try this answer."));
return;
}
}
}
bool bPassed = sQuestAnswer.toUpper() == sUserAnswer.toUpper();
QString sPassed = bPassed ? "Yes" : "No";
// insert to user tries
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests_answers(userid, questid, user_answer, quest_answer, passed, levenshtein, dt) "
"VALUES(:userid, :questid, :user_answer, :quest_answer, :passed, :levenshtein, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
query.bindValue(":user_answer", sUserAnswer);
query.bindValue(":quest_answer", sQuestAnswer);
query.bindValue(":passed", sPassed);
query.bindValue(":levenshtein", 1000);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
if(!bPassed){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "Answer incorrect"));
return;
}
// insert to user passed quests
{
QSqlQuery query(db);
query.prepare("INSERT INTO users_quests(userid, questid, dt_passed) "
"VALUES(:userid, :questid, NOW())");
query.bindValue(":userid", nUserID);
query.bindValue(":questid", nQuestID);
if(!query.exec()){
pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
return;
}
}
RunTasks::AddPublicEvents(pWebSocketServer, "quests", "User #" + QString::number(nUserID) + " " + sNick
+ " passed quest #" + QString::number(nQuestID) + " " + sQuestName);
RunTasks::UpdateUserRating(pWebSocketServer, nUserID);
RunTasks::UpdateQuestSolved(pWebSocketServer, nQuestID);
jsonData["result"] = QJsonValue("DONE");
jsonData["m"] = QJsonValue(m);
pWebSocketServer->sendMessage(pClient, jsonData);
}
<|endoftext|> |
<commit_before>#include <Halide.h>
#include <stdio.h>
#ifdef _WIN32
extern "C" bool QueryPerformanceCounter(uint64_t *);
extern "C" bool QueryPerformanceFrequency(uint64_t *);
double currentTime() {
uint64_t t, freq;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&freq);
return (t * 1000.0) / freq;
}
#else
#include <sys/time.h>
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
#endif
using namespace Halide;
HalideExtern_2(float, powf, float, float);
int main(int argc, char **argv) {
Func f, g, h;
Var x, y;
f(x, y) = powf((x+1)/512.0f, (y+1)/512.0f);
g(x, y) = pow((x+1)/512.0f, (y+1)/512.0f);
h(x, y) = fast_pow((x+1)/512.0f, (y+1)/512.0f);
f.vectorize(x, 8);
g.vectorize(x, 8);
h.vectorize(x, 8);
f.compile_jit();
g.compile_jit();
h.compile_jit();
Image<float> correct_result(1024, 768);
Image<float> fast_result(1024, 768);
Image<float> faster_result(1024, 768);
double t1 = currentTime();
f.realize(correct_result);
double t2 = currentTime();
g.realize(fast_result);
double t3 = currentTime();
h.realize(faster_result);
double t4 = currentTime();
RDom r(correct_result);
Func fast_error, faster_error;
Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y);
Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y);
fast_error() += fast_delta * fast_delta;
faster_error() += faster_delta * faster_delta;
Image<float> fast_err = fast_error.realize();
Image<float> faster_err = faster_error.realize();
int N = correct_result.width() * correct_result.height();
fast_err(0) = sqrtf(fast_err(0)/N);
faster_err(0) = sqrtf(faster_err(0)/N);
printf("powf: %f ns per pixel\n"
"Halide's pow: %f ns per pixel (rms error = %f)\n"
"Halide's fast_pow: %f ns per pixel (rms error = %f)\n",
1000000*(t2-t1) / N,
1000000*(t3-t2) / N, fast_err(0),
1000000*(t4-t3) / N, faster_err(0));
if (fast_err(0) > 0.0000001) {
printf("Error for pow too large\n");
return -1;
}
if (faster_err(0) > 0.0001) {
printf("Error for fast_pow too large\n");
return -1;
}
if (t2-t1 < t3-t2) {
printf("powf is faster than Halide's pow\n");
return -1;
}
if (t3-t2 < t4-t3) {
printf("pow is faster than fast_pow\n");
return -1;
}
printf("Success!\n");
return 0;
}
<commit_msg>More reliable timing for fast pow test<commit_after>#include <Halide.h>
#include <stdio.h>
#ifdef _WIN32
extern "C" bool QueryPerformanceCounter(uint64_t *);
extern "C" bool QueryPerformanceFrequency(uint64_t *);
double currentTime() {
uint64_t t, freq;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&freq);
return (t * 1000.0) / freq;
}
#else
#include <sys/time.h>
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
#endif
using namespace Halide;
HalideExtern_2(float, powf, float, float);
int main(int argc, char **argv) {
Func f, g, h;
Var x, y;
f(x, y) = powf((x+1)/512.0f, (y+1)/512.0f);
g(x, y) = pow((x+1)/512.0f, (y+1)/512.0f);
h(x, y) = fast_pow((x+1)/512.0f, (y+1)/512.0f);
f.vectorize(x, 8);
g.vectorize(x, 8);
h.vectorize(x, 8);
f.compile_jit();
g.compile_jit();
h.compile_jit();
Image<float> correct_result(2048, 768);
Image<float> fast_result(2048, 768);
Image<float> faster_result(2048, 768);
double t1 = currentTime();
f.realize(correct_result);
double t2 = currentTime();
g.realize(fast_result);
double t3 = currentTime();
h.realize(faster_result);
double t4 = currentTime();
RDom r(correct_result);
Func fast_error, faster_error;
Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y);
Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y);
fast_error() += cast<double>(fast_delta * fast_delta);
faster_error() += cast<double>(faster_delta * faster_delta);
Image<double> fast_err = fast_error.realize();
Image<double> faster_err = faster_error.realize();
int N = correct_result.width() * correct_result.height();
fast_err(0) = sqrt(fast_err(0)/N);
faster_err(0) = sqrt(faster_err(0)/N);
printf("powf: %f ns per pixel\n"
"Halide's pow: %f ns per pixel (rms error = %0.10f)\n"
"Halide's fast_pow: %f ns per pixel (rms error = %0.10f)\n",
1000000*(t2-t1) / N,
1000000*(t3-t2) / N, fast_err(0),
1000000*(t4-t3) / N, faster_err(0));
if (fast_err(0) > 0.000001) {
printf("Error for pow too large\n");
return -1;
}
if (faster_err(0) > 0.0001) {
printf("Error for fast_pow too large\n");
return -1;
}
if (t2-t1 < t3-t2) {
printf("powf is faster than Halide's pow\n");
return -1;
}
if (t3-t2 < t4-t3) {
printf("pow is faster than fast_pow\n");
return -1;
}
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/base:$Name: $:$Id: TViewer3DPad.cxx,v 1.4 2005/03/11 17:22:21 brun Exp $
// Author: Richard Maunder 10/3/2005
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TViewer3DPad.h"
#include "TVirtualPad.h"
#include "TView.h"
#include "TBuffer3D.h"
#include "TBuffer3DTypes.h"
#include <assert.h>
//______________________________________________________________________________
Bool_t TViewer3DPad::PreferLocalFrame() const
{
// Indicates if we prefer positions in local frame. Always false - pad
// drawing is always done in master frame.
return kFALSE;
}
//______________________________________________________________________________
void TViewer3DPad::BeginScene()
{
// Open a scene on the viewer. Is re-entrant as pad requires a two pass
// draw.
assert(!fBuilding);
// Create a 3D view if none exists
TView *view = fPad.GetView();
if (!view) {
view = new TView(11); // Perspective view by default
if (!view) {
assert(kFALSE);
return;
}
fPad.SetView(view);
}
// Perform a first pass to calculate the range
if (!fBuilding && !view->GetAutoRange()) {
view->SetAutoRange(kTRUE);
}
fBuilding = kTRUE;
}
//______________________________________________________________________________
void TViewer3DPad::EndScene()
{
// Close the scene on the viewer
assert(fBuilding);
// If we are doing for auto-range pass on view invoke another pass
TView *view = fPad.GetView();
if (view) {
if (view->GetAutoRange()) {
view->SetAutoRange(kFALSE);
fPad.Paint();
}
}
fBuilding = kFALSE;
}
//______________________________________________________________________________
Int_t TViewer3DPad::AddObject(const TBuffer3D & buffer, Bool_t * addChildren)
{
// Add an 3D object described by the buffer to the viewer. Returns flags
// to indicate:
// i) if extra sections of the buffer need completing.
// ii) if child objects of the buffer object should be added (always true)
// Accept any children
if (addChildren) {
*addChildren = kTRUE;
}
TView * view = fPad.GetView();
if (!view) {
assert(kFALSE);
return TBuffer3D::kNone;
}
UInt_t reqSections = TBuffer3D::kCore|TBuffer3D::kRawSizes|TBuffer3D::kRaw;
if (!buffer.SectionsValid(reqSections)) {
return reqSections;
}
UInt_t i;
Int_t i0, i1, i2;
// Range pass
if (view->GetAutoRange()) {
Double_t x0, y0, z0, x1, y1, z1;
x0 = x1 = buffer.fPnts[0];
y0 = y1 = buffer.fPnts[1];
z0 = z1 = buffer.fPnts[2];
for (i=1; i<buffer.NbPnts(); i++) {
i0 = 3*i; i1 = i0+1; i2 = i0+2;
x0 = buffer.fPnts[i0] < x0 ? buffer.fPnts[i0] : x0;
y0 = buffer.fPnts[i1] < y0 ? buffer.fPnts[i1] : y0;
z0 = buffer.fPnts[i2] < z0 ? buffer.fPnts[i2] : z0;
x1 = buffer.fPnts[i0] > x1 ? buffer.fPnts[i0] : x1;
y1 = buffer.fPnts[i1] > y1 ? buffer.fPnts[i1] : y1;
z1 = buffer.fPnts[i2] > z1 ? buffer.fPnts[i2] : z1;
}
view->SetRange(x0,y0,z0,x1,y1,z1,2);
}
// Actual drawing pass
else {
// Do not show semi transparent objects
if (buffer.fTransparency > 50) {
return TBuffer3D::kNone;
}
if (buffer.Type()== TBuffer3DTypes::kMarker ) {
Double_t pndc[3], temp[3];
for (i=0; i<buffer.NbPnts(); i++) {
for ( i0=0; i0<3; i0++ ) temp[i0] = buffer.fPnts[3*i+i0];
view->WCtoNDC(temp, pndc);
fPad.PaintPolyMarker(1, &pndc[0], &pndc[1]);
}
} else {
for (i=0; i<buffer.NbSegs(); i++) {
i0 = 3*buffer.fSegs[3*i+1];
Double_t *ptpoints_0 = &(buffer.fPnts[i0]);
i0 = 3*buffer.fSegs[3*i+2];
Double_t *ptpoints_3 = &(buffer.fPnts[i0]);
fPad.PaintLine3D(ptpoints_0, ptpoints_3);
}
}
}
return TBuffer3D::kNone;
}
//______________________________________________________________________________
Int_t TViewer3DPad::AddObject(UInt_t /*placedID*/, const TBuffer3D & buffer, Bool_t * addChildren)
{
// We don't support placed ID shapes - ID is discarded
return AddObject(buffer,addChildren);
}
<commit_msg>From Richard: - modified TView to be perspective by default. Revert to cartesian as in v1.3<commit_after>// @(#)root/base:$Name: $:$Id: TViewer3DPad.cxx,v 1.5 2005/03/18 08:03:27 brun Exp $
// Author: Richard Maunder 10/3/2005
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TViewer3DPad.h"
#include "TVirtualPad.h"
#include "TView.h"
#include "TBuffer3D.h"
#include "TBuffer3DTypes.h"
#include <assert.h>
//______________________________________________________________________________
Bool_t TViewer3DPad::PreferLocalFrame() const
{
// Indicates if we prefer positions in local frame. Always false - pad
// drawing is always done in master frame.
return kFALSE;
}
//______________________________________________________________________________
void TViewer3DPad::BeginScene()
{
// Open a scene on the viewer. Is re-entrant as pad requires a two pass
// draw.
assert(!fBuilding);
// Create a 3D view if none exists
TView *view = fPad.GetView();
if (!view) {
view = new TView(1); // Cartesian view by default
if (!view) {
assert(kFALSE);
return;
}
fPad.SetView(view);
}
// Perform a first pass to calculate the range
if (!fBuilding && !view->GetAutoRange()) {
view->SetAutoRange(kTRUE);
}
fBuilding = kTRUE;
}
//______________________________________________________________________________
void TViewer3DPad::EndScene()
{
// Close the scene on the viewer
assert(fBuilding);
// If we are doing for auto-range pass on view invoke another pass
TView *view = fPad.GetView();
if (view) {
if (view->GetAutoRange()) {
view->SetAutoRange(kFALSE);
fPad.Paint();
}
}
fBuilding = kFALSE;
}
//______________________________________________________________________________
Int_t TViewer3DPad::AddObject(const TBuffer3D & buffer, Bool_t * addChildren)
{
// Add an 3D object described by the buffer to the viewer. Returns flags
// to indicate:
// i) if extra sections of the buffer need completing.
// ii) if child objects of the buffer object should be added (always true)
// Accept any children
if (addChildren) {
*addChildren = kTRUE;
}
TView * view = fPad.GetView();
if (!view) {
assert(kFALSE);
return TBuffer3D::kNone;
}
UInt_t reqSections = TBuffer3D::kCore|TBuffer3D::kRawSizes|TBuffer3D::kRaw;
if (!buffer.SectionsValid(reqSections)) {
return reqSections;
}
UInt_t i;
Int_t i0, i1, i2;
// Range pass
if (view->GetAutoRange()) {
Double_t x0, y0, z0, x1, y1, z1;
x0 = x1 = buffer.fPnts[0];
y0 = y1 = buffer.fPnts[1];
z0 = z1 = buffer.fPnts[2];
for (i=1; i<buffer.NbPnts(); i++) {
i0 = 3*i; i1 = i0+1; i2 = i0+2;
x0 = buffer.fPnts[i0] < x0 ? buffer.fPnts[i0] : x0;
y0 = buffer.fPnts[i1] < y0 ? buffer.fPnts[i1] : y0;
z0 = buffer.fPnts[i2] < z0 ? buffer.fPnts[i2] : z0;
x1 = buffer.fPnts[i0] > x1 ? buffer.fPnts[i0] : x1;
y1 = buffer.fPnts[i1] > y1 ? buffer.fPnts[i1] : y1;
z1 = buffer.fPnts[i2] > z1 ? buffer.fPnts[i2] : z1;
}
view->SetRange(x0,y0,z0,x1,y1,z1,2);
}
// Actual drawing pass
else {
// Do not show semi transparent objects
if (buffer.fTransparency > 50) {
return TBuffer3D::kNone;
}
if (buffer.Type()== TBuffer3DTypes::kMarker ) {
Double_t pndc[3], temp[3];
for (i=0; i<buffer.NbPnts(); i++) {
for ( i0=0; i0<3; i0++ ) temp[i0] = buffer.fPnts[3*i+i0];
view->WCtoNDC(temp, pndc);
fPad.PaintPolyMarker(1, &pndc[0], &pndc[1]);
}
} else {
for (i=0; i<buffer.NbSegs(); i++) {
i0 = 3*buffer.fSegs[3*i+1];
Double_t *ptpoints_0 = &(buffer.fPnts[i0]);
i0 = 3*buffer.fSegs[3*i+2];
Double_t *ptpoints_3 = &(buffer.fPnts[i0]);
fPad.PaintLine3D(ptpoints_0, ptpoints_3);
}
}
}
return TBuffer3D::kNone;
}
//______________________________________________________________________________
Int_t TViewer3DPad::AddObject(UInt_t /*placedID*/, const TBuffer3D & buffer, Bool_t * addChildren)
{
// We don't support placed ID shapes - ID is discarded
return AddObject(buffer,addChildren);
}
<|endoftext|> |
<commit_before>// $Id$
AliEmcalPicoTrackMaker* AddTaskEmcalPicoTrackMaker(
const char *name = "PicoTracks",
const char *inname = "tracks",
const char *runperiod = "",
Bool_t includeNoITS = kTRUE,
AliESDtrackCuts *cuts = 0
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalPicoTrackMaker", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalPicoTrackMaker", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
AliEmcalPicoTrackMaker *eTask = new AliEmcalPicoTrackMaker();
eTask->SetTracksOutName(name);
eTask->SetTracksInName(inname);
eTask->SetIncludeNoITS(includeNoITS);
TString runPeriod(runperiod);
runPeriod.ToLower();
if (runPeriod == "lhc11h") {
eTask->SetAODfilterBits(256,512); // hybrid tracks for LHC11h
eTask->SetMC(kFALSE);
}
else if (runPeriod == "lhc11a") {
eTask->SetAODfilterBits(256,16); // hybrid tracks for LHC11a
eTask->SetMC(kFALSE);
}
else if (runPeriod == "lhc12a15a" || runPeriod == "lhc12a15e") {
eTask->SetAODfilterBits(256,16); // hybrid tracks for LHC12a15a and LHC12a15e
eTask->SetMC(kTRUE);
}
else {
if (runPeriod.IsNull())
::Warning("Run period %s not known. It will use IsHybridGlobalConstrainedGlobal.");
}
eTask->SetESDtrackCuts(cuts);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(eTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
mgr->ConnectInput (eTask, 0, cinput1 );
return eTask;
}
<commit_msg>allow to set more options<commit_after>// $Id$
AliEmcalPicoTrackMaker* AddTaskEmcalPicoTrackMaker(
const char *name = "PicoTracks",
const char *inname = "tracks",
const char *runperiod = "",
Bool_t includeNoITS = kTRUE,
Double_t ptmin = 0,
Double_t ptmax = 1000,
Double_t etamin = -10,
Double_t etamax = +10,
Double_t phimin = -10,
Double_t phimax = +10,
AliESDtrackCuts *cuts = 0
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalPicoTrackMaker", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalPicoTrackMaker", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
AliEmcalPicoTrackMaker *eTask = new AliEmcalPicoTrackMaker();
eTask->SetTracksOutName(name);
eTask->SetTracksInName(inname);
eTask->SetIncludeNoITS(includeNoITS);
eTask->SetTrackPtLimits(ptmin, ptmax);
eTask->SetTrackEtaLimits(etamin, etamax);
eTask->SetTrackPhiLimits(phimin, phimax);
TString runPeriod(runperiod);
runPeriod.ToLower();
if (runPeriod == "lhc11h") {
eTask->SetAODfilterBits(256,512); // hybrid tracks for LHC11h
eTask->SetMC(kFALSE);
} else if (runPeriod == "lhc11a") {
eTask->SetAODfilterBits(256,16); // hybrid tracks for LHC11a
eTask->SetMC(kFALSE);
} else if (runPeriod == "lhc12a15a" || runPeriod == "lhc12a15e") {
eTask->SetAODfilterBits(256,16); // hybrid tracks for LHC12a15a and LHC12a15e
eTask->SetMC(kTRUE);
} else if (runPeriod.Contains(":")) {
TObjArray *arr = runPeriod.Tokenize(":");
TString arg1(arr->At(0)->GetName());
TString arg2("-1");
if (arr->GetEntries()>1)
arg2 = arr->At(1)->GetName();
eTask->SetAODfilterBits(arg1.Atoi(),arg2.Atoi());
delete arr;
} else {
if (runPeriod.IsNull())
::Warning("Run period %s not known. It will use IsHybridGlobalConstrainedGlobal.");
}
eTask->SetESDtrackCuts(cuts);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(eTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
mgr->ConnectInput (eTask, 0, cinput1 );
return eTask;
}
<|endoftext|> |
<commit_before>/***************************************************
This is a library for the Adafruit TTL JPEG Camera (VC0706 chipset)
Pick one up today in the adafruit shop!
------> http://www.adafruit.com/products/397
These displays use Serial to communicate, 2 pins are required to interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_VC0706.h"
// Initialization code used by all constructor types
void Adafruit_VC0706::common_init(void) {
swSerial = NULL;
hwSerial = NULL;
frameptr = 0;
bufferLen = 0;
serialNum = 0;
}
// Constructor when using SoftwareSerial or NewSoftSerial
#if ARDUINO >= 100
Adafruit_VC0706::Adafruit_VC0706(SoftwareSerial *ser) {
#else
Adafruit_VC0706::Adafruit_VC0706(NewSoftSerial *ser) {
#endif
common_init(); // Set everything to common state, then...
swSerial = ser; // ...override swSerial with value passed.
}
// Constructor when using HardwareSerial
Adafruit_VC0706::Adafruit_VC0706(HardwareSerial *ser) {
common_init(); // Set everything to common state, then...
hwSerial = ser; // ...override hwSerial with value passed.
}
boolean Adafruit_VC0706::begin(uint16_t baud) {
if(swSerial) swSerial->begin(baud);
else hwSerial->begin(baud);
return reset();
}
boolean Adafruit_VC0706::reset() {
uint8_t args[] = {0x0};
return runCommand(VC0706_RESET, args, 1, 5);
}
boolean Adafruit_VC0706::motionDetected() {
if (readResponse(4, 200) != 4) {
return false;
}
if (! verifyResponse(VC0706_COMM_MOTION_DETECTED))
return false;
return true;
}
boolean Adafruit_VC0706::setMotionStatus(uint8_t x, uint8_t d1, uint8_t d2) {
uint8_t args[] = {0x03, x, d1, d2};
return runCommand(VC0706_MOTION_CTRL, args, sizeof(args), 5);
}
uint8_t Adafruit_VC0706::getMotionStatus(uint8_t x) {
uint8_t args[] = {0x01, x};
return runCommand(VC0706_MOTION_STATUS, args, sizeof(args), 5);
}
boolean Adafruit_VC0706::setMotionDetect(boolean flag) {
if (! setMotionStatus(VC0706_MOTIONCONTROL,
VC0706_UARTMOTION, VC0706_ACTIVATEMOTION))
return false;
uint8_t args[] = {0x01, flag};
runCommand(VC0706_COMM_MOTION_CTRL, args, sizeof(args), 5);
}
boolean Adafruit_VC0706::getMotionDetect(void) {
uint8_t args[] = {0x0};
if (! runCommand(VC0706_COMM_MOTION_STATUS, args, 1, 6))
return false;
return camerabuff[5];
}
uint8_t Adafruit_VC0706::getImageSize() {
uint8_t args[] = {0x4, 0x4, 0x1, 0x00, 0x19};
if (! runCommand(VC0706_READ_DATA, args, sizeof(args), 6))
return -1;
return camerabuff[5];
}
boolean Adafruit_VC0706::setImageSize(uint8_t x) {
uint8_t args[] = {0x05, 0x04, 0x01, 0x00, 0x19, x};
return runCommand(VC0706_WRITE_DATA, args, sizeof(args), 5);
}
/****************** downsize image control */
uint8_t Adafruit_VC0706::getDownsize(void) {
uint8_t args[] = {0x0};
if (! runCommand(VC0706_DOWNSIZE_STATUS, args, 1, 6))
return -1;
return camerabuff[5];
}
boolean Adafruit_VC0706::setDownsize(uint8_t newsize) {
uint8_t args[] = {0x01, newsize};
return runCommand(VC0706_DOWNSIZE_CTRL, args, 2, 5);
}
/***************** other high level commands */
char * Adafruit_VC0706::getVersion(void) {
uint8_t args[] = {0x01};
sendCommand(VC0706_GEN_VERSION, args, 1);
// get reply
if (!readResponse(CAMERABUFFSIZ, 200))
return 0;
camerabuff[bufferLen] = 0; // end it!
return (char *)camerabuff; // return it!
}
/***************** baud rate commands */
char* Adafruit_VC0706::setBaud9600() {
uint8_t args[] = {0x03, 0x01, 0xAE, 0xC8};
sendCommand(VC0706_SET_PORT, args, sizeof(args));
// get reply
if (!readResponse(CAMERABUFFSIZ, 200))
return 0;
camerabuff[bufferLen] = 0; // end it!
return (char *)camerabuff; // return it!
}
char* Adafruit_VC0706::setBaud19200() {
uint8_t args[] = {0x03, 0x01, 0x56, 0xE4};
sendCommand(VC0706_SET_PORT, args, sizeof(args));
// get reply
if (!readResponse(CAMERABUFFSIZ, 200))
return 0;
camerabuff[bufferLen] = 0; // end it!
return (char *)camerabuff; // return it!
}
char* Adafruit_VC0706::setBaud38400() {
uint8_t args[] = {0x03, 0x01, 0x2A, 0xF2};
sendCommand(VC0706_SET_PORT, args, sizeof(args));
// get reply
if (!readResponse(CAMERABUFFSIZ, 200))
return 0;
camerabuff[bufferLen] = 0; // end it!
return (char *)camerabuff; // return it!
}
char* Adafruit_VC0706::setBaud57600() {
uint8_t args[] = {0x03, 0x01, 0x1C, 0x1C};
sendCommand(VC0706_SET_PORT, args, sizeof(args));
// get reply
if (!readResponse(CAMERABUFFSIZ, 200))
return 0;
camerabuff[bufferLen] = 0; // end it!
return (char *)camerabuff; // return it!
}
char* Adafruit_VC0706::setBaud115200() {
uint8_t args[] = {0x03, 0x01, 0x0D, 0xA6};
sendCommand(VC0706_SET_PORT, args, sizeof(args));
// get reply
if (!readResponse(CAMERABUFFSIZ, 200))
return 0;
camerabuff[bufferLen] = 0; // end it!
return (char *)camerabuff; // return it!
}
/****************** high level photo comamnds */
void Adafruit_VC0706::OSD(uint8_t x, uint8_t y, char *str) {
if (strlen(str) > 14) { str[13] = 0; }
uint8_t args[17] = {strlen(str), strlen(str)-1, (y & 0xF) | ((x & 0x3) << 4)};
for (uint8_t i=0; i<strlen(str); i++) {
char c = str[i];
if ((c >= '0') && (c <= '9')) {
str[i] -= '0';
} else if ((c >= 'A') && (c <= 'Z')) {
str[i] -= 'A';
str[i] += 10;
} else if ((c >= 'a') && (c <= 'z')) {
str[i] -= 'a';
str[i] += 36;
}
args[3+i] = str[i];
}
runCommand(VC0706_OSD_ADD_CHAR, args, strlen(str)+3, 5);
printBuff();
}
boolean Adafruit_VC0706::setCompression(uint8_t c) {
uint8_t args[] = {0x5, 0x1, 0x1, 0x12, 0x04, c};
return runCommand(VC0706_WRITE_DATA, args, sizeof(args), 5);
}
uint8_t Adafruit_VC0706::getCompression(void) {
uint8_t args[] = {0x4, 0x1, 0x1, 0x12, 0x04};
runCommand(VC0706_READ_DATA, args, sizeof(args), 6);
printBuff();
return camerabuff[5];
}
boolean Adafruit_VC0706::setPTZ(uint16_t wz, uint16_t hz, uint16_t pan, uint16_t tilt) {
uint8_t args[] = {0x08, wz >> 8, wz,
hz >> 8, wz,
pan>>8, pan,
tilt>>8, tilt};
return (! runCommand(VC0706_SET_ZOOM, args, sizeof(args), 5));
}
boolean Adafruit_VC0706::getPTZ(uint16_t &w, uint16_t &h, uint16_t &wz, uint16_t &hz, uint16_t &pan, uint16_t &tilt) {
uint8_t args[] = {0x0};
if (! runCommand(VC0706_GET_ZOOM, args, sizeof(args), 16))
return false;
printBuff();
w = camerabuff[5];
w <<= 8;
w |= camerabuff[6];
h = camerabuff[7];
h <<= 8;
h |= camerabuff[8];
wz = camerabuff[9];
wz <<= 8;
wz |= camerabuff[10];
hz = camerabuff[11];
hz <<= 8;
hz |= camerabuff[12];
pan = camerabuff[13];
pan <<= 8;
pan |= camerabuff[14];
tilt = camerabuff[15];
tilt <<= 8;
tilt |= camerabuff[16];
return true;
}
boolean Adafruit_VC0706::takePicture() {
frameptr = 0;
return cameraFrameBuffCtrl(VC0706_STOPCURRENTFRAME);
}
boolean Adafruit_VC0706::resumeVideo() {
return cameraFrameBuffCtrl(VC0706_RESUMEFRAME);
}
boolean Adafruit_VC0706::TVon() {
uint8_t args[] = {0x1, 0x1};
return runCommand(VC0706_TVOUT_CTRL, args, sizeof(args), 5);
}
boolean Adafruit_VC0706::TVoff() {
uint8_t args[] = {0x1, 0x0};
return runCommand(VC0706_TVOUT_CTRL, args, sizeof(args), 5);
}
boolean Adafruit_VC0706::cameraFrameBuffCtrl(uint8_t command) {
uint8_t args[] = {0x1, command};
return runCommand(VC0706_FBUF_CTRL, args, sizeof(args), 5);
}
uint32_t Adafruit_VC0706::frameLength(void) {
uint8_t args[] = {0x01, 0x00};
if (!runCommand(VC0706_GET_FBUF_LEN, args, sizeof(args), 9))
return 0;
uint32_t len;
len = camerabuff[5];
len <<= 8;
len |= camerabuff[6];
len <<= 8;
len |= camerabuff[7];
len <<= 8;
len |= camerabuff[8];
return len;
}
uint8_t Adafruit_VC0706::available(void) {
return bufferLen;
}
uint8_t * Adafruit_VC0706::readPicture(uint8_t n) {
uint8_t args[] = {0x0C, 0x0, 0x0A,
0, 0, frameptr >> 8, frameptr & 0xFF,
0, 0, 0, n,
CAMERADELAY >> 8, CAMERADELAY & 0xFF};
if (! runCommand(VC0706_READ_FBUF, args, sizeof(args), 5, false))
return 0;
// read into the buffer PACKETLEN!
if (readResponse(n+5, CAMERADELAY) == 0)
return 0;
frameptr += n;
return camerabuff;
}
/**************** low level commands */
boolean Adafruit_VC0706::runCommand(uint8_t cmd, uint8_t *args, uint8_t argn,
uint8_t resplen, boolean flushflag) {
// flush out anything in the buffer?
if (flushflag) {
readResponse(100, 10);
}
sendCommand(cmd, args, argn);
if (readResponse(resplen, 200) != resplen)
return false;
if (! verifyResponse(cmd))
return false;
return true;
}
void Adafruit_VC0706::sendCommand(uint8_t cmd, uint8_t args[] = 0, uint8_t argn = 0) {
if(swSerial) {
#if ARDUINO >= 100
swSerial->write((byte)0x56);
swSerial->write((byte)serialNum);
swSerial->write((byte)cmd);
for (uint8_t i=0; i<argn; i++) {
swSerial->write((byte)args[i]);
//Serial.print(" 0x");
//Serial.print(args[i], HEX);
}
#else
swSerial->print(0x56, BYTE);
swSerial->print(serialNum, BYTE);
swSerial->print(cmd, BYTE);
for (uint8_t i=0; i<argn; i++) {
swSerial->print(args[i], BYTE);
//Serial.print(" 0x");
//Serial.print(args[i], HEX);
}
#endif
} else {
#if ARDUINO >= 100
hwSerial->write((byte)0x56);
hwSerial->write((byte)serialNum);
hwSerial->write((byte)cmd);
for (uint8_t i=0; i<argn; i++) {
hwSerial->write((byte)args[i]);
//Serial.print(" 0x");
//Serial.print(args[i], HEX);
}
#else
hwSerial->print(0x56, BYTE);
hwSerial->print(serialNum, BYTE);
hwSerial->print(cmd, BYTE);
for (uint8_t i=0; i<argn; i++) {
hwSerial->print(args[i], BYTE);
//Serial.print(" 0x");
//Serial.print(args[i], HEX);
}
#endif
}
//Serial.println();
}
uint8_t Adafruit_VC0706::readResponse(uint8_t numbytes, uint8_t timeout) {
uint8_t counter = 0;
bufferLen = 0;
int avail;
while ((timeout != counter) && (bufferLen != numbytes)){
avail = swSerial ? swSerial->available() : hwSerial->available();
if (avail <= 0) {
delay(1);
counter++;
continue;
}
counter = 0;
// there's a byte!
camerabuff[bufferLen++] = swSerial ? swSerial->read() : hwSerial->read();
}
//printBuff();
//camerabuff[bufferLen] = 0;
//Serial.println((char*)camerabuff);
return bufferLen;
}
boolean Adafruit_VC0706::verifyResponse(uint8_t command) {
if ((camerabuff[0] != 0x76) ||
(camerabuff[1] != serialNum) ||
(camerabuff[2] != command) ||
(camerabuff[3] != 0x0))
return false;
return true;
}
void Adafruit_VC0706::printBuff() {
for (uint8_t i = 0; i< bufferLen; i++) {
Serial.print(" 0x");
Serial.print(camerabuff[i], HEX);
}
Serial.println();
}
<commit_msg>Delete Adafruit_VC0706.cpp<commit_after><|endoftext|> |
<commit_before>
//
// Calculate flow in the forward and central regions using the Q cumulants method.
//
// Inputs:
// - AliAODEvent
//
// Outputs:
// - AnalysisResults.root or forward_flow.root
//
#include <iostream>
#include <TROOT.h>
#include <TSystem.h>
#include <TList.h>
#include <THn.h>
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliAODEvent.h"
#include "AliMCEvent.h"
#include "AliForwardFlowRun2Task.h"
#include "AliForwardQCumulantRun2.h"
#include "AliForwardGenericFramework.h"
#include "AliForwardFlowUtil.h"
using namespace std;
ClassImp(AliForwardFlowRun2Task)
#if 0
; // For emacs
#endif
//_____________________________________________________________________
AliForwardFlowRun2Task::AliForwardFlowRun2Task() : AliAnalysisTaskSE(),
fAOD(0), // input event
fOutputList(0), // output list
fAnalysisList(0),
fEventList(0),
fRandom(0),
centralDist(),
refDist(),
forwardDist(),
fSettings(),
fUtil(),
fCalculator()
{
//
// Default constructor
//
}
//_____________________________________________________________________
AliForwardFlowRun2Task::AliForwardFlowRun2Task(const char* name) : AliAnalysisTaskSE(name),
fAOD(0), // input event
fOutputList(0), // output list
fAnalysisList(0),
fEventList(0),
fRandom(0),
centralDist(),
refDist(),
forwardDist(),
fSettings(),
fUtil(),
fCalculator()
{
//
// Constructor
//
// Parameters:
// name: Name of task
//
// Rely on validation task for event and track selection
DefineInput(1, AliForwardTaskValidation::Class());
// DefineInput(2, TList::Class());
// DefineInput(3, TList::Class());
// DefineInput(4, TList::Class());
DefineOutput(1, TList::Class());
}
//_____________________________________________________________________
void AliForwardFlowRun2Task::UserCreateOutputObjects()
{
//
// Create output objects
//
//bool saveAutoAdd = TH1::AddDirectoryStatus();
fOutputList = new TList(); // the final output list
fOutputList->SetOwner(kTRUE); // memory stuff: the list is owner of all objects it contains and will delete them if requested
TRandom r = TRandom(); // random integer to use for creation of samples (used for error bars).
// Needs to be created here, otherwise it will draw the same random number.
fAnalysisList = new TList();
fEventList = new TList();
fAnalysisList ->SetName("Analysis");
fEventList ->SetName("EventInfo");
fCent = new TH1D("Centrality","Centrality",fSettings.fCentBins,0,60);
fEventList->Add(fCent);
fVertex = new TH1D("Vertex","Vertex",fSettings.fNZvtxBins,fSettings.fZVtxAcceptanceLowEdge,fSettings.fZVtxAcceptanceUpEdge);
fEventList->Add(fVertex);
fCent->SetDirectory(0);
fVertex->SetDirectory(0);
//fEventList->Add(new TH1D("FMDHits","FMDHits",100,0,10));
fdNdeta = new TH2D("dNdeta","dNdeta",200 /*fSettings.fNDiffEtaBins*/,fSettings.fEtaLowEdge,fSettings.fEtaUpEdge,fSettings.fCentBins,0,60);
fdNdeta->SetDirectory(0);
fEventList->Add(fdNdeta);
fAnalysisList->Add(new TList());
fAnalysisList->Add(new TList());
//fAnalysisList->Add(new TList());
static_cast<TList*>(fAnalysisList->At(0))->SetName("Reference");
static_cast<TList*>(fAnalysisList->At(1))->SetName("Differential");
//static_cast<TList*>(fAnalysisList->At(2))->SetName("AutoCorrection");
fOutputList->Add(fAnalysisList);
fOutputList->Add(fEventList);
// do analysis from v_2 to a maximum of v_5
Int_t fMaxMoment = 4;
Int_t dimensions = 5;
Int_t dbins[5] = {fSettings.fnoSamples, fSettings.fNZvtxBins, fSettings.fNDiffEtaBins, fSettings.fCentBins, static_cast<Int_t>(fSettings.kW4ThreeTwoB)+1} ;
Int_t rbins[5] = {fSettings.fnoSamples, fSettings.fNZvtxBins, fSettings.fNRefEtaBins, fSettings.fCentBins, static_cast<Int_t>(fSettings.kW4ThreeTwoB)+1} ;
Double_t xmin[5] = {0,fSettings.fZVtxAcceptanceLowEdge, fSettings.fEtaLowEdge, 0, 0};
Double_t xmax[5] = {10,fSettings.fZVtxAcceptanceUpEdge, fSettings.fEtaUpEdge, 60, static_cast<Double_t>(fSettings.kW4ThreeTwoB)+1};
//static_cast<TList*>(fAnalysisList->At(2))->Add(new THnF("fQcorrfactor", "fQcorrfactor", dimensions, rbins, xmin, xmax)); //(eta, n)
//static_cast<TList*>(fAnalysisList->At(2))->Add(new THnF("fpcorrfactor","fpcorrfactor", dimensions, dbins, xmin, xmax)); //(eta, n)
Int_t ptnmax = (fSettings.doPt ? 10 : 0);
// create a THn for each harmonic
for (Int_t n = 2; n <= fMaxMoment; n++) {
for (Int_t ptn = 0; ptn <= ptnmax; ptn++){
static_cast<TList*>(fAnalysisList->At(0))->Add(new THnD(Form("cumuRef_v%d_pt%d", n,ptn), Form("cumuRef_v%d_pt%d", n,ptn), dimensions, rbins, xmin, xmax));
static_cast<TList*>(fAnalysisList->At(1))->Add(new THnD(Form("cumuDiff_v%d_pt%d", n,ptn),Form("cumuDiff_v%d_pt%d", n,ptn), dimensions, dbins, xmin, xmax));
// The THn has dimensions [random samples, vertex position, eta, centrality, kind of variable to store]
// set names
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(0)->SetName("samples");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(1)->SetName("vertex");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(2)->SetName("eta");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(3)->SetName("cent");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(4)->SetName("identifier");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(0)->SetName("samples");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(1)->SetName("vertex");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(2)->SetName("eta");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(3)->SetName("cent");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(4)->SetName("identifier");
}
}
// Make centralDist
Int_t centralEtaBins = (fSettings.useITS ? 200 : 400);
Int_t centralPhiBins = (fSettings.useITS ? 20 : 400);
Double_t centralEtaMin = (fSettings.useSPD ? -2.5 : fSettings.useITS ? -4 : -1.5);
Double_t centralEtaMax = (fSettings.useSPD ? 2.5 : fSettings.useITS ? 6 : 1.5);
// Make refDist
Int_t refEtaBins = (((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? 200 : 400);
Int_t refPhiBins = (((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? 20 : 400);
Double_t refEtaMin = ((fSettings.ref_mode & fSettings.kSPDref) ? -2.5
: ((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? -4
: -1.5);
Double_t refEtaMax = ((fSettings.ref_mode & fSettings.kSPDref) ? 2.5
: ((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? 6
: 1.5);
centralDist = new TH2D("c","",centralEtaBins,centralEtaMin,centralEtaMax,centralPhiBins,0,2*TMath::Pi());
centralDist ->SetDirectory(0);
refDist = new TH2D("r","",refEtaBins,refEtaMin,refEtaMax,refPhiBins,0,2*TMath::Pi());
refDist ->SetDirectory(0);
forwardDist = new TH2D("ft","",200,-4,6,20,0,TMath::TwoPi());
forwardDist ->SetDirectory(0);
PostData(1, fOutputList);
//TH1::AddDirectory(saveAutoAdd);
}
//_____________________________________________________________________
void AliForwardFlowRun2Task::UserExec(Option_t *)
{
//
// Analyses the event with use of the helper class AliForwardQCumulantRun2
//
// Parameters:
// option: Not used
//
fCalculator.fSettings = fSettings;
fUtil.fSettings = fSettings;
// Get the event validation object
AliForwardTaskValidation* ev_val = dynamic_cast<AliForwardTaskValidation*>(this->GetInputData(1));
if (!ev_val->IsValidEvent()){
PostData(1, this->fOutputList);
return;
}
if (!fSettings.esd){
AliAODEvent* aodevent = dynamic_cast<AliAODEvent*>(InputEvent());
fUtil.fAODevent = aodevent;
if(!aodevent) throw std::runtime_error("Not AOD as expected");
}
if (fSettings.mc) fUtil.fMCevent = this->MCEvent();
fUtil.fevent = fInputEvent;
Double_t cent = fUtil.GetCentrality(fSettings.centrality_estimator);
if (cent > 60.0){
//PostData(1, fOutputList);
return;
}
fUtil.FillData(refDist,centralDist,forwardDist);
// dNdeta
for (Int_t etaBin = 1; etaBin <= centralDist->GetNbinsX(); etaBin++) {
Double_t eta = centralDist->GetXaxis()->GetBinCenter(etaBin);
for (Int_t phiBin = 1; phiBin <= centralDist->GetNbinsX(); phiBin++) {
fdNdeta->Fill(eta,cent,centralDist->GetBinContent(etaBin,phiBin));
}
}
for (Int_t etaBin = 1; etaBin <= forwardDist->GetNbinsX(); etaBin++) {
Double_t eta = forwardDist->GetXaxis()->GetBinCenter(etaBin);
for (Int_t phiBin = 1; phiBin <= forwardDist->GetNbinsX(); phiBin++) {
fdNdeta->Fill(eta,cent,forwardDist->GetBinContent(etaBin,phiBin));
}
}
Double_t zvertex = fUtil.GetZ();
//if (fSettings.makeFakeHoles) fUtil.MakeFakeHoles(*forwardDist);
fCent->Fill(cent);
fVertex->Fill(zvertex);
if (fSettings.a5){
fCalculator.CumulantsAccumulate(forwardDist, fOutputList, cent, zvertex,kTRUE,true,false);
fCalculator.CumulantsAccumulate(centralDist, fOutputList, cent, zvertex,kFALSE,true,false);
}
else{
if (fSettings.ref_mode & fSettings.kFMDref) fCalculator.CumulantsAccumulate(refDist, fOutputList, cent, zvertex,kTRUE,true,false);
else fCalculator.CumulantsAccumulate(refDist, fOutputList, cent, zvertex,kFALSE,true,false);
}
fCalculator.CumulantsAccumulate(forwardDist, fOutputList, cent, zvertex,kTRUE,false,true);
fCalculator.CumulantsAccumulate(centralDist, fOutputList, cent, zvertex,kFALSE,false,true);
UInt_t randomInt = fRandom.Integer(fSettings.fnoSamples);
fCalculator.saveEvent(fOutputList, cent, zvertex, randomInt, 0);
fCalculator.reset();
centralDist->Reset();
forwardDist->Reset();
refDist->Reset();
PostData(1, fOutputList);
return;
}
//_____________________________________________________________________
void AliForwardFlowRun2Task::Terminate(Option_t */*option*/)
{
std::cout << "Terminating" << '\n';
return;
}
//_______________________________________________________________
<commit_msg>minor update<commit_after>
//
// Calculate flow in the forward and central regions using the Q cumulants method.
//
// Inputs:
// - AliAODEvent
//
// Outputs:
// - AnalysisResults.root or forward_flow.root
//
#include <iostream>
#include <TROOT.h>
#include <TSystem.h>
#include <TList.h>
#include <THn.h>
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliAODEvent.h"
#include "AliMCEvent.h"
#include "AliForwardFlowRun2Task.h"
#include "AliForwardQCumulantRun2.h"
#include "AliForwardGenericFramework.h"
#include "AliForwardFlowUtil.h"
using namespace std;
ClassImp(AliForwardFlowRun2Task)
#if 0
; // For emacs
#endif
//_____________________________________________________________________
AliForwardFlowRun2Task::AliForwardFlowRun2Task() : AliAnalysisTaskSE(),
fAOD(0), // input event
fOutputList(0), // output list
fAnalysisList(0),
fEventList(0),
fRandom(0),
centralDist(),
refDist(),
forwardDist(),
fSettings(),
fUtil(),
fCalculator()
{
//
// Default constructor
//
}
//_____________________________________________________________________
AliForwardFlowRun2Task::AliForwardFlowRun2Task(const char* name) : AliAnalysisTaskSE(name),
fAOD(0), // input event
fOutputList(0), // output list
fAnalysisList(0),
fEventList(0),
fRandom(0),
centralDist(),
refDist(),
forwardDist(),
fSettings(),
fUtil(),
fCalculator()
{
//
// Constructor
//
// Parameters:
// name: Name of task
//
// Rely on validation task for event and track selection
DefineInput(1, AliForwardTaskValidation::Class());
// DefineInput(2, TList::Class());
// DefineInput(3, TList::Class());
// DefineInput(4, TList::Class());
DefineOutput(1, TList::Class());
}
//_____________________________________________________________________
void AliForwardFlowRun2Task::UserCreateOutputObjects()
{
//
// Create output objects
//
//bool saveAutoAdd = TH1::AddDirectoryStatus();
fOutputList = new TList(); // the final output list
fOutputList->SetOwner(kTRUE); // memory stuff: the list is owner of all objects it contains and will delete them if requested
TRandom r = TRandom(); // random integer to use for creation of samples (used for error bars).
// Needs to be created here, otherwise it will draw the same random number.
fAnalysisList = new TList();
fEventList = new TList();
fAnalysisList ->SetName("Analysis");
fEventList ->SetName("EventInfo");
fCent = new TH1D("Centrality","Centrality",fSettings.fCentBins,0,60);
fEventList->Add(fCent);
fVertex = new TH1D("Vertex","Vertex",fSettings.fNZvtxBins,fSettings.fZVtxAcceptanceLowEdge,fSettings.fZVtxAcceptanceUpEdge);
fEventList->Add(fVertex);
fCent->SetDirectory(0);
fVertex->SetDirectory(0);
//fEventList->Add(new TH1D("FMDHits","FMDHits",100,0,10));
fdNdeta = new TH2D("dNdeta","dNdeta",200 /*fSettings.fNDiffEtaBins*/,fSettings.fEtaLowEdge,fSettings.fEtaUpEdge,fSettings.fCentBins,0,60);
fdNdeta->SetDirectory(0);
fEventList->Add(fdNdeta);
fAnalysisList->Add(new TList());
fAnalysisList->Add(new TList());
//fAnalysisList->Add(new TList());
static_cast<TList*>(fAnalysisList->At(0))->SetName("Reference");
static_cast<TList*>(fAnalysisList->At(1))->SetName("Differential");
//static_cast<TList*>(fAnalysisList->At(2))->SetName("AutoCorrection");
fOutputList->Add(fAnalysisList);
fOutputList->Add(fEventList);
// do analysis from v_2 to a maximum of v_5
Int_t fMaxMoment = 4;
Int_t dimensions = 5;
Int_t dbins[5] = {fSettings.fnoSamples, fSettings.fNZvtxBins, fSettings.fNDiffEtaBins, fSettings.fCentBins, static_cast<Int_t>(fSettings.kW4ThreeTwoB)+1} ;
Int_t rbins[5] = {fSettings.fnoSamples, fSettings.fNZvtxBins, fSettings.fNRefEtaBins, fSettings.fCentBins, static_cast<Int_t>(fSettings.kW4ThreeTwoB)+1} ;
Double_t xmin[5] = {0,fSettings.fZVtxAcceptanceLowEdge, fSettings.fEtaLowEdge, 0, 0};
Double_t xmax[5] = {10,fSettings.fZVtxAcceptanceUpEdge, fSettings.fEtaUpEdge, 60, static_cast<Double_t>(fSettings.kW4ThreeTwoB)+1};
//static_cast<TList*>(fAnalysisList->At(2))->Add(new THnF("fQcorrfactor", "fQcorrfactor", dimensions, rbins, xmin, xmax)); //(eta, n)
//static_cast<TList*>(fAnalysisList->At(2))->Add(new THnF("fpcorrfactor","fpcorrfactor", dimensions, dbins, xmin, xmax)); //(eta, n)
Int_t ptnmax = (fSettings.doPt ? 10 : 0);
// create a THn for each harmonic
for (Int_t n = 2; n <= fMaxMoment; n++) {
for (Int_t ptn = 0; ptn <= ptnmax; ptn++){
static_cast<TList*>(fAnalysisList->At(0))->Add(new THnD(Form("cumuRef_v%d_pt%d", n,ptn), Form("cumuRef_v%d_pt%d", n,ptn), dimensions, rbins, xmin, xmax));
static_cast<TList*>(fAnalysisList->At(1))->Add(new THnD(Form("cumuDiff_v%d_pt%d", n,ptn),Form("cumuDiff_v%d_pt%d", n,ptn), dimensions, dbins, xmin, xmax));
// The THn has dimensions [random samples, vertex position, eta, centrality, kind of variable to store]
// set names
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(0)->SetName("samples");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(1)->SetName("vertex");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(2)->SetName("eta");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(3)->SetName("cent");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(0))->FindObject(Form("cumuRef_v%d_pt%d", n,ptn)))->GetAxis(4)->SetName("identifier");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(0)->SetName("samples");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(1)->SetName("vertex");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(2)->SetName("eta");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(3)->SetName("cent");
static_cast<THnD*>(static_cast<TList*>(fAnalysisList->At(1))->FindObject(Form("cumuDiff_v%d_pt%d", n,ptn)))->GetAxis(4)->SetName("identifier");
}
}
// Make centralDist
Int_t centralEtaBins = (fSettings.useITS ? 200 : 400);
Int_t centralPhiBins = (fSettings.useITS ? 20 : 400);
Double_t centralEtaMin = (fSettings.useSPD ? -2.5 : fSettings.useITS ? -4 : -1.5);
Double_t centralEtaMax = (fSettings.useSPD ? 2.5 : fSettings.useITS ? 6 : 1.5);
// Make refDist
Int_t refEtaBins = (((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? 200 : 400);
Int_t refPhiBins = (((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? 20 : 400);
Double_t refEtaMin = ((fSettings.ref_mode & fSettings.kSPDref) ? -2.5
: ((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? -4
: -1.5);
Double_t refEtaMax = ((fSettings.ref_mode & fSettings.kSPDref) ? 2.5
: ((fSettings.ref_mode & fSettings.kITSref) | (fSettings.ref_mode & fSettings.kFMDref)) ? 6
: 1.5);
centralDist = new TH2D("c","",centralEtaBins,centralEtaMin,centralEtaMax,centralPhiBins,0,2*TMath::Pi());
centralDist ->SetDirectory(0);
refDist = new TH2D("r","",refEtaBins,refEtaMin,refEtaMax,refPhiBins,0,2*TMath::Pi());
refDist ->SetDirectory(0);
forwardDist = new TH2D("ft","",200,-4,6,20,0,TMath::TwoPi());
forwardDist ->SetDirectory(0);
PostData(1, fOutputList);
}
//_____________________________________________________________________
void AliForwardFlowRun2Task::UserExec(Option_t *)
{
//
// Analyses the event with use of the helper class AliForwardQCumulantRun2
//
// Parameters:
// option: Not used
//
fCalculator.fSettings = fSettings;
fUtil.fSettings = fSettings;
// Get the event validation object
AliForwardTaskValidation* ev_val = dynamic_cast<AliForwardTaskValidation*>(this->GetInputData(1));
if (!ev_val->IsValidEvent()){
PostData(1, this->fOutputList);
return;
}
if (!fSettings.esd){
AliAODEvent* aodevent = dynamic_cast<AliAODEvent*>(InputEvent());
fUtil.fAODevent = aodevent;
if(!aodevent) throw std::runtime_error("Not AOD as expected");
}
if (fSettings.mc) fUtil.fMCevent = this->MCEvent();
fUtil.fevent = fInputEvent;
Double_t cent = fUtil.GetCentrality(fSettings.centrality_estimator);
if (cent > 60.0){
//PostData(1, fOutputList);
return;
}
fUtil.FillData(refDist,centralDist,forwardDist);
// dNdeta
for (Int_t etaBin = 1; etaBin <= centralDist->GetNbinsX(); etaBin++) {
Double_t eta = centralDist->GetXaxis()->GetBinCenter(etaBin);
for (Int_t phiBin = 1; phiBin <= centralDist->GetNbinsX(); phiBin++) {
fdNdeta->Fill(eta,cent,centralDist->GetBinContent(etaBin,phiBin));
}
}
for (Int_t etaBin = 1; etaBin <= forwardDist->GetNbinsX(); etaBin++) {
Double_t eta = forwardDist->GetXaxis()->GetBinCenter(etaBin);
for (Int_t phiBin = 1; phiBin <= forwardDist->GetNbinsX(); phiBin++) {
fdNdeta->Fill(eta,cent,forwardDist->GetBinContent(etaBin,phiBin));
}
}
Double_t zvertex = fUtil.GetZ();
//if (fSettings.makeFakeHoles) fUtil.MakeFakeHoles(*forwardDist);
fCent->Fill(cent);
fVertex->Fill(zvertex);
if (fSettings.a5){
fCalculator.CumulantsAccumulate(forwardDist, fOutputList, cent, zvertex,kTRUE,true,false);
fCalculator.CumulantsAccumulate(centralDist, fOutputList, cent, zvertex,kFALSE,true,false);
}
else{
if (fSettings.ref_mode & fSettings.kFMDref) fCalculator.CumulantsAccumulate(refDist, fOutputList, cent, zvertex,kTRUE,true,false);
else fCalculator.CumulantsAccumulate(refDist, fOutputList, cent, zvertex,kFALSE,true,false);
}
fCalculator.CumulantsAccumulate(forwardDist, fOutputList, cent, zvertex,kTRUE,false,true);
fCalculator.CumulantsAccumulate(centralDist, fOutputList, cent, zvertex,kFALSE,false,true);
UInt_t randomInt = fRandom.Integer(fSettings.fnoSamples);
fCalculator.saveEvent(fOutputList, cent, zvertex, randomInt, 0);
fCalculator.reset();
centralDist->Reset();
forwardDist->Reset();
refDist->Reset();
PostData(1, fOutputList);
return;
}
//_____________________________________________________________________
void AliForwardFlowRun2Task::Terminate(Option_t */*option*/)
{
std::cout << "Terminating" << '\n';
return;
}
//_______________________________________________________________
<|endoftext|> |
<commit_before><commit_msg>unused include vector<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include "NexusPublisher.h"
/**
* Create an object responsible for the main business logic of the software. It
* manages reading data from the NeXus file and publishing it to the data
* stream.
*
* @param publisher - the publisher which provides methods to publish the data
* to a data stream
* @param brokerAddress - the IP or hostname of the broker for the data stream
* @param streamName - the name of the data stream, called the topic in the case
* of a Kafka publisher
* @param filename - the full path of a NeXus file
* @return - a NeXusPublisher object, call streamData() on it to start streaming
* data
*/
NexusPublisher::NexusPublisher(std::shared_ptr<EventPublisher> publisher,
const std::string &brokerAddress,
const std::string &streamName,
const std::string &filename,
const bool quietMode, const bool randomMode)
: m_publisher(publisher),
m_fileReader(std::make_shared<NexusFileReader>(filename)),
m_quietMode(quietMode), m_randomMode(randomMode) {
publisher->setUp(brokerAddress, streamName);
}
/**
* For a given frame number, reads the data from file and stores them in
* messagesPerFrame EventData objects
*
* @param frameNumber - the number of the frame for which to construct a message
* @return - an object containing the data from the specified frame
*/
std::vector<std::shared_ptr<EventData>>
NexusPublisher::createMessageData(hsize_t frameNumber,
const int messagesPerFrame) {
std::vector<std::shared_ptr<EventData>> eventDataVector;
std::vector<uint32_t> detIds;
m_fileReader->getEventDetIds(detIds, frameNumber);
std::vector<uint64_t> tofs;
m_fileReader->getEventTofs(tofs, frameNumber);
auto numberOfFrames = m_fileReader->getNumberOfFrames();
uint32_t eventsPerMessage =
static_cast<uint32_t>(ceil(static_cast<double>(detIds.size()) /
static_cast<double>(messagesPerFrame)));
for (int messageNumber = 0; messageNumber < messagesPerFrame;
messageNumber++) {
auto eventData = std::make_shared<EventData>();
auto upToDetId = detIds.begin() + ((messageNumber + 1) * eventsPerMessage);
auto upToTof = tofs.begin() + ((messageNumber + 1) * eventsPerMessage);
// The last message of the frame will contain any remaining events
if (messageNumber == (messagesPerFrame - 1)) {
upToDetId = detIds.end();
upToTof = tofs.end();
eventData->setEndFrame(true);
if (frameNumber == (numberOfFrames - 1)) {
eventData->setEndRun(true);
}
}
std::vector<uint32_t> detIdsCurrentMessage(
detIds.begin() + (messageNumber * eventsPerMessage), upToDetId);
std::vector<uint64_t> tofsCurrentMessage(
tofs.begin() + (messageNumber * eventsPerMessage), upToTof);
eventData->setDetId(detIdsCurrentMessage);
eventData->setTof(tofsCurrentMessage);
eventData->setNumberOfFrames(
static_cast<uint32_t>(m_fileReader->getNumberOfFrames()));
eventData->setFrameNumber(static_cast<uint32_t>(frameNumber));
eventData->setTotalCounts(m_fileReader->getTotalEventCount());
eventDataVector.push_back(eventData);
}
return eventDataVector;
}
/**
* Start streaming all the data from the file
*/
void NexusPublisher::streamData(const int maxEventsPerFramePart) {
std::string rawbuf;
// frame numbers run from 0 to numberOfFrames-1
reportProgress(0.0);
int64_t totalBytesSent = 0;
const auto numberOfFrames = m_fileReader->getNumberOfFrames();
auto framePartsPerFrame =
m_fileReader->getFramePartsPerFrame(maxEventsPerFramePart);
for (size_t frameNumber = 0; frameNumber < numberOfFrames; frameNumber++) {
totalBytesSent +=
createAndSendMessage(rawbuf, frameNumber, framePartsPerFrame[frameNumber]);
reportProgress(static_cast<float>(frameNumber) /
static_cast<float>(numberOfFrames));
}
reportProgress(1.0);
std::cout << std::endl
<< "Frames sent: " << m_fileReader->getNumberOfFrames() << std::endl
<< "Bytes sent: " << totalBytesSent << std::endl;
}
/**
* Using Google Flatbuffers, create a message for the specifed frame and store
* it in the provided buffer
*
* @param rawbuf - a buffer for the message
* @param frameNumber - the number of the frame for which data will be sent
*/
int64_t NexusPublisher::createAndSendMessage(std::string &rawbuf,
size_t frameNumber,
const int messagesPerFrame) {
auto messageData = createMessageData(frameNumber, messagesPerFrame);
std::vector<int> indexes;
indexes.reserve(messageData.size());
for (int i = 0; i < messageData.size(); ++i)
indexes.push_back(i);
if (m_randomMode && indexes.size() > 1) {
std::random_shuffle(indexes.begin()+1, indexes.end());
}
int64_t dataSize = 0;
for (const auto &index : indexes) {
auto buffer_uptr =
messageData[index]->getBufferPointer(rawbuf, m_messageID + index);
m_publisher->sendMessage(reinterpret_cast<char *>(buffer_uptr.get()),
messageData[index]->getBufferSize());
dataSize += rawbuf.size();
}
m_messageID += indexes.size();
return dataSize;
}
/**
* Display a progress bar
*
* @param progress - progress between 0 (starting) and 1 (complete)
*/
void NexusPublisher::reportProgress(const float progress) {
if (!m_quietMode) {
const int barWidth = 70;
std::cout << "[";
auto pos = static_cast<int>(barWidth * progress);
for (int i = 0; i < barWidth; ++i) {
if (i < pos)
std::cout << "=";
else if (i == pos)
std::cout << ">";
else
std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << " %\r";
std::cout.flush();
}
}
<commit_msg>Re #15 correct ceil in std namespace<commit_after>#include <iostream>
#include "NexusPublisher.h"
/**
* Create an object responsible for the main business logic of the software. It
* manages reading data from the NeXus file and publishing it to the data
* stream.
*
* @param publisher - the publisher which provides methods to publish the data
* to a data stream
* @param brokerAddress - the IP or hostname of the broker for the data stream
* @param streamName - the name of the data stream, called the topic in the case
* of a Kafka publisher
* @param filename - the full path of a NeXus file
* @return - a NeXusPublisher object, call streamData() on it to start streaming
* data
*/
NexusPublisher::NexusPublisher(std::shared_ptr<EventPublisher> publisher,
const std::string &brokerAddress,
const std::string &streamName,
const std::string &filename,
const bool quietMode, const bool randomMode)
: m_publisher(publisher),
m_fileReader(std::make_shared<NexusFileReader>(filename)),
m_quietMode(quietMode), m_randomMode(randomMode) {
publisher->setUp(brokerAddress, streamName);
}
/**
* For a given frame number, reads the data from file and stores them in
* messagesPerFrame EventData objects
*
* @param frameNumber - the number of the frame for which to construct a message
* @return - an object containing the data from the specified frame
*/
std::vector<std::shared_ptr<EventData>>
NexusPublisher::createMessageData(hsize_t frameNumber,
const int messagesPerFrame) {
std::vector<std::shared_ptr<EventData>> eventDataVector;
std::vector<uint32_t> detIds;
m_fileReader->getEventDetIds(detIds, frameNumber);
std::vector<uint64_t> tofs;
m_fileReader->getEventTofs(tofs, frameNumber);
auto numberOfFrames = m_fileReader->getNumberOfFrames();
uint32_t eventsPerMessage =
static_cast<uint32_t>(std::ceil(static_cast<double>(detIds.size()) /
static_cast<double>(messagesPerFrame)));
for (int messageNumber = 0; messageNumber < messagesPerFrame;
messageNumber++) {
auto eventData = std::make_shared<EventData>();
auto upToDetId = detIds.begin() + ((messageNumber + 1) * eventsPerMessage);
auto upToTof = tofs.begin() + ((messageNumber + 1) * eventsPerMessage);
// The last message of the frame will contain any remaining events
if (messageNumber == (messagesPerFrame - 1)) {
upToDetId = detIds.end();
upToTof = tofs.end();
eventData->setEndFrame(true);
if (frameNumber == (numberOfFrames - 1)) {
eventData->setEndRun(true);
}
}
std::vector<uint32_t> detIdsCurrentMessage(
detIds.begin() + (messageNumber * eventsPerMessage), upToDetId);
std::vector<uint64_t> tofsCurrentMessage(
tofs.begin() + (messageNumber * eventsPerMessage), upToTof);
eventData->setDetId(detIdsCurrentMessage);
eventData->setTof(tofsCurrentMessage);
eventData->setNumberOfFrames(
static_cast<uint32_t>(m_fileReader->getNumberOfFrames()));
eventData->setFrameNumber(static_cast<uint32_t>(frameNumber));
eventData->setTotalCounts(m_fileReader->getTotalEventCount());
eventDataVector.push_back(eventData);
}
return eventDataVector;
}
/**
* Start streaming all the data from the file
*/
void NexusPublisher::streamData(const int maxEventsPerFramePart) {
std::string rawbuf;
// frame numbers run from 0 to numberOfFrames-1
reportProgress(0.0);
int64_t totalBytesSent = 0;
const auto numberOfFrames = m_fileReader->getNumberOfFrames();
auto framePartsPerFrame =
m_fileReader->getFramePartsPerFrame(maxEventsPerFramePart);
for (size_t frameNumber = 0; frameNumber < numberOfFrames; frameNumber++) {
totalBytesSent +=
createAndSendMessage(rawbuf, frameNumber, framePartsPerFrame[frameNumber]);
reportProgress(static_cast<float>(frameNumber) /
static_cast<float>(numberOfFrames));
}
reportProgress(1.0);
std::cout << std::endl
<< "Frames sent: " << m_fileReader->getNumberOfFrames() << std::endl
<< "Bytes sent: " << totalBytesSent << std::endl;
}
/**
* Using Google Flatbuffers, create a message for the specifed frame and store
* it in the provided buffer
*
* @param rawbuf - a buffer for the message
* @param frameNumber - the number of the frame for which data will be sent
*/
int64_t NexusPublisher::createAndSendMessage(std::string &rawbuf,
size_t frameNumber,
const int messagesPerFrame) {
auto messageData = createMessageData(frameNumber, messagesPerFrame);
std::vector<int> indexes;
indexes.reserve(messageData.size());
for (int i = 0; i < messageData.size(); ++i)
indexes.push_back(i);
if (m_randomMode && indexes.size() > 1) {
std::random_shuffle(indexes.begin()+1, indexes.end());
}
int64_t dataSize = 0;
for (const auto &index : indexes) {
auto buffer_uptr =
messageData[index]->getBufferPointer(rawbuf, m_messageID + index);
m_publisher->sendMessage(reinterpret_cast<char *>(buffer_uptr.get()),
messageData[index]->getBufferSize());
dataSize += rawbuf.size();
}
m_messageID += indexes.size();
return dataSize;
}
/**
* Display a progress bar
*
* @param progress - progress between 0 (starting) and 1 (complete)
*/
void NexusPublisher::reportProgress(const float progress) {
if (!m_quietMode) {
const int barWidth = 70;
std::cout << "[";
auto pos = static_cast<int>(barWidth * progress);
for (int i = 0; i < barWidth; ++i) {
if (i < pos)
std::cout << "=";
else if (i == pos)
std::cout << ">";
else
std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << " %\r";
std::cout.flush();
}
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include <algorithm>
#include <climits>
#include <numeric>
#include <tuple>
#include <vector>
#include SPECIFIC_HEADER
// Running tests
TEST(TEST_NAME, InputItSelf)
{
auto expected = std::make_tuple(-2, 1, 1);
auto&& out = sum3({{ 1, -2, 1 }});
ASSERT_EQ(1, out.size());
ASSERT_TRUE(expected == out[0]);
}
TEST(TEST_NAME, OverflowReachingZeroIsInvalid)
{
int b = -1097024319;
int a = -b -b;
ASSERT_TRUE(a < 0);
auto&& out = sum3({{ b, b, a }});
ASSERT_TRUE(out.size() == 0);
}
TEST(TEST_NAME, MultipleTriplets)
{
std::vector<std::tuple<int,int,int>> expected = { std::tuple<int,int,int>{-1, 0, 1}, std::tuple<int,int,int>{-1, -1, 2} };
auto&& out = sum3({{ -1, 0, 1, 2, -1, -4 }});
ASSERT_EQ(2, out.size());
ASSERT_TRUE(out[0] != out[1]);
ASSERT_TRUE(expected[0] == out[0] || expected[0] == out[1]);
ASSERT_TRUE(expected[1] == out[0] || expected[1] == out[1]);
}
RC_GTEST_PROP(TEST_NAME, SumToZero, (std::vector<int> const& in))
{
RC_PRE(in.size() >= 3);
auto&& out = sum3(in);
RC_ASSERT(std::find_if_not(std::begin(out), std::end(out)
, [](auto t) { return std::get<0>(t) + std::get<1>(t) + std::get<2>(t) == 0;
}) == std::end(out));
}
RC_GTEST_PROP(TEST_NAME, Ordered, (std::vector<int> const& in))
{
RC_PRE(in.size() >= 3);
auto&& out = sum3(in);
RC_ASSERT(std::find_if_not(std::begin(out), std::end(out)
, [](auto t) { return std::get<0>(t) <= std::get<1>(t) && std::get<1>(t) <= std::get<2>(t);
}) == std::end(out));
}
RC_GTEST_PROP(TEST_NAME, Unicity, (std::vector<int> const& in))
{
RC_PRE(in.size() >= 3);
auto&& out = sum3(in);
std::sort(std::begin(out), std::end(out));
RC_ASSERT(std::unique(std::begin(out), std::end(out)) == std::end(out));
}
RC_GTEST_PROP(TEST_NAME, ComeFromInput, (std::vector<int> const& in))
{
RC_PRE(in.size() >= 3);
auto&& out = sum3(in);
auto sin = in;
std::sort(std::begin(sin), std::end(sin));
RC_ASSERT(std::find_if_not(std::begin(out), std::end(out)
, [&sin](auto t) {
auto it = std::find(std::begin(sin), std::end(sin), std::get<0>(t));
it = std::find(it, std::end(sin), std::get<1>(t));
return std::find(std::begin(sin), std::end(sin), std::get<2>(t)) != std::end(sin);
}) == std::end(out));
}
bool same_sign(int a, int b)
{
return (a < 0 && b < 0) || (a > 0 && b > 0);
}
RC_GTEST_PROP(TEST_NAME, FindAnswerWhenItExist, (std::vector<int> in, int a, int b))
{
int c = -a -b;
RC_PRE((a == 0 && b == 0 && c == 0) || !same_sign(a,b) || !same_sign(b,c) || !same_sign(c,a));
int tab[] = {a, b ,c};
std::sort(tab, tab+3);
auto possible_answer = std::make_tuple(tab[0], tab[1], tab[2]);
std::size_t pa = *rc::gen::inRange(std::size_t(), in.size());
in.insert(std::next(std::begin(in), pa), a);
std::size_t pb = *rc::gen::inRange(std::size_t(), in.size());
in.insert(std::next(std::begin(in), pb), b);
std::size_t pc = *rc::gen::inRange(std::size_t(), in.size());
in.insert(std::next(std::begin(in), pc), c);
auto&& out = sum3(in);
RC_ASSERT(out.size());
RC_ASSERT(std::find(std::begin(out), std::end(out), possible_answer) != std::end(out));
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
int ret { RUN_ALL_TESTS() };
return ret;
}
<commit_msg>[triplet-suming-to-zero][vs] Fix compile unsigned compared to int<commit_after>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include <algorithm>
#include <climits>
#include <numeric>
#include <tuple>
#include <vector>
#include SPECIFIC_HEADER
// Running tests
TEST(TEST_NAME, InputItSelf)
{
auto expected = std::make_tuple(-2, 1, 1);
auto&& out = sum3({{ 1, -2, 1 }});
ASSERT_EQ(1, out.size());
ASSERT_TRUE(expected == out[0]);
}
TEST(TEST_NAME, OverflowReachingZeroIsInvalid)
{
int b = -1097024319;
int a = -b -b;
ASSERT_TRUE(a < 0);
auto&& out = sum3({{ b, b, a }});
ASSERT_TRUE(out.size() == 0);
}
TEST(TEST_NAME, MultipleTriplets)
{
std::vector<std::tuple<int,int,int>> expected = { std::tuple<int,int,int>{-1, 0, 1}, std::tuple<int,int,int>{-1, -1, 2} };
auto&& out = sum3({{ -1, 0, 1, 2, -1, -4 }});
ASSERT_EQ(2, out.size());
ASSERT_TRUE(out[0] != out[1]);
ASSERT_TRUE(expected[0] == out[0] || expected[0] == out[1]);
ASSERT_TRUE(expected[1] == out[0] || expected[1] == out[1]);
}
RC_GTEST_PROP(TEST_NAME, SumToZero, (std::vector<int> const& in))
{
RC_PRE(in.size() >= 3);
auto&& out = sum3(in);
RC_ASSERT(std::find_if_not(std::begin(out), std::end(out)
, [](auto t) { return std::get<0>(t) + std::get<1>(t) + std::get<2>(t) == 0;
}) == std::end(out));
}
RC_GTEST_PROP(TEST_NAME, Ordered, (std::vector<int> const& in))
{
RC_PRE(in.size() >= unsigned(3));
auto&& out = sum3(in);
RC_ASSERT(std::find_if_not(std::begin(out), std::end(out)
, [](auto t) { return std::get<0>(t) <= std::get<1>(t) && std::get<1>(t) <= std::get<2>(t);
}) == std::end(out));
}
RC_GTEST_PROP(TEST_NAME, Unicity, (std::vector<int> const& in))
{
RC_PRE(in.size() >= unsigned(3));
auto&& out = sum3(in);
std::sort(std::begin(out), std::end(out));
RC_ASSERT(std::unique(std::begin(out), std::end(out)) == std::end(out));
}
RC_GTEST_PROP(TEST_NAME, ComeFromInput, (std::vector<int> const& in))
{
RC_PRE(in.size() >= unsigned(3));
auto&& out = sum3(in);
auto sin = in;
std::sort(std::begin(sin), std::end(sin));
RC_ASSERT(std::find_if_not(std::begin(out), std::end(out)
, [&sin](auto t) {
auto it = std::find(std::begin(sin), std::end(sin), std::get<0>(t));
it = std::find(it, std::end(sin), std::get<1>(t));
return std::find(std::begin(sin), std::end(sin), std::get<2>(t)) != std::end(sin);
}) == std::end(out));
}
bool same_sign(int a, int b)
{
return (a < 0 && b < 0) || (a > 0 && b > 0);
}
RC_GTEST_PROP(TEST_NAME, FindAnswerWhenItExist, (std::vector<int> in, int a, int b))
{
int c = -a -b;
RC_PRE((a == 0 && b == 0 && c == 0) || !same_sign(a,b) || !same_sign(b,c) || !same_sign(c,a));
int tab[] = {a, b ,c};
std::sort(tab, tab+3);
auto possible_answer = std::make_tuple(tab[0], tab[1], tab[2]);
std::size_t pa = *rc::gen::inRange(std::size_t(), in.size());
in.insert(std::next(std::begin(in), pa), a);
std::size_t pb = *rc::gen::inRange(std::size_t(), in.size());
in.insert(std::next(std::begin(in), pb), b);
std::size_t pc = *rc::gen::inRange(std::size_t(), in.size());
in.insert(std::next(std::begin(in), pc), c);
auto&& out = sum3(in);
RC_ASSERT(out.size());
RC_ASSERT(std::find(std::begin(out), std::end(out), possible_answer) != std::end(out));
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
int ret { RUN_ALL_TESTS() };
return ret;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTkAppInit.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* tkAppInit.c --
*
* Provides a default version of the Tcl_AppInit procedure for
* use in wish and similar Tk-based applications.
*
* Copyright (c) 1993 The Regents of the University of California.
* Copyright (c) 1994 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#ifdef VTK_COMPILED_USING_MPI
# include <mpi.h>
# include "vtkMPIController.h"
#endif // VTK_COMPILED_USING_MPI
#include "vtkSystemIncludes.h"
#include "vtkToolkits.h"
#include "Wrapping/Tcl/vtkTkAppInitConfigure.h"
#if defined(CMAKE_INTDIR)
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR
#else
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD
#endif
#ifdef VTK_USE_RENDERING
# include "vtkTk.h"
#else
# include "vtkTcl.h"
#endif
/*
* Make sure all the kits register their classes with vtkInstantiator.
*/
#include "vtkCommonInstantiator.h"
#include "vtkFilteringInstantiator.h"
#include "vtkIOInstantiator.h"
#include "vtkImagingInstantiator.h"
#include "vtkGraphicsInstantiator.h"
#ifdef VTK_USE_RENDERING
#include "vtkRenderingInstantiator.h"
#endif
#ifdef VTK_USE_PATENTED
#include "vtkPatentedInstantiator.h"
#endif
#ifdef VTK_USE_HYBRID
#include "vtkHybridInstantiator.h"
#endif
#ifdef VTK_USE_PARALLEL
#include "vtkParallelInstantiator.h"
#endif
static void vtkTkAppInitEnableMSVCDebugHook();
/*
*----------------------------------------------------------------------
*
* main --
*
* This is the main program for the application.
*
* Results:
* None: Tk_Main never returns here, so this procedure never
* returns either.
*
* Side effects:
* Whatever the application does.
*
*----------------------------------------------------------------------
*/
#ifdef VTK_COMPILED_USING_MPI
class vtkMPICleanup {
public:
vtkMPICleanup()
{
this->Controller = 0;
}
void Initialize(int *argc, char ***argv)
{
MPI_Init(argc, argv);
this->Controller = vtkMPIController::New();
this->Controller->Initialize(argc, argv, 1);
vtkMultiProcessController::SetGlobalController(this->Controller);
}
~vtkMPICleanup()
{
if ( this->Controller )
{
this->Controller->Finalize();
this->Controller->Delete();
}
}
private:
vtkMPIController *Controller;
};
static vtkMPICleanup VTKMPICleanup;
#endif // VTK_COMPILED_USING_MPI
int
main(int argc, char **argv)
{
ios::sync_with_stdio();
vtkTkAppInitEnableMSVCDebugHook();
#ifdef VTK_COMPILED_USING_MPI
VTKMPICleanup.Initialize(&argc, &argv);
#endif // VTK_COMPILED_USING_MPI
#ifdef VTK_USE_RENDERING
Tk_Main(argc, argv, Tcl_AppInit);
#else
Tcl_Main(argc, argv, Tcl_AppInit);
#endif
return 0; /* Needed only to prevent compiler warning. */
}
/*
*----------------------------------------------------------------------
*
* Tcl_AppInit --
*
* This procedure performs application-specific initialization.
* Most applications, especially those that incorporate additional
* packages, will have their own version of this procedure.
*
* Results:
* Returns a standard Tcl completion code, and leaves an error
* message in interp->result if an error occurs.
*
* Side effects:
* Depends on the startup script.
*
*----------------------------------------------------------------------
*/
extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp);
extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp);
extern "C" int Vtkiotcl_Init(Tcl_Interp *interp);
#ifdef VTK_USE_RENDERING
extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp);
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp);
extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp);
#endif
#endif
#ifdef VTK_USE_PATENTED
extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_HYBRID
extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_PARALLEL
extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp);
#endif
void help() {
}
int Tcl_AppInit(Tcl_Interp *interp)
{
#ifdef __CYGWIN__
Tcl_SetVar(interp, "tclDefaultLibrary", "/usr/share/tcl" TCL_VERSION, TCL_GLOBAL_ONLY);
#endif
if (Tcl_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Tk_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#endif
/* init the core vtk stuff */
if (Vtkcommontcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkfilteringtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkimagingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkgraphicstcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkiotcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Vtkrenderingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
// Need to init here because rendering did not when this option is on
if (Vtktkrenderwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#endif
#ifdef VTK_USE_PATENTED
if (Vtkpatentedtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_HYBRID
if (Vtkhybridtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_PARALLEL
if (Vtkparalleltcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
/*
* Append path to VTK packages to auto_path
*/
static char script[] =
"foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}"
" [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]"
" [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]"
" ] {\n"
" if {[file isdirectory $dir]} {\n"
" lappend auto_path $dir\n"
" }\n"
"}\n"
"rename package package.orig\n"
"proc package {args} {\n"
" if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n"
" global errorInfo env\n"
" if {[lindex $args 0] == \"require\"} {\n"
" set expecting {can\'t find package vtk}\n"
" if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n"
" set msg {The Tcl interpreter was probably not able to find the"
" VTK packages. Please check that your TCLLIBPATH environment variable"
" includes the path to your VTK Tcl directory. You might find it under"
" your VTK binary directory in Wrapping/Tcl, or under your"
" site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n"
" if {[info exists env(TCLLIBPATH)]} {\n"
" append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n"
" }\n"
" set errorInfo \"$msg The TCLLIBPATH variable is a set of"
" space separated paths (hence, path containing spaces should be"
" surrounded by quotes first). Windows users should use forward"
" (Unix-style) slashes \'/\' instead of the usual backward slashes. "
" More informations can be found in the Wrapping/Tcl/README source"
" file (also available online at"
" http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n"
"$errorInfo\"\n"
" }\n"
" }\n"
" error $catch_res $errorInfo\n"
" }\n"
" return $package_res\n"
"}\n";
Tcl_Eval(interp, script);
/*
* Specify a user-specific startup file to invoke if the application
* is run interactively. Typically the startup file is "~/.apprc"
* where "app" is the name of the application. If this line is deleted
* then no user-specific startup file will be run under any conditions.
*/
Tcl_SetVar(interp,
(char *) "tcl_rcFileName",
(char *) "~/.vtkrc",
TCL_GLOBAL_ONLY);
return TCL_OK;
}
// For a DEBUG build on MSVC, add a hook to prevent error dialogs when
// being run from DART.
#if defined(_MSC_VER) && defined(_DEBUG)
# include <crtdbg.h>
static int vtkTkAppInitDebugReport(int, char* message, int*)
{
fprintf(stderr, message);
exit(1);
return 0;
}
void vtkTkAppInitEnableMSVCDebugHook()
{
if(getenv("DART_TEST_FROM_DART"))
{
_CrtSetReportHook(vtkTkAppInitDebugReport);
}
}
#else
void vtkTkAppInitEnableMSVCDebugHook()
{
}
#endif
<commit_msg>fix warning<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTkAppInit.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* tkAppInit.c --
*
* Provides a default version of the Tcl_AppInit procedure for
* use in wish and similar Tk-based applications.
*
* Copyright (c) 1993 The Regents of the University of California.
* Copyright (c) 1994 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#ifdef VTK_COMPILED_USING_MPI
# include <mpi.h>
# include "vtkMPIController.h"
#endif // VTK_COMPILED_USING_MPI
#include "vtkSystemIncludes.h"
#include "vtkToolkits.h"
#include "Wrapping/Tcl/vtkTkAppInitConfigure.h"
#if defined(CMAKE_INTDIR)
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR
#else
# define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD
#endif
#ifdef VTK_USE_RENDERING
# include "vtkTk.h"
#else
# include "vtkTcl.h"
#endif
/*
* Make sure all the kits register their classes with vtkInstantiator.
*/
#include "vtkCommonInstantiator.h"
#include "vtkFilteringInstantiator.h"
#include "vtkIOInstantiator.h"
#include "vtkImagingInstantiator.h"
#include "vtkGraphicsInstantiator.h"
#ifdef VTK_USE_RENDERING
#include "vtkRenderingInstantiator.h"
#endif
#ifdef VTK_USE_PATENTED
#include "vtkPatentedInstantiator.h"
#endif
#ifdef VTK_USE_HYBRID
#include "vtkHybridInstantiator.h"
#endif
#ifdef VTK_USE_PARALLEL
#include "vtkParallelInstantiator.h"
#endif
static void vtkTkAppInitEnableMSVCDebugHook();
/*
*----------------------------------------------------------------------
*
* main --
*
* This is the main program for the application.
*
* Results:
* None: Tk_Main never returns here, so this procedure never
* returns either.
*
* Side effects:
* Whatever the application does.
*
*----------------------------------------------------------------------
*/
#ifdef VTK_COMPILED_USING_MPI
class vtkMPICleanup {
public:
vtkMPICleanup()
{
this->Controller = 0;
}
void Initialize(int *argc, char ***argv)
{
MPI_Init(argc, argv);
this->Controller = vtkMPIController::New();
this->Controller->Initialize(argc, argv, 1);
vtkMultiProcessController::SetGlobalController(this->Controller);
}
~vtkMPICleanup()
{
if ( this->Controller )
{
this->Controller->Finalize();
this->Controller->Delete();
}
}
private:
vtkMPIController *Controller;
};
static vtkMPICleanup VTKMPICleanup;
#endif // VTK_COMPILED_USING_MPI
int
main(int argc, char **argv)
{
ios::sync_with_stdio();
vtkTkAppInitEnableMSVCDebugHook();
#ifdef VTK_COMPILED_USING_MPI
VTKMPICleanup.Initialize(&argc, &argv);
#endif // VTK_COMPILED_USING_MPI
#ifdef VTK_USE_RENDERING
Tk_Main(argc, argv, Tcl_AppInit);
#else
Tcl_Main(argc, argv, Tcl_AppInit);
#endif
return 0; /* Needed only to prevent compiler warning. */
}
/*
*----------------------------------------------------------------------
*
* Tcl_AppInit --
*
* This procedure performs application-specific initialization.
* Most applications, especially those that incorporate additional
* packages, will have their own version of this procedure.
*
* Results:
* Returns a standard Tcl completion code, and leaves an error
* message in interp->result if an error occurs.
*
* Side effects:
* Depends on the startup script.
*
*----------------------------------------------------------------------
*/
extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp);
extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp);
extern "C" int Vtkiotcl_Init(Tcl_Interp *interp);
#ifdef VTK_USE_RENDERING
extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp);
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp);
extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp);
#endif
#endif
#ifdef VTK_USE_PATENTED
extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_HYBRID
extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp);
#endif
#ifdef VTK_USE_PARALLEL
extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp);
#endif
void help() {
}
int Tcl_AppInit(Tcl_Interp *interp)
{
#ifdef __CYGWIN__
Tcl_SetVar(interp, "tclDefaultLibrary", "/usr/share/tcl" TCL_VERSION, TCL_GLOBAL_ONLY);
#endif
if (Tcl_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Tk_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#endif
/* init the core vtk stuff */
if (Vtkcommontcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkfilteringtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkimagingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkgraphicstcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtkiotcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#ifdef VTK_USE_RENDERING
if (Vtkrenderingtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA)
// Need to init here because rendering did not when this option is on
if (Vtktkrenderwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#endif
#ifdef VTK_USE_PATENTED
if (Vtkpatentedtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_HYBRID
if (Vtkhybridtcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
#ifdef VTK_USE_PARALLEL
if (Vtkparalleltcl_Init(interp) == TCL_ERROR)
{
return TCL_ERROR;
}
#endif
/*
* Append path to VTK packages to auto_path
*/
static char script[] =
"foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}"
" [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]"
" [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]"
" ] {\n"
" if {[file isdirectory $dir]} {\n"
" lappend auto_path $dir\n"
" }\n"
"}\n"
"rename package package.orig\n"
"proc package {args} {\n"
" if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n"
" global errorInfo env\n"
" if {[lindex $args 0] == \"require\"} {\n"
" set expecting {can\'t find package vtk}\n"
" if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n"
" set msg {The Tcl interpreter was probably not able to find the"
" VTK packages. Please check that your TCLLIBPATH environment variable"
" includes the path to your VTK Tcl directory. You might find it under"
" your VTK binary directory in Wrapping/Tcl, or under your"
" site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n"
" if {[info exists env(TCLLIBPATH)]} {\n"
" append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n"
" }\n"
" set errorInfo \"$msg The TCLLIBPATH variable is a set of"
" space separated paths (hence, path containing spaces should be"
" surrounded by quotes first). Windows users should use forward"
" (Unix-style) slashes \'/\' instead of the usual backward slashes. "
" More informations can be found in the Wrapping/Tcl/README source"
" file (also available online at"
" http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n"
"$errorInfo\"\n"
" }\n"
" }\n"
" error $catch_res $errorInfo\n"
" }\n"
" return $package_res\n"
"}\n";
Tcl_Eval(interp, script);
/*
* Specify a user-specific startup file to invoke if the application
* is run interactively. Typically the startup file is "~/.apprc"
* where "app" is the name of the application. If this line is deleted
* then no user-specific startup file will be run under any conditions.
*/
Tcl_SetVar(interp,
(char *) "tcl_rcFileName",
(char *) "~/.vtkrc",
TCL_GLOBAL_ONLY);
return TCL_OK;
}
// For a DEBUG build on MSVC, add a hook to prevent error dialogs when
// being run from DART.
#if defined(_MSC_VER) && defined(_DEBUG)
# include <crtdbg.h>
static int vtkTkAppInitDebugReport(int, char* message, int*)
{
fprintf(stderr, message);
exit(1);
}
void vtkTkAppInitEnableMSVCDebugHook()
{
if(getenv("DART_TEST_FROM_DART"))
{
_CrtSetReportHook(vtkTkAppInitDebugReport);
}
}
#else
void vtkTkAppInitEnableMSVCDebugHook()
{
}
#endif
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
int main(int argc, char **argv)
{
init_shogun(&print_message, &print_message, &print_message);
SGVector<float64_t> data(10);
CMath::range_fill_vector(data.vector, data.vlen, 1.0);
float64_t low, up, mean;
float64_t error_prob=0.05;
mean=CStatistics::confidence_intervals_mean(data, error_prob, low, up);
SG_SPRINT("sample mean: %f. True mean lies in [%f,%f] with %f%%\n",
mean, low, up, 100*(1-error_prob));
SG_SPRINT("\nEND\n");
exit_shogun();
return 0;
}
<commit_msg>fixed mem-leak<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
int main(int argc, char **argv)
{
init_shogun(&print_message, &print_message, &print_message);
SGVector<float64_t> data(10, true);
CMath::range_fill_vector(data.vector, data.vlen, 1.0);
float64_t low, up, mean;
float64_t error_prob=0.05;
mean=CStatistics::confidence_intervals_mean(data, error_prob, low, up);
SG_SPRINT("sample mean: %f. True mean lies in [%f,%f] with %f%%\n",
mean, low, up, 100*(1-error_prob));
data.free_vector();
SG_SPRINT("\nEND\n");
exit_shogun();
return 0;
}
<|endoftext|> |
<commit_before>#include "MainLogic.h"
#include "MotorDriver.h"
#include "DualEncoderDriver.h"
#include "FrontLiftedDetection.h"
#include "ProximitySensors.h"
#include <cmath>
#define STANDARD_SPEED 170
#define SPEED_CHANGE_STEP 1
#define DISTANCE_BETWEEN_MOTORS 85.00
#define HALF_DISTANCE_BETWEEN_MOTORS (DISTANCE_BETWEEN_MOTORS / 2.00)
#define SAMPLE_FREQUENCY 250
enum {
SEARCH_INITIAL,
SEARCH_TURNING,
SEARCH_FORWARD,
FOUND_LEFT,
FOUND_RIGHT,
FOUND_STRAIGHT,
STOP_MOVING
} STATE = SEARCH_INITIAL;
enum {
MOVEMENT_SYSTEM_STATUS_OFF,
MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT,
MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT
} movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
template<typename T> inline void swap(T& a, T& b) { T c = a; a = b; b = c; }
static float distanceExpectedByLeftTire, distanceExpectedByRightTire;
static int16_t leftMotorSpeed, rightMotorSpeed, leftMotorDir, rightMotorDir;
static int8_t directionOfLinearMovement;
static float circleMotorSpeedDifference;
void HandleControlledMovement()
{
switch(movementSystemStatus)
{
case MOVEMENT_SYSTEM_STATUS_OFF:
// stop the motors, they should not be moving
setMotors(0, 0);
break;
case MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT:
{
float leftTyreSpeed = (float)leftEncoder.getSpeed();
float rightTyreSpeed = (float)rightEncoder.getSpeed();
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTyreSpeed > rightTyreSpeed)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
}
else if(leftTyreSpeed < rightTyreSpeed)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= (float)(leftTyreSpeed / SAMPLE_FREQUENCY);
distanceExpectedByRightTire -= (float)(rightTyreSpeed / SAMPLE_FREQUENCY);
if( (distanceExpectedByLeftTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByLeftTire > 0 && directionOfLinearMovement < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByRightTire > 0 && directionOfLinearMovement < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
case MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT:
{
float leftTyreSpeed = leftEncoder.getSpeed();
float rightTyreSpeed = rightEncoder.getSpeed();
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTyreSpeed / rightTyreSpeed > circleMotorSpeedDifference)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
rightMotorSpeed += SPEED_CHANGE_STEP;
}
else if(leftTyreSpeed / rightTyreSpeed < circleMotorSpeedDifference)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
rightMotorSpeed -= SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= leftTyreSpeed / SAMPLE_FREQUENCY;
distanceExpectedByRightTire -= rightTyreSpeed / SAMPLE_FREQUENCY;
if( (distanceExpectedByLeftTire < 0 && leftMotorDir > 0) ||
(distanceExpectedByLeftTire > 0 && leftMotorDir < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && rightMotorDir > 0) ||
(distanceExpectedByRightTire > 0 && rightMotorDir < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
}
}
inline bool IsMovementComplete()
{
return movementSystemStatus == MOVEMENT_SYSTEM_STATUS_OFF;
}
void LinearMovement(int32_t distanceInMMWithDirection) // TODO: Fix backwards
{
// evaluate direction and pass to drivers the start state
if(0 < distanceInMMWithDirection)
{
directionOfLinearMovement = 1;
setMotors(STANDARD_SPEED, STANDARD_SPEED);
}
else
{
directionOfLinearMovement = -1;
setMotors(-STANDARD_SPEED, -STANDARD_SPEED);
}
// set setpoints for end of movement, used in handler
distanceExpectedByRightTire = (float)distanceInMMWithDirection;
distanceExpectedByLeftTire = (float)distanceInMMWithDirection;
// set motor speeds, used in handler
rightMotorSpeed = STANDARD_SPEED;
leftMotorSpeed = STANDARD_SPEED;
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT;
}
void Turn(int turnRadius, int turnDegrees)
{
if(turnDegrees == 0) return;
distanceExpectedByLeftTire = 2.00 * ((float)turnRadius + HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
distanceExpectedByRightTire = 2.00 * ((float)turnRadius - HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
if(turnDegrees < 0)
{
swap(distanceExpectedByLeftTire, distanceExpectedByRightTire);
distanceExpectedByLeftTire *= -1;
distanceExpectedByRightTire *= -1;
}
circleMotorSpeedDifference = distanceExpectedByLeftTire / distanceExpectedByRightTire;
leftMotorDir = (turnDegrees > 0 || distanceExpectedByLeftTire > 0) ? 1 : -1;
rightMotorDir = (turnDegrees < 0 || distanceExpectedByRightTire > 0) ? 1 : -1;
leftMotorSpeed = STANDARD_SPEED * leftMotorDir;
rightMotorSpeed = STANDARD_SPEED * rightMotorDir;
if(turnDegrees > 0) leftMotorSpeed *= STANDARD_SPEED;
else rightMotorSpeed *= STANDARD_SPEED;
setMotors(leftMotorSpeed, rightMotorSpeed);
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT;
}
void MovePattern()
{
switch(STATE)
{
case SEARCH_INITIAL:
if(IsMovementComplete())
{
Turn(0, -90);
STATE = SEARCH_TURNING;
}
break;
case SEARCH_TURNING:
if(IsMovementComplete())
{
LinearMovement(200);
STATE = SEARCH_FORWARD;
}
break;
case SEARCH_FORWARD:
if(IsMovementComplete())
{
Turn(50, 270);
STATE = SEARCH_TURNING;
}
break;
case FOUND_LEFT:
Turn(0, -90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_RIGHT:
Turn(0, 90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_STRAIGHT:
if(IsMovementComplete())
{
LinearMovement(1000);
STATE = FOUND_STRAIGHT;
}
break;
default:
if(IsMovementComplete())
{
setMotors(0, 0);
}
break;
}
}
/*
void RoundPattern()
{
switch(STATE)
{
case INITIAL_STATE:
{
Turn(200,360);
STATE = STATE_TURNING;
}
break;
case STATE_TURNING:
if(IsMovementComplete())
{
// keep turning
Turn(200,360);
}
break;
default:
setMotors(0, 0);
break;
}
// if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1)
// {
// STATE = EXIT_STATE_ON_SIDE;
// }
// if(OutOfRing())
// {
// STATE = EXIT_STATE_OUT_OF_RING;
// }
// if(Impact())
// {
// STATE = EXIT_STATE_ON_IMPACT;
// }
}
*/
void MainLogic()
{
uint8_t left, right;
readProximitySensors(left, right);
if(left) STATE = FOUND_LEFT;
else if(right) STATE = FOUND_RIGHT;
MovePattern();
HandleControlledMovement();
}
<commit_msg>Remove template swap<commit_after>#include "MainLogic.h"
#include "MotorDriver.h"
#include "DualEncoderDriver.h"
#include "FrontLiftedDetection.h"
#include "ProximitySensors.h"
#include <cmath>
#define STANDARD_SPEED 170
#define SPEED_CHANGE_STEP 1
#define DISTANCE_BETWEEN_MOTORS 85.00
#define HALF_DISTANCE_BETWEEN_MOTORS (DISTANCE_BETWEEN_MOTORS / 2.00)
#define SAMPLE_FREQUENCY 250
enum {
SEARCH_INITIAL,
SEARCH_TURNING,
SEARCH_FORWARD,
FOUND_LEFT,
FOUND_RIGHT,
FOUND_STRAIGHT,
STOP_MOVING
} STATE = SEARCH_INITIAL;
enum {
MOVEMENT_SYSTEM_STATUS_OFF,
MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT,
MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT
} movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
static float distanceExpectedByLeftTire, distanceExpectedByRightTire;
static int16_t leftMotorSpeed, rightMotorSpeed, leftMotorDir, rightMotorDir;
static int8_t directionOfLinearMovement;
static float circleMotorSpeedDifference;
void HandleControlledMovement()
{
switch(movementSystemStatus)
{
case MOVEMENT_SYSTEM_STATUS_OFF:
// stop the motors, they should not be moving
setMotors(0, 0);
break;
case MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT:
{
float leftTyreSpeed = (float)leftEncoder.getSpeed();
float rightTyreSpeed = (float)rightEncoder.getSpeed();
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTyreSpeed > rightTyreSpeed)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
}
else if(leftTyreSpeed < rightTyreSpeed)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= (float)(leftTyreSpeed / SAMPLE_FREQUENCY);
distanceExpectedByRightTire -= (float)(rightTyreSpeed / SAMPLE_FREQUENCY);
if( (distanceExpectedByLeftTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByLeftTire > 0 && directionOfLinearMovement < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByRightTire > 0 && directionOfLinearMovement < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
case MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT:
{
float leftTyreSpeed = leftEncoder.getSpeed();
float rightTyreSpeed = rightEncoder.getSpeed();
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTyreSpeed / rightTyreSpeed > circleMotorSpeedDifference)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
rightMotorSpeed += SPEED_CHANGE_STEP;
}
else if(leftTyreSpeed / rightTyreSpeed < circleMotorSpeedDifference)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
rightMotorSpeed -= SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= leftTyreSpeed / SAMPLE_FREQUENCY;
distanceExpectedByRightTire -= rightTyreSpeed / SAMPLE_FREQUENCY;
if( (distanceExpectedByLeftTire < 0 && leftMotorDir > 0) ||
(distanceExpectedByLeftTire > 0 && leftMotorDir < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && rightMotorDir > 0) ||
(distanceExpectedByRightTire > 0 && rightMotorDir < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
}
}
inline bool IsMovementComplete()
{
return movementSystemStatus == MOVEMENT_SYSTEM_STATUS_OFF;
}
void LinearMovement(int32_t distanceInMMWithDirection) // TODO: Fix backwards
{
// evaluate direction and pass to drivers the start state
if(0 < distanceInMMWithDirection)
{
directionOfLinearMovement = 1;
setMotors(STANDARD_SPEED, STANDARD_SPEED);
}
else
{
directionOfLinearMovement = -1;
setMotors(-STANDARD_SPEED, -STANDARD_SPEED);
}
// set setpoints for end of movement, used in handler
distanceExpectedByRightTire = (float)distanceInMMWithDirection;
distanceExpectedByLeftTire = (float)distanceInMMWithDirection;
// set motor speeds, used in handler
rightMotorSpeed = STANDARD_SPEED;
leftMotorSpeed = STANDARD_SPEED;
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT;
}
void Turn(int turnRadius, int turnDegrees)
{
if(turnDegrees == 0) return;
distanceExpectedByLeftTire = 2.00 * ((float)turnRadius + HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
distanceExpectedByRightTire = 2.00 * ((float)turnRadius - HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
if(turnDegrees < 0)
{
auto temp = -distanceExpectedByLeftTire;
distanceExpectedByLeftTire = -distanceExpectedByRightTire;
distanceExpectedByRightTire = temp;
}
circleMotorSpeedDifference = distanceExpectedByLeftTire / distanceExpectedByRightTire;
leftMotorDir = (turnDegrees > 0 || distanceExpectedByLeftTire > 0) ? 1 : -1;
rightMotorDir = (turnDegrees < 0 || distanceExpectedByRightTire > 0) ? 1 : -1;
leftMotorSpeed = STANDARD_SPEED * leftMotorDir;
rightMotorSpeed = STANDARD_SPEED * rightMotorDir;
if(turnDegrees > 0) leftMotorSpeed *= STANDARD_SPEED;
else rightMotorSpeed *= STANDARD_SPEED;
setMotors(leftMotorSpeed, rightMotorSpeed);
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT;
}
void MovePattern()
{
switch(STATE)
{
case SEARCH_INITIAL:
if(IsMovementComplete())
{
Turn(0, -90);
STATE = SEARCH_TURNING;
}
break;
case SEARCH_TURNING:
if(IsMovementComplete())
{
LinearMovement(200);
STATE = SEARCH_FORWARD;
}
break;
case SEARCH_FORWARD:
if(IsMovementComplete())
{
Turn(50, 270);
STATE = SEARCH_TURNING;
}
break;
case FOUND_LEFT:
Turn(0, -90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_RIGHT:
Turn(0, 90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_STRAIGHT:
if(IsMovementComplete())
{
LinearMovement(1000);
STATE = FOUND_STRAIGHT;
}
break;
default:
if(IsMovementComplete())
{
setMotors(0, 0);
}
break;
}
}
/*
void RoundPattern()
{
switch(STATE)
{
case INITIAL_STATE:
{
Turn(200,360);
STATE = STATE_TURNING;
}
break;
case STATE_TURNING:
if(IsMovementComplete())
{
// keep turning
Turn(200,360);
}
break;
default:
setMotors(0, 0);
break;
}
// if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1)
// {
// STATE = EXIT_STATE_ON_SIDE;
// }
// if(OutOfRing())
// {
// STATE = EXIT_STATE_OUT_OF_RING;
// }
// if(Impact())
// {
// STATE = EXIT_STATE_ON_IMPACT;
// }
}
*/
void MainLogic()
{
uint8_t left, right;
readProximitySensors(left, right);
if(left) STATE = FOUND_LEFT;
else if(right) STATE = FOUND_RIGHT;
MovePattern();
HandleControlledMovement();
}
<|endoftext|> |
<commit_before>#include "MergeSort.h"
#include <cstring>
#include <vector>
void Merge(int *s, int start, int mid, int last) {
std::vector<int> t(last - start + 2);
int i, j, k;
for (i = start, j = mid + 1, k = start; i <= mid && j <= last; k++) {
if (s[i] <= s[j]) {
t[k] = s[i];
i++;
} else {
t[k] = s[j];
j++;
}
}
for (; i <= mid; i++, k++)
t[k] = s[i];
for (; j <= last; j++, k++)
t[k] = s[j];
std::memcpy(s + start, &t.begin() + start, (last - start) * sizeof(int));
}
void MergeSort(int *s, int beg, int end) {
int mid = (beg + end - 1) / 2;
if (beg + 2 >= end) {
Merge(s, beg, mid, end - 1);
return;
}
MergeSort(s, beg, mid + 1);
MergeSort(s, mid + 1, end);
Merge(s, beg, mid, end - 1);
}
<commit_msg>fix compiling bug<commit_after>#include "MergeSort.h"
#include <cstring>
#include <vector>
void Merge(int *s, int start, int mid, int last) {
std::vector<int> t(last - start + 2);
int i, j, k;
for (i = start, j = mid + 1, k = start; i <= mid && j <= last; k++) {
if (s[i] <= s[j]) {
t[k] = s[i];
i++;
} else {
t[k] = s[j];
j++;
}
}
for (; i <= mid; i++, k++)
t[k] = s[i];
for (; j <= last; j++, k++)
t[k] = s[j];
std::memcpy(s + start, t.data() + start, (last - start) * sizeof(int));
}
void MergeSort(int *s, int beg, int end) {
int mid = (beg + end - 1) / 2;
if (beg + 2 >= end) {
Merge(s, beg, mid, end - 1);
return;
}
MergeSort(s, beg, mid + 1);
MergeSort(s, mid + 1, end);
Merge(s, beg, mid, end - 1);
}
<|endoftext|> |
<commit_before>#include "model.h"
#include "recognition.h"
#include <memory>
#include <algorithm>
#include <vector>
using std::min;
using std::max;
using std::make_shared;
using std::dynamic_pointer_cast;
int FIGURE_SELECT_GAP = -1;
int CLOSED_FIGURE_GAP = -1;
const int TRACK_FIT_GAP = 10;
const int DELETION_MOVE_MINIMAL_LENGTH = 5;
const int DELETION_MOVE_MAX_ANGLE = 30;
const int DELETION_MOVE_MIN_COUNT = 3;
const double SQUARING_MIN_RATIO = 0.8;
const double MIN_FIT_POINTS_AMOUNT = 0.75;
void setRecognitionPreset(RecognitionPreset preset) {
switch (preset) {
case RecognitionPreset::Mouse:
FIGURE_SELECT_GAP = 10;
CLOSED_FIGURE_GAP = 10;
break;
case RecognitionPreset::Touch:
FIGURE_SELECT_GAP = 30;
CLOSED_FIGURE_GAP = 50;
break;
};
}
int figureSelectGap() {
return FIGURE_SELECT_GAP;
}
BoundingBox getBoundingBox(const Track &track) {
BoundingBox res;
res.leftUp = res.rightDown = track[0];
for (Point p : track.points) {
res.leftUp.x = min(res.leftUp.x, p.x);
res.leftUp.y = min(res.leftUp.y, p.y);
res.rightDown.x = max(res.rightDown.x, p.x);
res.rightDown.y = max(res.rightDown.y, p.y);
}
return res;
}
double getCircumference(const Track &track) {
double res = 0;
for (size_t i = 0; i + 1 < track.size(); i++) {
res += (track[i + 1] - track[i]).length();
}
return res;
}
double getClosedCircumference(const Track &track) {
double res = getCircumference(track);
res += (track[0] - track[track.size() - 1]).length();
return res;
}
bool cutToClosed(Track &track) {
auto &points = track.points;
auto it = points.begin();
while (it != points.end() && (points[0] - *it).length() <= CLOSED_FIGURE_GAP) {
it++;
}
while (it != points.end() && (points[0] - *it).length() > CLOSED_FIGURE_GAP) {
it++;
}
if (it == points.end()) {
return false;
}
while (it != points.end() && (points[0] - *it).length() <= CLOSED_FIGURE_GAP) {
it++;
}
points.erase(it, points.end());
return true;
}
double fitsToTrack(const Track &track, const PFigure &figure) {
BoundingBox box = getBoundingBox(track);
double maxDistance = TRACK_FIT_GAP;
maxDistance = std::min(maxDistance, std::min(box.width(), box.height()) * 0.2);
int goodCount = 0;
for (Point p : track.points) {
goodCount += figure->getApproximateDistanceToBorder(p) <= maxDistance;
}
return goodCount * 1.0 / track.size();
}
using namespace figures;
bool isDeletionTrack(const Track &track) {
int cnt = 0;
std::cout << "new\n";
for (int i = 0; i < (int)track.size(); i++) {
int prevPoint = i - 1;
while (prevPoint >= 0 && (track[i] - track[prevPoint]).length() < DELETION_MOVE_MINIMAL_LENGTH) {
prevPoint--;
}
int nextPoint = i + 1;
while (nextPoint < (int)track.size() && (track[i] - track[nextPoint]).length() < DELETION_MOVE_MINIMAL_LENGTH) {
nextPoint++;
}
if (prevPoint >= 0 && nextPoint < (int)track.size()) {
Point vec1 = track[nextPoint] - track[i];
Point vec2 = track[prevPoint] - track[i];
double ang = acos(Point::dotProduct(vec1, vec2) / (vec1.length() * vec2.length()));
if (ang <= PI * DELETION_MOVE_MAX_ANGLE / 180) {
cnt++;
i = nextPoint;
}
}
}
std::cout << "deletion cnt = " << cnt << "\n";
return cnt >= DELETION_MOVE_MIN_COUNT;
}
PFigure recognizeConnections(const Track &track, Model &model) {
Point start = track[0];
Point end = track[track.size() - 1];
for (auto it = model.begin(); it != model.end(); it++) {
PFigure figure = *it;
auto figA = dynamic_pointer_cast<BoundedFigure>(figure);
if (!figA) { continue; }
if (!figure->isInsideOrOnBorder(start)) { continue; }
for (PFigure figure2 : model) {
if (figure == figure2) {
continue;
}
auto figB = dynamic_pointer_cast<BoundedFigure>(figure2);
if (figB && figB->isInsideOrOnBorder(end)) {
auto result = make_shared<SegmentConnection>(figA, figB);
model.addFigure(result);
return result;
}
}
}
return nullptr;
}
PFigure recognizeGrabs(const Track &track, Model &model) {
Point start = track[0];
Point end = track[track.size() - 1];
for (auto it = model.begin(); it != model.end(); it++) {
PFigure figure = *it;
if (figure->getApproximateDistanceToBorder(start) <= FIGURE_SELECT_GAP) { // grabbed
// recognize deletion
if (isDeletionTrack(track)) {
model.removeFigure(it);
return figure;
}
// try connection
auto figA = dynamic_pointer_cast<BoundedFigure>(figure);
if (figA) {
for (PFigure figure2 : model) {
if (figure == figure2) {
continue;
}
auto figB = dynamic_pointer_cast<BoundedFigure>(figure2);
if (figB && figB->getApproximateDistanceToBorder(end) <= FIGURE_SELECT_GAP) {
auto result = make_shared<SegmentConnection>(figA, figB);
model.addFigure(result);
return result;
}
}
}
// now we try translation
figure->translate(end - start);
model.recalculate();
return figure;
}
}
return nullptr;
}
void squareBoundedFigure(PBoundedFigure figure) {
BoundingBox box = figure->getBoundingBox();
double siz1 = box.width();
double siz2 = box.height();
if (siz1 > siz2) {
std::swap(siz1, siz2);
}
std::cout << "bounded size=" << siz1 << ";" << siz2 << "; k=" << (siz1 / siz2) << "\n";
if (siz1 / siz2 < SQUARING_MIN_RATIO) { return; }
double siz = (siz1 + siz2) / 2;
box.rightDown = box.leftUp + Point(siz, siz);
figure->setBoundingBox(box);
}
struct SelectionFit {
bool isSegment;
double distance;
PFigure figure;
SelectionFit() : isSegment(false), distance(HUGE_VAL), figure(nullptr) {}
bool operator<(const SelectionFit &other) const {
if (isSegment != other.isSegment) { return isSegment > other.isSegment; }
return distance < other.distance;
}
};
PFigure recognizeClicks(const Point &click, Model &model) {
SelectionFit bestFit;
for (PFigure figure : model) {
SelectionFit currentFit;
currentFit.isSegment = !!dynamic_pointer_cast<Segment>(figure);
currentFit.distance = figure->getApproximateDistanceToBorder(click);
currentFit.figure = figure;
if (currentFit.distance >= FIGURE_SELECT_GAP) { continue; }
bestFit = min(bestFit, currentFit);
}
if (bestFit.figure) {
model.selectedFigure = bestFit.figure;
} else {
for (PFigure figure : model) {
if (figure->isInsideOrOnBorder(click)) {
model.selectedFigure = figure;
}
}
}
std::shared_ptr<Segment> segm = dynamic_pointer_cast<Segment>(model.selectedFigure);
if (segm) {
if ((click - segm->getA()).length() <= FIGURE_SELECT_GAP) {
segm->setArrowedA(!segm->getArrowedA());
}
if ((click - segm->getB()).length() <= FIGURE_SELECT_GAP) {
segm->setArrowedB(!segm->getArrowedB());
}
return segm;
}
return nullptr;
}
/*
* Consider a continuos polyline. This function returns its center of mass.
* Please note that this differs from center of mass of all points of track,
* we calculate weighted sum of segments' centers (weight == length of segment)
*/
Point getWeightedCenter(const Track &track) {
Point result;
double summaryLength = 0;
for (size_t i = 0; i < track.size(); i++) {
Point a = track[i];
Point b = track[(i + 1) % track.size()];
Point middle = (a + b) * 0.5;
double length = (b - a).length();
result += middle * length;
summaryLength += length;
}
result = result * (1.0 / summaryLength);
return result;
}
/*
* Calculates best rectangle which will fit the track
* For example, it considers that there may be some
* outliners (they happen near corners when drawing on touch devices)
* First, it calculate approximate center of the rectangle and then
* it calculates average 'width' and 'height' of the rectangle.
* Points which differ from the center no more than width/4 are
* considered 'horizontal segments' and vice-versa for vertical.
*/
BoundingBox getBestFitRectangle(const Track &track) {
BoundingBox total = getBoundingBox(track);
double maxDx = total.width() / 4;
double maxDy = total.height() / 4;
Point center = getWeightedCenter(track);
double sumDx = 0, sumDy = 0;
int countDx = 0, countDy = 0;
for (Point p : track.points) {
double dx = fabs(p.x - center.x);
double dy = fabs(p.y - center.y);
if (dx < maxDx && dy >= maxDy) {
sumDy += dy;
countDy++;
}
if (dy < maxDy && dx >= maxDx) {
sumDx += dx;
countDx++;
}
}
Point diff(
countDx ? sumDx / countDx : maxDx,
countDy ? sumDy / countDy : maxDy
);
return BoundingBox({ center - diff, center + diff });
}
std::vector<Point> smoothCurve(std::vector<Point> current) {
assert(!current.empty());
Point start = current[0];
Point end = current.back();
if ((start - end).length() <= CLOSED_FIGURE_GAP) {
end = current.back() = start;
}
Segment segment(start, end);
std::pair<double, size_t> maxDistance(0, 0);
for (size_t i = 0; i < current.size(); i++) {
double d = segment.getApproximateDistanceToBorder(current[i]);
maxDistance = max(maxDistance, std::make_pair(d, i));
}
std::vector<Point> result;
if (maxDistance.first > TRACK_FIT_GAP) {
auto part1 = smoothCurve(std::vector<Point>(current.begin(), current.begin() + maxDistance.second + 1));
auto part2 = smoothCurve(std::vector<Point>(current.begin() + maxDistance.second, current.end()));
result.insert(result.end(), part1.begin(), part1.end());
result.insert(result.end(), part2.begin() + 1, part2.end());
} else {
result.push_back(start);
result.push_back(end);
}
return result;
}
PFigure recognize(const Track &_track, Model &model) {
if (FIGURE_SELECT_GAP < 0 || CLOSED_FIGURE_GAP < 0) {
throw std::logic_error("Recognition preset is not selected");
}
// this is to preserve the API (const Track&) and make future optimizations possible
// i.e. avoid copying if it's not necessary
Track track = _track;
if (track.empty()) { return nullptr; }
// Very small tracks are clicks
if (getClosedCircumference(track) <= CLOSED_FIGURE_GAP) {
return recognizeClicks(track[0], model);
}
// Moving and connecting
if (PFigure result = recognizeGrabs(track, model)) {
return result;
}
// Connecting interior-->interior
if (PFigure result = recognizeConnections(track, model)) {
return result;
}
// Drawing new figures
std::vector<PFigure> candidates;
if (!cutToClosed(track)) {
candidates.push_back(make_shared<Segment>(track[0], track[track.size() - 1]));
} else {
candidates.push_back(make_shared<Ellipse>(getBoundingBox(track)));
candidates.push_back(make_shared<Rectangle>(getBestFitRectangle(track)));
}
if (candidates.empty()) { return nullptr; }
std::vector<double> fits;
for (PFigure figure : candidates) {
fits.push_back(fitsToTrack(track, figure));
}
size_t id = max_element(fits.begin(), fits.end()) - fits.begin();
std::cout << "max_fit = " << fits[id] << "; id = " << id << "\n";
if (fits[id] >= MIN_FIT_POINTS_AMOUNT) { // we allow some of points to fall out of our track
auto boundedFigure = dynamic_pointer_cast<BoundedFigure>(candidates[id]);
if (boundedFigure) {
squareBoundedFigure(boundedFigure);
}
model.addFigure(candidates[id]);
return candidates[id];
}
auto result = make_shared<Curve>(smoothCurve(track.points));
model.addFigure(result);
return result;
}
<commit_msg>recognition: selection is dropped now if you click out of figures (#66)<commit_after>#include "model.h"
#include "recognition.h"
#include <memory>
#include <algorithm>
#include <vector>
using std::min;
using std::max;
using std::make_shared;
using std::dynamic_pointer_cast;
int FIGURE_SELECT_GAP = -1;
int CLOSED_FIGURE_GAP = -1;
const int TRACK_FIT_GAP = 10;
const int DELETION_MOVE_MINIMAL_LENGTH = 5;
const int DELETION_MOVE_MAX_ANGLE = 30;
const int DELETION_MOVE_MIN_COUNT = 3;
const double SQUARING_MIN_RATIO = 0.8;
const double MIN_FIT_POINTS_AMOUNT = 0.75;
void setRecognitionPreset(RecognitionPreset preset) {
switch (preset) {
case RecognitionPreset::Mouse:
FIGURE_SELECT_GAP = 10;
CLOSED_FIGURE_GAP = 10;
break;
case RecognitionPreset::Touch:
FIGURE_SELECT_GAP = 30;
CLOSED_FIGURE_GAP = 50;
break;
};
}
int figureSelectGap() {
return FIGURE_SELECT_GAP;
}
BoundingBox getBoundingBox(const Track &track) {
BoundingBox res;
res.leftUp = res.rightDown = track[0];
for (Point p : track.points) {
res.leftUp.x = min(res.leftUp.x, p.x);
res.leftUp.y = min(res.leftUp.y, p.y);
res.rightDown.x = max(res.rightDown.x, p.x);
res.rightDown.y = max(res.rightDown.y, p.y);
}
return res;
}
double getCircumference(const Track &track) {
double res = 0;
for (size_t i = 0; i + 1 < track.size(); i++) {
res += (track[i + 1] - track[i]).length();
}
return res;
}
double getClosedCircumference(const Track &track) {
double res = getCircumference(track);
res += (track[0] - track[track.size() - 1]).length();
return res;
}
bool cutToClosed(Track &track) {
auto &points = track.points;
auto it = points.begin();
while (it != points.end() && (points[0] - *it).length() <= CLOSED_FIGURE_GAP) {
it++;
}
while (it != points.end() && (points[0] - *it).length() > CLOSED_FIGURE_GAP) {
it++;
}
if (it == points.end()) {
return false;
}
while (it != points.end() && (points[0] - *it).length() <= CLOSED_FIGURE_GAP) {
it++;
}
points.erase(it, points.end());
return true;
}
double fitsToTrack(const Track &track, const PFigure &figure) {
BoundingBox box = getBoundingBox(track);
double maxDistance = TRACK_FIT_GAP;
maxDistance = std::min(maxDistance, std::min(box.width(), box.height()) * 0.2);
int goodCount = 0;
for (Point p : track.points) {
goodCount += figure->getApproximateDistanceToBorder(p) <= maxDistance;
}
return goodCount * 1.0 / track.size();
}
using namespace figures;
bool isDeletionTrack(const Track &track) {
int cnt = 0;
std::cout << "new\n";
for (int i = 0; i < (int)track.size(); i++) {
int prevPoint = i - 1;
while (prevPoint >= 0 && (track[i] - track[prevPoint]).length() < DELETION_MOVE_MINIMAL_LENGTH) {
prevPoint--;
}
int nextPoint = i + 1;
while (nextPoint < (int)track.size() && (track[i] - track[nextPoint]).length() < DELETION_MOVE_MINIMAL_LENGTH) {
nextPoint++;
}
if (prevPoint >= 0 && nextPoint < (int)track.size()) {
Point vec1 = track[nextPoint] - track[i];
Point vec2 = track[prevPoint] - track[i];
double ang = acos(Point::dotProduct(vec1, vec2) / (vec1.length() * vec2.length()));
if (ang <= PI * DELETION_MOVE_MAX_ANGLE / 180) {
cnt++;
i = nextPoint;
}
}
}
std::cout << "deletion cnt = " << cnt << "\n";
return cnt >= DELETION_MOVE_MIN_COUNT;
}
PFigure recognizeConnections(const Track &track, Model &model) {
Point start = track[0];
Point end = track[track.size() - 1];
for (auto it = model.begin(); it != model.end(); it++) {
PFigure figure = *it;
auto figA = dynamic_pointer_cast<BoundedFigure>(figure);
if (!figA) { continue; }
if (!figure->isInsideOrOnBorder(start)) { continue; }
for (PFigure figure2 : model) {
if (figure == figure2) {
continue;
}
auto figB = dynamic_pointer_cast<BoundedFigure>(figure2);
if (figB && figB->isInsideOrOnBorder(end)) {
auto result = make_shared<SegmentConnection>(figA, figB);
model.addFigure(result);
return result;
}
}
}
return nullptr;
}
PFigure recognizeGrabs(const Track &track, Model &model) {
Point start = track[0];
Point end = track[track.size() - 1];
for (auto it = model.begin(); it != model.end(); it++) {
PFigure figure = *it;
if (figure->getApproximateDistanceToBorder(start) <= FIGURE_SELECT_GAP) { // grabbed
// recognize deletion
if (isDeletionTrack(track)) {
model.removeFigure(it);
return figure;
}
// try connection
auto figA = dynamic_pointer_cast<BoundedFigure>(figure);
if (figA) {
for (PFigure figure2 : model) {
if (figure == figure2) {
continue;
}
auto figB = dynamic_pointer_cast<BoundedFigure>(figure2);
if (figB && figB->getApproximateDistanceToBorder(end) <= FIGURE_SELECT_GAP) {
auto result = make_shared<SegmentConnection>(figA, figB);
model.addFigure(result);
return result;
}
}
}
// now we try translation
figure->translate(end - start);
model.recalculate();
return figure;
}
}
return nullptr;
}
void squareBoundedFigure(PBoundedFigure figure) {
BoundingBox box = figure->getBoundingBox();
double siz1 = box.width();
double siz2 = box.height();
if (siz1 > siz2) {
std::swap(siz1, siz2);
}
std::cout << "bounded size=" << siz1 << ";" << siz2 << "; k=" << (siz1 / siz2) << "\n";
if (siz1 / siz2 < SQUARING_MIN_RATIO) { return; }
double siz = (siz1 + siz2) / 2;
box.rightDown = box.leftUp + Point(siz, siz);
figure->setBoundingBox(box);
}
struct SelectionFit {
bool isSegment;
double distance;
PFigure figure;
SelectionFit() : isSegment(false), distance(HUGE_VAL), figure(nullptr) {}
bool operator<(const SelectionFit &other) const {
if (isSegment != other.isSegment) { return isSegment > other.isSegment; }
return distance < other.distance;
}
};
PFigure recognizeClicks(const Point &click, Model &model) {
SelectionFit bestFit;
for (PFigure figure : model) {
SelectionFit currentFit;
currentFit.isSegment = !!dynamic_pointer_cast<Segment>(figure);
currentFit.distance = figure->getApproximateDistanceToBorder(click);
currentFit.figure = figure;
if (currentFit.distance >= FIGURE_SELECT_GAP) { continue; }
bestFit = min(bestFit, currentFit);
}
if (bestFit.figure) {
model.selectedFigure = bestFit.figure;
} else {
bool found = false;
for (PFigure figure : model) {
if (figure->isInsideOrOnBorder(click)) {
model.selectedFigure = figure;
found = true;
}
}
if (!found) {
model.selectedFigure = nullptr;
}
}
std::shared_ptr<Segment> segm = dynamic_pointer_cast<Segment>(model.selectedFigure);
if (segm) {
if ((click - segm->getA()).length() <= FIGURE_SELECT_GAP) {
segm->setArrowedA(!segm->getArrowedA());
}
if ((click - segm->getB()).length() <= FIGURE_SELECT_GAP) {
segm->setArrowedB(!segm->getArrowedB());
}
return segm;
}
return nullptr;
}
/*
* Consider a continuos polyline. This function returns its center of mass.
* Please note that this differs from center of mass of all points of track,
* we calculate weighted sum of segments' centers (weight == length of segment)
*/
Point getWeightedCenter(const Track &track) {
Point result;
double summaryLength = 0;
for (size_t i = 0; i < track.size(); i++) {
Point a = track[i];
Point b = track[(i + 1) % track.size()];
Point middle = (a + b) * 0.5;
double length = (b - a).length();
result += middle * length;
summaryLength += length;
}
result = result * (1.0 / summaryLength);
return result;
}
/*
* Calculates best rectangle which will fit the track
* For example, it considers that there may be some
* outliners (they happen near corners when drawing on touch devices)
* First, it calculate approximate center of the rectangle and then
* it calculates average 'width' and 'height' of the rectangle.
* Points which differ from the center no more than width/4 are
* considered 'horizontal segments' and vice-versa for vertical.
*/
BoundingBox getBestFitRectangle(const Track &track) {
BoundingBox total = getBoundingBox(track);
double maxDx = total.width() / 4;
double maxDy = total.height() / 4;
Point center = getWeightedCenter(track);
double sumDx = 0, sumDy = 0;
int countDx = 0, countDy = 0;
for (Point p : track.points) {
double dx = fabs(p.x - center.x);
double dy = fabs(p.y - center.y);
if (dx < maxDx && dy >= maxDy) {
sumDy += dy;
countDy++;
}
if (dy < maxDy && dx >= maxDx) {
sumDx += dx;
countDx++;
}
}
Point diff(
countDx ? sumDx / countDx : maxDx,
countDy ? sumDy / countDy : maxDy
);
return BoundingBox({ center - diff, center + diff });
}
std::vector<Point> smoothCurve(std::vector<Point> current) {
assert(!current.empty());
Point start = current[0];
Point end = current.back();
if ((start - end).length() <= CLOSED_FIGURE_GAP) {
end = current.back() = start;
}
Segment segment(start, end);
std::pair<double, size_t> maxDistance(0, 0);
for (size_t i = 0; i < current.size(); i++) {
double d = segment.getApproximateDistanceToBorder(current[i]);
maxDistance = max(maxDistance, std::make_pair(d, i));
}
std::vector<Point> result;
if (maxDistance.first > TRACK_FIT_GAP) {
auto part1 = smoothCurve(std::vector<Point>(current.begin(), current.begin() + maxDistance.second + 1));
auto part2 = smoothCurve(std::vector<Point>(current.begin() + maxDistance.second, current.end()));
result.insert(result.end(), part1.begin(), part1.end());
result.insert(result.end(), part2.begin() + 1, part2.end());
} else {
result.push_back(start);
result.push_back(end);
}
return result;
}
PFigure recognize(const Track &_track, Model &model) {
if (FIGURE_SELECT_GAP < 0 || CLOSED_FIGURE_GAP < 0) {
throw std::logic_error("Recognition preset is not selected");
}
// this is to preserve the API (const Track&) and make future optimizations possible
// i.e. avoid copying if it's not necessary
Track track = _track;
if (track.empty()) { return nullptr; }
// Very small tracks are clicks
if (getClosedCircumference(track) <= CLOSED_FIGURE_GAP) {
return recognizeClicks(track[0], model);
}
// Moving and connecting
if (PFigure result = recognizeGrabs(track, model)) {
return result;
}
// Connecting interior-->interior
if (PFigure result = recognizeConnections(track, model)) {
return result;
}
// Drawing new figures
std::vector<PFigure> candidates;
if (!cutToClosed(track)) {
candidates.push_back(make_shared<Segment>(track[0], track[track.size() - 1]));
} else {
candidates.push_back(make_shared<Ellipse>(getBoundingBox(track)));
candidates.push_back(make_shared<Rectangle>(getBestFitRectangle(track)));
}
if (candidates.empty()) { return nullptr; }
std::vector<double> fits;
for (PFigure figure : candidates) {
fits.push_back(fitsToTrack(track, figure));
}
size_t id = max_element(fits.begin(), fits.end()) - fits.begin();
std::cout << "max_fit = " << fits[id] << "; id = " << id << "\n";
if (fits[id] >= MIN_FIT_POINTS_AMOUNT) { // we allow some of points to fall out of our track
auto boundedFigure = dynamic_pointer_cast<BoundedFigure>(candidates[id]);
if (boundedFigure) {
squareBoundedFigure(boundedFigure);
}
model.addFigure(candidates[id]);
return candidates[id];
}
auto result = make_shared<Curve>(smoothCurve(track.points));
model.addFigure(result);
return result;
}
<|endoftext|> |
<commit_before>/// \file AddTaskEmcalJetCDF.C
/// \brief Adds a AliAnalysisTaskEmcalJetCDF analysis task and coresponding containers
///
/// Analysis of leading jets distribution of pt and multiplicity, R distribution
/// N80 and Pt80 and Toward, Transverse, Away UE histos
///
/// \author Adrian SEVCENCO <Adrian.Sevcenco@cern.ch>, Institute of Space Science, Romania
/// \date Mar 19, 2015
/// Add a AliAnalysisTaskEmcalJetCDF task - detailed signature
/// \param const char *ntracks
/// \param const char *nclusters
/// \param const char *njets
/// \param const char *nrho
/// \param Double_t jetradius
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDF* task
AliAnalysisTaskEmcalJetCDF* AddTaskEmcalJetCDF (
AliEmcalJetTask* jf_task,
const char *ntracks = "usedefault",
const char *nclusters = "usedefault",
const char *njets = "Jets",
const char *nrho = "",
Double_t jetptcut = 1.,
Double_t jetptcutmax = 250.,
Double_t jetareacut = 0.001,
AliJetContainer::JetAcceptanceType acceptance = AliJetContainer::kTPCfid,
Int_t leadhadtype = 0, // AliJetContainer :: Int_t fLeadingHadronType; 0 = charged, 1 = neutral, 2 = both
const char *taskname = "CDF"
)
{
// const char* ncells = "usedefault",
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if ( !mgr ) { ::Error ( "AddTaskEmcalJetCDF", "No analysis manager to connect to." ); return NULL; }
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
AliVEventHandler* handler = mgr->GetInputEventHandler();
if (!handler) { ::Error ( "AddTaskEmcalJetCDF", "This task requires an input event handler" ); return NULL; }
if ( (!jf_task) && (!jf_task->InheritsFrom ( "AliEmcalJetTask")) ) { ::Error ( "AddTaskEmcalJetCDF", "Invalid AliEmcalJetTask* pointer"); return NULL; }
enum EDataType_t { kUnknown, kESD, kAOD };
EDataType_t dataType = kUnknown;
if (handler->InheritsFrom("AliESDInputHandler")) { dataType = kESD; }
else
if (handler->InheritsFrom("AliAODInputHandler")) { dataType = kAOD; }
AliJetContainer::EJetType_t jettype_t = jf_task->GetJetType();
AliJetContainer::ERecoScheme_t recomb_t = jf_task->GetRecombScheme();
AliJetContainer::EJetAlgo_t jetalgo_t = AliJetContainer::antikt_algorithm;
Double_t radius = jf_task->GetRadius();
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString name ( taskname );
TString tracks ( ntracks );
TString clusters ( nclusters );
//TString cellName(ncells);
TString jets ( njets );
TString rho ( nrho );
if ( tracks.EqualTo("usedefault") )
{
if ( dataType == kESD ) { tracks = "Tracks"; }
else
if ( dataType == kAOD ) { tracks = "tracks"; }
else
{ tracks = ""; }
}
if ( clusters.EqualTo("usedefault") )
{
if ( dataType == kESD ) { clusters = "CaloClusters"; }
else
if ( dataType == kAOD ) { clusters = "caloClusters"; }
else
{ clusters = ""; }
}
// if (cellName.EqualTo ("usedefault"))
// {
// if (dataType == kESD) { cellName = "EMCALCells"; }
// else cellName = "emcalCells"; }
// }
TString acctype = "acc"; acctype += TString::Itoa(acceptance,10);
if ( jetptcut < 1. ) { jetptcut = 1.; }
TString jetstr = "jpt";
jetstr += ( ULong_t ) ( jetptcut * 1000 );
if ( !jets.IsNull() ) { name += "_" + jets + "_" + jetstr; }
if ( !rho.IsNull() ) { name += "_" + rho; }
if ( !acctype.IsNull() ) { name += "_" + acctype; }
AliAnalysisTaskEmcalJetCDF* jetTask = new AliAnalysisTaskEmcalJetCDF ( name );
jetTask->SetVzRange(-10,10);
jetTask->SetNeedEmcalGeom(kFALSE);
AliParticleContainer* trackCont = jetTask->AddParticleContainer ( tracks.Data() );
trackCont->SetParticlePtCut(0.15);
AliClusterContainer* clusterCont = NULL;
if ( !clusters.IsNull() )
{
clusterCont = jetTask->AddClusterContainer ( clusters.Data() );
clusterCont->SetClusECut(0.);
clusterCont->SetClusPtCut(0.);
clusterCont->SetClusHadCorrEnergyCut(0.30);
clusterCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
}
AliJetContainer *jetCont = jetTask->AddJetContainer(
jettype_t,
jetalgo_t,
recomb_t,
radius,
acceptance,
trackCont,
clusterCont,
name);
if ( !jetCont ) { std::cout << "AddTaskEmcalJetCDF.C :: could not add jetCont" << std::endl; return NULL; }
if ( !rho.IsNull() ) { jetCont->SetRhoName ( nrho ); }
jetCont->SetPercAreaCut ( jetareacut );
jetCont->SetJetPtCut ( jetptcut );
jetCont->SetJetPtCutMax ( jetptcutmax );
jetCont->SetLeadingHadronType ( leadhadtype ); // Int_t fLeadingHadronType; 0 = charged, 1 = neutral, 2 = both
jetCont->SetMaxTrackPt(1000);
jetCont->SetNLeadingJets(1);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask ( jetTask );
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
TString contname = name + "_histos";
TString outfile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer ( contname.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, outfile.Data() );
mgr->ConnectInput ( jetTask, 0, cinput1 );
mgr->ConnectOutput ( jetTask, 1, coutput1 );
return jetTask;
}
AliAnalysisTaskEmcalJetCDF* AddTaskEmcalJetCDF (
const char* taskname,
const char *ntracks = "usedefault",
const char *nclusters = "usedefault",
const char *njets = "Jets",
const char *nrho = "",
Double_t jetradius = 0.2,
Double_t jetptcut = 1.,
Double_t jetptcutmax = 250.,
Double_t jetareacut = 0.001,
AliJetContainer::JetAcceptanceType type = AliJetContainer::kTPCfid,
Int_t leadhadtype = 0, // AliJetContainer :: Int_t fLeadingHadronType; 0 = charged, 1 = neutral, 2 = both
const char *taskname = "CDF"
)
{
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) { ::Error("AddTaskEmcalJetCDF", "No analysis manager to connect to."); }
AliEmcalJetTask* jf = dynamic_cast<AliEmcalJetTask*>(mgr->GetTask(taskname));
if (!jf) { AliError("AddTaskEmcalJetCDF :: task is not EmcalJetTask");}
return AddTaskEmcalJetCDF ( jf, ntracks, nclusters, njets, nrho, jetptcut, jetptcutmax, jetareacut, type, leadhadtype, taskname);
}
// kate: indent-mode none; indent-width 2; replace-tabs on;
<commit_msg>AddTaskEmcalJetCDF.C :: new updates<commit_after>/// \file AddTaskEmcalJetCDF.C
/// \brief Adds a AliAnalysisTaskEmcalJetCDF analysis task and coresponding containers
///
/// Analysis of leading jets distribution of pt and multiplicity, R distribution
/// N80 and Pt80 and Toward, Transverse, Away UE histos
///
/// \author Adrian SEVCENCO <Adrian.Sevcenco@cern.ch>, Institute of Space Science, Romania
/// \date Mar 19, 2015
/// Add a AliAnalysisTaskEmcalJetCDF task - detailed signature
/// \param const char *ntracks
/// \param const char *nclusters
/// \param const char *njets
/// \param const char *nrho
/// \param Double_t jetradius
/// \param Double_t jetptcut
/// \param Double_t jetareacut
/// \param const char *type ; either TPC, EMCAL or USER
/// \param Int_t leadhadtype ; 0 = charged, 1 = neutral, 2 = both
/// \param const char *taskname
/// \return AliAnalysisTaskEmcalJetCDF* task
AliAnalysisTaskEmcalJetCDF* AddTaskEmcalJetCDF (
AliEmcalJetTask* jf_task,
const char *ntracks = "usedefault",
const char *nclusters = "usedefault",
const char *njets = "Jets",
const char *nrho = "",
Double_t jetptcut = 1.,
Double_t jetptcutmax = 250.,
Double_t jetareacut = 0.001,
AliJetContainer::JetAcceptanceType acceptance = AliJetContainer::kTPCfid,
Int_t leadhadtype = 0, // AliJetContainer :: Int_t fLeadingHadronType; 0 = charged, 1 = neutral, 2 = both
const char *taskname = "CDF"
)
{
// const char* ncells = "usedefault",
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if ( !mgr ) { ::Error ( "AddTaskEmcalJetCDF", "No analysis manager to connect to." ); return NULL; }
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
AliVEventHandler* handler = mgr->GetInputEventHandler();
if (!handler) { ::Error ( "AddTaskEmcalJetCDF", "This task requires an input event handler" ); return NULL; }
if ( (!jf_task) && (!jf_task->InheritsFrom ( "AliEmcalJetTask")) ) { ::Error ( "AddTaskEmcalJetCDF", "Invalid AliEmcalJetTask* pointer"); return NULL; }
enum EDataType_t { kUnknown, kESD, kAOD };
EDataType_t dataType = kUnknown;
if (handler->InheritsFrom("AliESDInputHandler")) { dataType = kESD; }
else
if (handler->InheritsFrom("AliAODInputHandler")) { dataType = kAOD; }
AliJetContainer::EJetType_t jettype_t = jf_task->GetJetType();
AliJetContainer::ERecoScheme_t recomb_t = jf_task->GetRecombScheme();
AliJetContainer::EJetAlgo_t jetalgo_t = AliJetContainer::antikt_algorithm;
Double_t radius = jf_task->GetRadius();
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString name ( taskname );
TString tracks ( ntracks );
TString clusters ( nclusters );
//TString cellName(ncells);
TString jets ( njets );
TString rho ( nrho );
if ( tracks.EqualTo("usedefault") )
{
if ( dataType == kESD ) { tracks = "Tracks"; }
else
if ( dataType == kAOD ) { tracks = "tracks"; }
else
{ tracks = ""; }
}
if ( clusters.EqualTo("usedefault") )
{
if ( dataType == kESD ) { clusters = "CaloClusters"; }
else
if ( dataType == kAOD ) { clusters = "caloClusters"; }
else
{ clusters = ""; }
}
// if (cellName.EqualTo ("usedefault"))
// {
// if (dataType == kESD) { cellName = "EMCALCells"; }
// else cellName = "emcalCells"; }
// }
TString acctype = "acc"; acctype += TString::Itoa(acceptance,10);
if ( jetptcut < 1. ) { jetptcut = 1.; }
TString jetstr = "jpt";
jetstr += ( ULong_t ) ( jetptcut * 1000 );
if ( !jets.IsNull() ) { name += "_" + jets + "_" + jetstr; }
if ( !rho.IsNull() ) { name += "_" + rho; }
if ( !acctype.IsNull() ) { name += "_" + acctype; }
AliAnalysisTaskEmcalJetCDF* jetTask = new AliAnalysisTaskEmcalJetCDF ( name );
jetTask->SetVzRange(-10,10);
jetTask->SetNeedEmcalGeom(kFALSE);
if ( tracks.EqualTo("mcparticles") )
{
AliMCParticleContainer* mcpartCont = jetTask->AddMCParticleContainer ( tracks.Data() );
mcpartCont->SelectPhysicalPrimaries(kTRUE);
}
else
if ( tracks.EqualTo("tracks") || tracks.EqualTo("Tracks") ) {
AliTrackContainer* trackCont = jetTask->AddTrackContainer( tracks.Data() );
trackCont->SetFilterHybridTracks(kTRUE);
}
else
if ( !tracks.IsNull())
{
jetTask->AddParticleContainer(tracks.Data());
}
AliParticleContainer* partCont = jetTask->GetParticleContainer(0);
if (partCont) { partCont->SetParticlePtCut(0.15); }
AliClusterContainer* clusterCont = NULL;
if ( !clusters.IsNull() )
{
clusterCont = jetTask->AddClusterContainer ( clusters.Data() );
clusterCont->SetClusECut(0.);
clusterCont->SetClusPtCut(0.);
clusterCont->SetClusHadCorrEnergyCut(0.30);
clusterCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
}
AliJetContainer *jetCont = jetTask->AddJetContainer(
jettype_t,
jetalgo_t,
recomb_t,
radius,
acceptance,
partCont,
clusterCont,
name);
if ( !jetCont ) { std::cout << "AddTaskEmcalJetCDF.C :: could not add jetCont" << std::endl; return NULL; }
if ( !rho.IsNull() ) { jetCont->SetRhoName ( nrho ); }
jetCont->SetPercAreaCut ( jetareacut );
jetCont->SetJetPtCut ( jetptcut );
jetCont->SetJetPtCutMax ( jetptcutmax );
jetCont->SetLeadingHadronType ( leadhadtype ); // Int_t fLeadingHadronType; 0 = charged, 1 = neutral, 2 = both
jetCont->SetMaxTrackPt(1000);
jetCont->SetNLeadingJets(1);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask ( jetTask );
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
TString contname = name + "_histos";
TString outfile = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer ( contname.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, outfile.Data() );
mgr->ConnectInput ( jetTask, 0, cinput1 );
mgr->ConnectOutput ( jetTask, 1, coutput1 );
return jetTask;
}
AliAnalysisTaskEmcalJetCDF* AddTaskEmcalJetCDF (
const char* taskname,
const char *ntracks = "usedefault",
const char *nclusters = "usedefault",
const char *njets = "Jets",
const char *nrho = "",
Double_t jetradius = 0.2,
Double_t jetptcut = 1.,
Double_t jetptcutmax = 250.,
Double_t jetareacut = 0.001,
AliJetContainer::JetAcceptanceType type = AliJetContainer::kTPCfid,
Int_t leadhadtype = 0, // AliJetContainer :: Int_t fLeadingHadronType; 0 = charged, 1 = neutral, 2 = both
const char *taskname = "CDF"
)
{
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) { ::Error("AddTaskEmcalJetCDF", "No analysis manager to connect to."); }
AliEmcalJetTask* jf = dynamic_cast<AliEmcalJetTask*>(mgr->GetTask(taskname));
if (!jf) { AliError("AddTaskEmcalJetCDF :: task is not EmcalJetTask");}
return AddTaskEmcalJetCDF ( jf, ntracks, nclusters, njets, nrho, jetptcut, jetptcutmax, jetareacut, type, leadhadtype, taskname);
}
// kate: indent-mode none; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>/*
* niinudge.cpp
*
* Copyright (c) 2014 Tobias Wood.
*
* 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/.
*
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <getopt.h>
#include <Eigen/Core>
#include "Nifti/Nifti.h"
#include "QUIT/MultiArray.h"
#include "QUIT/Util.h"
using namespace std;
using namespace Eigen;
using namespace QUIT;
const string usage = "niinudge - A utility for moving Nifti images in physical space.\n\
\n\
Usage: niinudge [options] file1 [other files]\n\
By default nothing happens. Specify one of the options to move your image.\n\
Many of the options require a 3 dimensional vector argument. Valid formats for\n\
this are:\n\
X Y Z - Make sure you encase this format in quotes (\" \")!\n\
\n\
Options:\n\
--tfm, -t : Output an Insight Transform file for ANTs\n\
--out, -o prefix : Add a prefix to the output filenames\n\
--nudge, -n \"X Y Z\" : Nudge the image (X Y Z added to current offset)\n\
--offset, -f \"X Y Z\" : Set the offset to (X,Y,Z)\n\
--cog, -c : Move the Center of Gravity to the origin of the\n\
first image, and make subsequent images match\n\
--verbose, -v : Print out what the program is doing\n\
-h, --help: Print this message and quit.\n\
";
static const struct option long_opts[] = {
{"tfm", no_argument, 0, 't'},
{"nudge", required_argument, 0, 'n'},
{"out", required_argument, 0, 'o'},
{"offset", required_argument, 0, 'f'},
{"cog", no_argument, 0, 'c'},
{"verbose", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
static const char *short_opts = "tn:o:f:cvh";
static string prefix;
static int verbose = false, output_transform = false;
Vector3f calc_cog(Nifti::File &f);
Vector3f calc_cog(Nifti::File &f) {
const auto dims = f.matrix();
MultiArray<float, 3> a(dims);
f.open(f.imagePath(), Nifti::Mode::Read);
f.readVolumes(a.begin(), a.end(), 0, 1);
Vector3f cog = Vector3f::Zero();
float mass = 0.;
for (size_t k = 0; k < dims[2]; k++) {
for (size_t j = 0; j < dims[1]; j++) {
for (size_t i = 0; i < dims[0]; i++) {
float val = a[{i,j,k}];
if (isfinite(val)) {
cog += val * Vector3f(i,j,k);
mass += val;
}
}
}
}
cog /= mass;
if (verbose) cout << "CoG in voxels: " << cog.transpose() << ", mass: " << mass << endl;
cog = f.header().transform() * cog;
if (verbose) cout << "CoG in space: " << cog.transpose() << endl;
f.close();
return cog;
}
void write_transform(const Affine3f &tfm, const string path);
void write_transform(const Affine3f &tfm, const string path){
ofstream file(path);
IOFormat fmt(StreamPrecision, DontAlignCols);
file << "#Insight Transform File V1.0" << endl;
file << "# Transform 0" << endl;
file << "Transform: MatrixOffsetTransformBase_double_3_3" << endl;
file << "Parameters: " << tfm.matrix().block<1,3>(0,0).format(fmt)
<< " " << tfm.matrix().block<1,3>(1,0).format(fmt)
<< " " << tfm.matrix().block<1,3>(2,0).format(fmt)
<< " " << tfm.translation().matrix().transpose().format(fmt) << endl;
file << "FixedParameters: 0 0 0" << endl;
file.close();
}
int main(int argc, char **argv) {
// Make a first pass to permute the options and get filenames at the end
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {
switch (c) {
case 't': output_transform = true; break;
case 'o': prefix = optarg; break;
case 'v': verbose = true; break;
case '?': // getopt will print an error message
case 'h':
cout << usage << endl;
return EXIT_FAILURE;
default:
break;
}
}
if ((argc - optind) <= 0 ) {
cerr << "No input image file specified." << endl;
cout << usage << endl;
return EXIT_FAILURE;
}
vector<Nifti::File> files;
vector<vector<char>> data;
files.reserve(argc - optind);
data.reserve(argc - optind);
while (optind < argc) {
files.emplace_back(Nifti::File(argv[optind++], Nifti::Mode::Read));
Nifti::File &f = files.back();
if (verbose) cout << "Opened file: " << f.imagePath() << endl;
data.emplace_back(vector<char>(f.dataSize()));
f.readBytes(data.back());
f.close();
}
optind = 1;
while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {
Vector3f nudge;
switch (c) {
case 'n':
ReadEigen(optarg, nudge);
for (Nifti::File &f : files) {
if (verbose) cout << "Nudging offset by: " << nudge.transpose() << " in file: " << f.imagePath() << endl;
Nifti::Header h = f.header();
Affine3f xfm = h.transform();
xfm = Translation3f(nudge) * xfm;
h.setTransform(xfm);
f.setHeader(h);
}
break;
case 'f':
ReadEigen(optarg, nudge);
for (Nifti::File &f : files) {
if (verbose) cout << "Setting offset to: " << nudge.transpose() << " in file: " << f.imagePath() << endl;
Nifti::Header h = f.header();
Affine3f xfm = h.transform();
xfm.translation() = nudge;
h.setTransform(xfm);
f.setHeader(h);
}
break;
case 'c': {
if (verbose) cout << "Aligning origin to CoG in file: " << files.front().imagePath() << endl;
Vector3f CoG = calc_cog(files.front());
if (output_transform) {
Affine3f tfm(Translation3f(-CoG));
write_transform(tfm, files.front().basePath()+".tfm");
} else {
Affine3f xfm1 = files.front().header().transform();
xfm1 = Translation3f(-CoG) * xfm1;
Vector3f offset = xfm1.translation();
for (Nifti::File &f : files) {
Nifti::Header h = f.header();
Affine3f xfm = h.transform();
xfm.translation() = offset;
h.setTransform(xfm);
f.setHeader(h);
}
}
} break;
case '?': // getopt will print an error message
case 'h':
break;
default:
break;
}
}
auto f = files.begin();
auto d = data.begin();
for (; f != files.end(); f++, d++) {
string outpath = prefix + f->imagePath();
if (verbose) cout << "Writing file: " << outpath << endl;
f->open(outpath, Nifti::Mode::Write);
f->writeBytes(*d);
f->close();
}
return EXIT_SUCCESS;
}
<commit_msg>Rewrote niinudge to only work on one file at a time and include rotations.<commit_after>/*
* niinudge.cpp
*
* Copyright (c) 2014 Tobias Wood.
*
* 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/.
*
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <getopt.h>
#include <Eigen/Core>
#include "Nifti/Nifti.h"
#include "QUIT/MultiArray.h"
#include "QUIT/Util.h"
using namespace std;
using namespace Eigen;
using namespace QUIT;
const string usage = "niinudge - A utility for moving Nifti images in physical space.\n\
\n\
Usage: niinudge [options] infile outfile\n\
By default nothing happens. Specify one of the options to move your image.\n\
Many of the options require a 3 dimensional vector argument. Valid formats for\n\
this are:\n\
X Y Z - Make sure you encase this format in quotes (\" \")!\n\
\n\
Options:\n\
--nudge, -n \"X Y Z\" : Nudge the image (X Y Z added to current offset)\n\
--offset, -f \"X Y Z\" : Set the offset to (X,Y,Z)\n\
--cog, -c : Move the Center of Gravity to the origin of the\n\
first image, and make subsequent images match\n\
--rotate, -r \"X/Y/Z a\" : Rotate about specifed axis by specified angle\n\
--verbose, -v : Print out what the program is doing\n\
-h, --help : Print this message and quit.\n\
";
static const struct option long_opts[] = {
{"nudge", required_argument, 0, 'n'},
{"offset", required_argument, 0, 'f'},
{"cog", no_argument, 0, 'c'},
{"rotate", required_argument, 0, 'r'},
{"verbose", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
static const char *short_opts = "n:o:f:cr:vh";
static string prefix;
static int verbose = false, output_transform = false;
Vector3f calc_cog(Nifti::File &f);
Vector3f calc_cog(Nifti::File &f) {
const auto dims = f.matrix();
MultiArray<float, 3> a(dims);
f.open(f.imagePath(), Nifti::Mode::Read);
f.readVolumes(a.begin(), a.end(), 0, 1);
Vector3f cog = Vector3f::Zero();
float mass = 0.;
for (size_t k = 0; k < dims[2]; k++) {
for (size_t j = 0; j < dims[1]; j++) {
for (size_t i = 0; i < dims[0]; i++) {
float val = a[{i,j,k}];
if (isfinite(val)) {
cog += val * Vector3f(i,j,k);
mass += val;
}
}
}
}
cog /= mass;
if (verbose) cout << "CoG in voxels: " << cog.transpose() << ", mass: " << mass << endl;
cog = f.header().transform() * cog;
if (verbose) cout << "CoG in space: " << cog.transpose() << endl;
f.close();
return cog;
}
void write_transform(const Affine3f &tfm, const string path);
void write_transform(const Affine3f &tfm, const string path){
ofstream file(path);
IOFormat fmt(StreamPrecision, DontAlignCols);
file << "#Insight Transform File V1.0" << endl;
file << "# Transform 0" << endl;
file << "Transform: MatrixOffsetTransformBase_double_3_3" << endl;
file << "Parameters: " << tfm.matrix().block<1,3>(0,0).format(fmt)
<< " " << tfm.matrix().block<1,3>(1,0).format(fmt)
<< " " << tfm.matrix().block<1,3>(2,0).format(fmt)
<< " " << tfm.translation().matrix().transpose().format(fmt) << endl;
file << "FixedParameters: 0 0 0" << endl;
file.close();
}
int main(int argc, char **argv) {
// Make a first pass to permute the options and get filenames at the end
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case '?': // getopt will print an error message
case 'h':
cout << usage << endl;
return EXIT_FAILURE;
default:
break;
}
}
if ((argc - optind) <= 0 ) {
cerr << "No input image file specified." << endl;
cout << usage << endl;
return EXIT_FAILURE;
}
string inFilename(argv[optind++]);
string outFilename(argv[optind++]);
if (verbose) cout << "Opening input file: " << inFilename << endl;
Nifti::File inFile(inFilename);
// Now reset optind and process options
optind = 1;
Nifti::Header hdr = inFile.header();
Affine3f xfm = hdr.transform();
if (verbose) cout << "Initial transform: " << endl << xfm.matrix() << endl;
while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {
switch (c) {
case 'n': {
Vector3f nudge;
ReadEigen(optarg, nudge);
if (verbose) cout << "Nudging by: " << nudge.transpose() << endl;
xfm = Translation3f(nudge) * xfm;
} break;
case 'f': {
Vector3f nudge;
ReadEigen(optarg, nudge);
if (verbose) cout << "Setting offset to: " << nudge.transpose() << endl;
xfm.translation() = nudge;
} break;
case 'c': {
if (verbose) cout << "Aligning origin to CoG." << endl;
Vector3f CoG = calc_cog(inFile);
xfm = Translation3f(-CoG) * xfm;
} break;
case 'r': {
stringstream args{string{optarg}};
string axis; args >> axis;
float angle; args >> angle;
if (verbose) cout << "Rotating image by " << angle << " around " << axis << " axis." << endl;
if (axis == "X") {
xfm = AngleAxisf(angle * M_PI / 180., Vector3f::UnitX()) * xfm;
} else if (axis == "Y") {
xfm = AngleAxisf(angle * M_PI / 180., Vector3f::UnitY()) * xfm;
} else if (axis == "Z") {
xfm = AngleAxisf(angle * M_PI / 180., Vector3f::UnitZ()) * xfm;
} else {
throw(runtime_error("Invalid axis specification: " + axis));
}
} break;
}
}
if (verbose) cout << "Final transform: " << endl << xfm.matrix() << endl;
vector<char> data(inFile.dataSize());
inFile.readBytes(data);
if (verbose) cout << "Writing file: " << outFilename << endl;
hdr.setTransform(xfm);
Nifti::File outFile(hdr, outFilename, inFile.extensions());
outFile.writeBytes(data);
inFile.close();
outFile.close();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//
// ControlPrinter.cpp
// Tonic
//
// Created by Morgan Packard on 4/28/13.
//
#include "ControlPrinter.h"
namespace Tonic { namespace Tonic_{
ControlPrinter_::ControlPrinter_()
:message("%f\n"), hasPrinted(false){
}
void ControlPrinter_::setMessage(string messageArg){
message = messageArg + "\n";
}
} // Namespace Tonic_
} // Namespace Tonic
<commit_msg>More verbose message to ControlPrinter.<commit_after>//
// ControlPrinter.cpp
// Tonic
//
// Created by Morgan Packard on 4/28/13.
//
#include "ControlPrinter.h"
namespace Tonic { namespace Tonic_{
ControlPrinter_::ControlPrinter_()
:message("%f\n"), hasPrinted(false){
}
void ControlPrinter_::setMessage(string messageArg){
message = "Tonic::ControlPrinter message:" + messageArg + "\n";
}
} // Namespace Tonic_
} // Namespace Tonic
<|endoftext|> |
<commit_before>#include <list>
#include <iostream>
#include <string>
#include <regex>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/stat.h>
#include "log.h"
#include "crawler.h"
#include "strexception.h"
#include "tld.h"
// thanks [http://myregexp.com/examples.html]
std::regex Crawler::domain_regex("(([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6})");
inline bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
void Crawler::setCallback(DomainFoundFunc cb) {
df_callback = cb;
}
CURL* Crawler::init_curl() {
CURL *curl = curl_easy_init();
if(!curl)
throw StringException("Could not initialize curl");
}
void Crawler::make_dir(std::string name) {
const int err = mkdir(name.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if(err == -1 && errno != EEXIST) {
throw StringException(std::string("Could not create string ").append(name));
}
}
void Crawler::make_dir_struct(std::string path, std::string domain, int lvl) {
std::string cur = path;
if(domain.length() < lvl) {
make_dir(cur.append("/").append(domain));
return;
}
for(int i = 0; i < lvl; i++) {
const char* c = domain.substr(i, 1).c_str();
switch(c[0]) {
case '.':
continue;
break;
}
cur.append("/").append(c);
make_dir(cur);
}
}
std::string Crawler::get_dir_struct(std::string path, std::string domain, int lvl) {
std::string cur = path;
if(domain.length() < lvl)
return cur.append("/").append(domain);
for(int i = 0; i < lvl; i++) {
const char* c = domain.substr(i, 1).c_str();
switch(c[0]) {
case '.':
continue;
break;
}
cur.append("/").append(c);
}
return cur;
}
static size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
static size_t write_data_var(void *ptr, size_t size, size_t nmemb, void *usr) {
size_t real = size * nmemb;
((std::string*)usr)->append((char*)ptr, real);
return real;
}
void Crawler::crawl(std::string domain) {
download_robots(domain);
parse_domains(domain);
}
bool Crawler::domain_is_valid(std::string domain) {
for(const auto &c_tld : Tld::tlds) {
if(ends_with(domain, c_tld)) {
LOG << "Domain " << domain << " ends with " << c_tld << std::endl;
return true;
}
}
LOG << "Domain " << domain << " seems to be invalid" << std::endl;
return false;
}
bool Crawler::domain_is_new(std::string domain) {
std::string fname = get_dir_struct(std::string(OUTPUT_DIR), domain, DIR_STRUCT_LEVEL).append("/").append(domain);
LOG << "Checking if " << fname << " exists...";
struct stat buffer;
bool res = (stat (fname.c_str(), &buffer) == 0);
if(res)
LOG_INTERNAL << "yes";
else
LOG_INTERNAL << "no";
LOG_INTERNAL << std::endl;
return !res;
}
void Crawler::new_domain(std::string domain) {
// TODO: add logpool
LOG << "New domain found: " << domain << std::endl;
download_robots(domain);
if(df_callback)
df_callback(domain);
}
void Crawler::parse_domains(std::string domain) {
LOG << "Searching index of " << domain << " for new domains" << std::endl;
std::string url = domain;
url.append(INDEX_URL);
CURL *curl = init_curl();
std::string buffer;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_var);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "robot-farmer V0.1");
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::smatch domain_match;
const std::sregex_token_iterator end;
for (std::sregex_token_iterator i(buffer.cbegin(), buffer.cend(), domain_regex);
i != end;
++i)
{
LOG << "Checking domain " << *i << std::endl;
if(domain_is_new(*i)) {
if(domain_is_valid(*i)) {
LOG << "Calling new_domain" << std::endl;
new_domain(*i);
}
}
}
}
void Crawler::download_robots(std::string domain) {
LOG << "Downloading robots.txt from " << domain << std::endl;
std::string url = domain;
url.append(ROBOTS_TXT_URL);
#if FILE_OUTPUT
make_dir(std::string(OUTPUT_DIR));
make_dir_struct(std::string(OUTPUT_DIR), domain, DIR_STRUCT_LEVEL);
std::string fname = get_dir_struct(std::string(OUTPUT_DIR), domain, DIR_STRUCT_LEVEL).append("/").append(domain);
const char* filename = fname.c_str();
FILE *fp = fopen(filename, "wb");
if(!fp)
throw StringException(std::string("Could not open output file ").append(filename));
#endif
CURL *curl = init_curl();
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "robot-farmer V0.1");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
#if FILE_OUTPUT
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
#else
std::string buffer;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_var);
#endif
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
#if FILE_OUTPUT
fclose(fp);
#endif
}
<commit_msg>Changed error handling<commit_after>#include <list>
#include <iostream>
#include <string>
#include <regex>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/stat.h>
#include "log.h"
#include "crawler.h"
#include "strexception.h"
#include "tld.h"
// thanks [http://myregexp.com/examples.html]
std::regex Crawler::domain_regex("(([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6})");
inline bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
void Crawler::setCallback(DomainFoundFunc cb) {
df_callback = cb;
}
CURL* Crawler::init_curl() {
CURL *curl = curl_easy_init();
if(!curl)
throw StringException("Could not initialize curl");
}
void Crawler::make_dir(std::string name) {
const int err = mkdir(name.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if(err == -1 && errno != EEXIST) {
throw StringException(std::string("Could not create string ").append(name));
}
}
void Crawler::make_dir_struct(std::string path, std::string domain, int lvl) {
std::string cur = path;
if(domain.length() < lvl) {
make_dir(cur.append("/").append(domain));
return;
}
for(int i = 0; i < lvl; i++) {
const char* c = domain.substr(i, 1).c_str();
switch(c[0]) {
case '.':
case '\0':
continue;
break;
}
cur.append("/").append(c);
make_dir(cur);
}
}
std::string Crawler::get_dir_struct(std::string path, std::string domain, int lvl) {
std::string cur = path;
if(domain.length() < lvl)
return cur.append("/").append(domain);
for(int i = 0; i < lvl; i++) {
const char* c = domain.substr(i, 1).c_str();
switch(c[0]) {
case '.':
case '\0':
continue;
break;
}
cur.append("/").append(c);
}
return cur;
}
static size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
static size_t write_data_var(void *ptr, size_t size, size_t nmemb, void *usr) {
size_t real = size * nmemb;
((std::string*)usr)->append((char*)ptr, real);
return real;
}
void Crawler::crawl(std::string domain) {
download_robots(domain);
parse_domains(domain);
}
bool Crawler::domain_is_valid(std::string domain) {
for(const auto &c_tld : Tld::tlds) {
if(ends_with(domain, c_tld)) {
LOG << "Domain " << domain << " ends with " << c_tld << std::endl;
return true;
}
}
LOG << "Domain " << domain << " seems to be invalid" << std::endl;
return false;
}
bool Crawler::domain_is_new(std::string domain) {
std::string fname = get_dir_struct(std::string(OUTPUT_DIR), domain, DIR_STRUCT_LEVEL).append("/").append(domain);
LOG << "Checking if " << fname << " exists...";
struct stat buffer;
bool res = (stat (fname.c_str(), &buffer) == 0);
if(res)
LOG_INTERNAL << "yes";
else
LOG_INTERNAL << "no";
LOG_INTERNAL << std::endl;
return !res;
}
void Crawler::new_domain(std::string domain) {
// TODO: add logpool
LOG << "New domain found: " << domain << std::endl;
download_robots(domain);
if(df_callback)
df_callback(domain);
}
void Crawler::parse_domains(std::string domain) {
LOG << "Searching index of " << domain << " for new domains" << std::endl;
std::string url = domain;
url.append(INDEX_URL);
CURL *curl = init_curl();
std::string buffer;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_var);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "robot-farmer V0.1");
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::smatch domain_match;
const std::sregex_token_iterator end;
for (std::sregex_token_iterator i(buffer.cbegin(), buffer.cend(), domain_regex);
i != end;
++i)
{
LOG << "Checking domain " << *i << std::endl;
if(domain_is_new(*i)) {
if(domain_is_valid(*i)) {
LOG << "Calling new_domain" << std::endl;
new_domain(*i);
}
}
}
}
void Crawler::download_robots(std::string domain) {
LOG << "Downloading robots.txt from " << domain << std::endl;
std::string url = domain;
url.append(ROBOTS_TXT_URL);
#if FILE_OUTPUT
make_dir(std::string(OUTPUT_DIR));
make_dir_struct(std::string(OUTPUT_DIR), domain, DIR_STRUCT_LEVEL);
std::string fname = get_dir_struct(std::string(OUTPUT_DIR), domain, DIR_STRUCT_LEVEL).append("/").append(domain);
const char* filename = fname.c_str();
FILE *fp = fopen(filename, "wb");
if(!fp) {
LOG << "Could not open output file " << filename;
return;
}
#endif
CURL *curl = init_curl();
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "robot-farmer V0.1");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
#if FILE_OUTPUT
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
#else
std::string buffer;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_var);
#endif
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
#if FILE_OUTPUT
fclose(fp);
#endif
}
<|endoftext|> |
<commit_before><commit_msg>The initial value for PRODUCT should obviously be one, not zero<commit_after><|endoftext|> |
<commit_before>/*
* Contact groups model
* This file is based on TelepathyQt4Yell Models
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "groups-model.h"
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/PendingReady>
#include "groups-model-item.h"
#include "proxy-tree-node.h"
#include "accounts-model.h"
#include "contact-model-item.h"
#include <KDebug>
#include <KGlobal>
#include <KLocale>
#include <KLocalizedString>
struct GroupsModel::Private
{
Private(AccountsModel *am)
: mAM(am)
{
KGlobal::locale()->insertCatalog(QLatin1String("telepathy-common-internals"));
m_ungroupedString = i18n("Ungrouped");
}
TreeNode *node(const QModelIndex &index) const;
AccountsModel *mAM;
TreeNode *mTree;
///translated string for 'Ungrouped'
QString m_ungroupedString;
};
TreeNode *GroupsModel::Private::node(const QModelIndex &index) const
{
TreeNode *node = reinterpret_cast<TreeNode *>(index.internalPointer());
return node ? node : mTree;
}
GroupsModel::GroupsModel(AccountsModel *am, QObject *parent)
: QAbstractItemModel(parent),
mPriv(new GroupsModel::Private(am))
{
mPriv->mTree = new TreeNode;
connect(mPriv->mTree,
SIGNAL(changed(TreeNode*)),
SLOT(onItemChanged(TreeNode*)));
connect(mPriv->mTree,
SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
SLOT(onItemsAdded(TreeNode*,QList<TreeNode*>)));
connect(mPriv->mTree,
SIGNAL(childrenRemoved(TreeNode*,int,int)),
SLOT(onItemsRemoved(TreeNode*,int,int)));
loadAccountsModel();
QHash<int, QByteArray> roles;
roles[GroupNameRole] = "groupName";
setRoleNames(roles);
}
GroupsModel::~GroupsModel()
{
delete mPriv->mTree;
delete mPriv;
}
int GroupsModel::columnCount(const QModelIndex &parent) const
{
return 1;
}
int GroupsModel::rowCount(const QModelIndex &parent) const
{
return mPriv->node(parent)->size();
}
QVariant GroupsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
return mPriv->node(index)->data(role);
}
Qt::ItemFlags GroupsModel::flags(const QModelIndex &index) const
{
if (index.isValid()) {
bool isGroup = index.data(AccountsModel::ItemRole).userType() == qMetaTypeId<GroupsModelItem*>();
if (isGroup) {
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;
} else {
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
}
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
Qt::DropActions GroupsModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
QStringList GroupsModel::mimeTypes() const
{
QStringList types;
types << "application/vnd.telepathy.contact";
return types;
}
QMimeData* GroupsModel::mimeData(const QModelIndexList& indexes) const
{
QMimeData *mimeData = new QMimeData();
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (const QModelIndex &index, indexes) {
if (index.isValid()) {
ContactModelItem *c = data(index, AccountsModel::ItemRole).value<ContactModelItem*>();
//We put a contact ID and its account ID to the stream, so we can later recreate the contact using AccountsModel
stream << c->contact().data()->id() << mPriv->mAM->accountForContactItem(c).data()->objectPath();
}
}
mimeData->setData("application/vnd.telepathy.contact", encodedData);
return mimeData;
}
bool GroupsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent)
{
if (action == Qt::IgnoreAction) {
return true;
}
if (!data->hasFormat("application/vnd.telepathy.contact")) {
return false;
}
if (column > 0) {
return false;
}
QByteArray encodedData = data->data("application/vnd.telepathy.contact");
QDataStream stream(&encodedData, QIODevice::ReadOnly);
QList<ContactModelItem*> contacts;
while (!stream.atEnd()) {
QString contact;
QString account;
//get contact and account out of the stream
stream >> contact >> account;
Tp::AccountPtr accountPtr = mPriv->mAM->accountPtrForPath(account);
//casted pointer is checked below, before first use
contacts.append(qobject_cast<ContactModelItem*>(mPriv->mAM->contactItemForId(accountPtr->uniqueIdentifier(), contact)));
}
foreach (ContactModelItem *contact, contacts) {
Q_ASSERT(contact);
QString group = parent.data(GroupsModel::GroupNameRole).toString();
kDebug() << contact->contact().data()->alias() << "added to group" << group;
if (group != m_ungroupedString) {
//FIXME: Should we connect this somewhere?
Tp::PendingOperation *op = contact->contact().data()->manager().data()->addContactsToGroup(group,
QList<Tp::ContactPtr>() << contact->contact());
connect(op, SIGNAL(finished(Tp::PendingOperation*)),
this, SIGNAL(operationFinished(Tp::PendingOperation*)));
}
}
return true;
}
bool GroupsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid()) {
mPriv->node(index)->setData(role, value);
}
return false;
}
QModelIndex GroupsModel::index(int row, int column, const QModelIndex &parent) const
{
TreeNode *parentNode = mPriv->node(parent);
if (row < parentNode->size()) {
return createIndex(row, column, parentNode->childAt(row));
}
return QModelIndex();
}
QModelIndex GroupsModel::index(TreeNode *node) const
{
if (node->parent()) {
return createIndex(node->parent()->indexOf(node), 0, node);
} else {
return QModelIndex();
}
}
QModelIndex GroupsModel::parent(const QModelIndex &index) const
{
if (!index.isValid()) {
return QModelIndex();
}
TreeNode *currentNode = mPriv->node(index);
if (currentNode->parent()) {
return GroupsModel::index(currentNode->parent());
} else {
// no parent: return root node
return QModelIndex();
}
}
void GroupsModel::onItemChanged(TreeNode* node)
{
if (node->parent()) {
//if it is a group item
if (node->parent() == mPriv->mTree) {
GroupsModelItem *groupItem = qobject_cast<GroupsModelItem*>(node);
Q_ASSERT(groupItem);
groupItem->countOnlineContacts();
} else {
GroupsModelItem *groupItem = qobject_cast<GroupsModelItem*>(node->parent());
Q_ASSERT(groupItem);
groupItem->countOnlineContacts();
emit dataChanged(index(node->parent()), index(node->parent()));
}
}
emit dataChanged(index(node), index(node));
}
void GroupsModel::onItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
QModelIndex parentIndex = index(parent);
int currentSize = rowCount(parentIndex);
beginInsertRows(parentIndex, currentSize, currentSize + nodes.size() - 1);
foreach (TreeNode *node, nodes) {
parent->addChild(node);
}
endInsertRows();
}
void GroupsModel::onItemsRemoved(TreeNode *parent, int first, int last)
{
kDebug();
QModelIndex parentIndex = index(parent);
QList<TreeNode *> removedItems;
beginRemoveRows(parentIndex, first, last);
for (int i = last; i >= first; i--) {
parent->childAt(i)->remove();
}
endRemoveRows();
onItemChanged(parent);
}
void GroupsModel::onSourceItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
kDebug() << "Adding" << nodes.size() << "nodes...";
QModelIndex parentIndex = index(parent);
int currentSize = rowCount(parentIndex);
foreach (TreeNode *node, nodes) {
ContactModelItem *contactItem = qobject_cast<ContactModelItem*>(node);
QStringList groups = contactItem->contact()->groups();
addContactToGroups(contactItem, groups);
}
}
void GroupsModel::onSourceItemsRemoved(TreeNode* parent, int first, int last)
{
}
void GroupsModel::loadAccountsModel()
{
for (int x = 0; x < mPriv->mAM->rowCount(); x++) {
QModelIndex parent = mPriv->mAM->index(x, 0);
for (int i = 0; i < mPriv->mAM->rowCount(parent); i++) {
if (mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>()) {
QStringList groups = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
AccountsModel::GroupsRole).toStringList();
ContactModelItem *contactItem = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
AccountsModel::ItemRole).value<ContactModelItem*>();
addContactToGroups(contactItem, groups);
}
}
//we need to connect accounts onItemsAdded/onItemsRemoved to watch for changes
//and process them directly (directly add/remove the nodes)
AccountsModelItem *accountItem = mPriv->mAM->data(parent, AccountsModel::ItemRole).value<AccountsModelItem*>();
connect(accountItem, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
this, SLOT(onSourceItemsAdded(TreeNode*,QList<TreeNode*>)));
connect(accountItem, SIGNAL(childrenRemoved(TreeNode*,int,int)),
this, SLOT(onSourceItemsRemoved(TreeNode*,int,int)));
kDebug() << "Connecting" << accountItem->account()->displayName() << "to groups model";
}
}
void GroupsModel::onContactAddedToGroup(const QString& group)
{
addContactToGroups(qobject_cast<ProxyTreeNode*>(sender()), group);
}
void GroupsModel::onContactRemovedFromGroup(const QString& group)
{
removeContactFromGroup(qobject_cast<ProxyTreeNode*>(sender()), group);
}
void GroupsModel::removeContactFromGroup(ProxyTreeNode* proxyNode, const QString& group)
{
QStringList contactGroups = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->groups();
contactGroups.removeOne(group);
//if the contact really is in that group, remove it
if (qobject_cast<GroupsModelItem*>(proxyNode->parent())->groupName() == group) {
disconnect(proxyNode, SIGNAL(contactAddedToGroup(QString)), 0, 0);
disconnect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), 0, 0);
//if the the contact has no groups left, then put it in Ungrouped group
if (contactGroups.isEmpty()) {
addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), contactGroups);
}
qobject_cast<GroupsModelItem*>(proxyNode->parent())->removeProxyContact(proxyNode);
ContactModelItem *contactItem = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>();
Q_ASSERT(contactItem);
contactItem->contact().data()->manager().data()->removeContactsFromGroup(group, QList<Tp::ContactPtr>() << contactItem->contact());
}
}
void GroupsModel::addContactToGroups(ProxyTreeNode* proxyNode, const QString& group)
{
addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), group);
}
void GroupsModel::addContactToGroups(ContactModelItem* contactItem, const QString& group)
{
addContactToGroups(contactItem, QStringList(group));
}
void GroupsModel::addContactToGroups(ContactModelItem* contactItem, QStringList groups)
{
//check if the contact is in Ungrouped group, if it is, it needs to be removed from there
bool checkUngrouped = false;
//if the contact has no groups, create an 'Ungrouped' group for it
if (groups.isEmpty()) {
groups.append(m_ungroupedString);
} else {
checkUngrouped = true;
}
groups.removeDuplicates();
foreach (const QString &group, groups) {
bool groupExists = false;
GroupsModelItem *groupItem;
//check if the group already exists first
for (int i = 0; i < mPriv->mTree->children().size(); i++) {
GroupsModelItem *savedGroupItem = qobject_cast<GroupsModelItem*>(mPriv->mTree->childAt(i));
if (savedGroupItem->groupName() == group) {
groupExists = true;
groupItem = savedGroupItem;
if (!checkUngrouped) {
break;
}
}
if (checkUngrouped) {
if (savedGroupItem->groupName() == m_ungroupedString) {
for (int i = 0; i < savedGroupItem->size(); i++) {
ProxyTreeNode *tmpNode = qobject_cast<ProxyTreeNode*>(savedGroupItem->childAt(i));
if (tmpNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->id() == contactItem->contact()->id()) {
removeContactFromGroup(tmpNode, m_ungroupedString);
if (groupExists) {
break;
}
}
}
}
}
}
if (!groupExists) {
groupItem = new GroupsModelItem(group);
onItemsAdded(mPriv->mTree, QList<TreeNode *>() << groupItem);
}
ProxyTreeNode *proxyNode = new ProxyTreeNode(contactItem);
groupItem->addProxyContact(proxyNode);
connect(proxyNode, SIGNAL(contactAddedToGroup(QString)),
this, SLOT(onContactAddedToGroup(QString)));
connect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)),
this, SLOT(onContactRemovedFromGroup(QString)));
}
}
<commit_msg>Fix usage of m_ungroupedString var<commit_after>/*
* Contact groups model
* This file is based on TelepathyQt4Yell Models
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "groups-model.h"
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/PendingReady>
#include "groups-model-item.h"
#include "proxy-tree-node.h"
#include "accounts-model.h"
#include "contact-model-item.h"
#include <KDebug>
#include <KGlobal>
#include <KLocale>
#include <KLocalizedString>
struct GroupsModel::Private
{
Private(AccountsModel *am)
: mAM(am)
{
KGlobal::locale()->insertCatalog(QLatin1String("telepathy-common-internals"));
m_ungroupedString = i18n("Ungrouped");
}
TreeNode *node(const QModelIndex &index) const;
AccountsModel *mAM;
TreeNode *mTree;
///translated string for 'Ungrouped'
QString m_ungroupedString;
};
TreeNode *GroupsModel::Private::node(const QModelIndex &index) const
{
TreeNode *node = reinterpret_cast<TreeNode *>(index.internalPointer());
return node ? node : mTree;
}
GroupsModel::GroupsModel(AccountsModel *am, QObject *parent)
: QAbstractItemModel(parent),
mPriv(new GroupsModel::Private(am))
{
mPriv->mTree = new TreeNode;
connect(mPriv->mTree,
SIGNAL(changed(TreeNode*)),
SLOT(onItemChanged(TreeNode*)));
connect(mPriv->mTree,
SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
SLOT(onItemsAdded(TreeNode*,QList<TreeNode*>)));
connect(mPriv->mTree,
SIGNAL(childrenRemoved(TreeNode*,int,int)),
SLOT(onItemsRemoved(TreeNode*,int,int)));
loadAccountsModel();
QHash<int, QByteArray> roles;
roles[GroupNameRole] = "groupName";
setRoleNames(roles);
}
GroupsModel::~GroupsModel()
{
delete mPriv->mTree;
delete mPriv;
}
int GroupsModel::columnCount(const QModelIndex &parent) const
{
return 1;
}
int GroupsModel::rowCount(const QModelIndex &parent) const
{
return mPriv->node(parent)->size();
}
QVariant GroupsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
return mPriv->node(index)->data(role);
}
Qt::ItemFlags GroupsModel::flags(const QModelIndex &index) const
{
if (index.isValid()) {
bool isGroup = index.data(AccountsModel::ItemRole).userType() == qMetaTypeId<GroupsModelItem*>();
if (isGroup) {
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;
} else {
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
}
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
Qt::DropActions GroupsModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
QStringList GroupsModel::mimeTypes() const
{
QStringList types;
types << "application/vnd.telepathy.contact";
return types;
}
QMimeData* GroupsModel::mimeData(const QModelIndexList& indexes) const
{
QMimeData *mimeData = new QMimeData();
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (const QModelIndex &index, indexes) {
if (index.isValid()) {
ContactModelItem *c = data(index, AccountsModel::ItemRole).value<ContactModelItem*>();
//We put a contact ID and its account ID to the stream, so we can later recreate the contact using AccountsModel
stream << c->contact().data()->id() << mPriv->mAM->accountForContactItem(c).data()->objectPath();
}
}
mimeData->setData("application/vnd.telepathy.contact", encodedData);
return mimeData;
}
bool GroupsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent)
{
if (action == Qt::IgnoreAction) {
return true;
}
if (!data->hasFormat("application/vnd.telepathy.contact")) {
return false;
}
if (column > 0) {
return false;
}
QByteArray encodedData = data->data("application/vnd.telepathy.contact");
QDataStream stream(&encodedData, QIODevice::ReadOnly);
QList<ContactModelItem*> contacts;
while (!stream.atEnd()) {
QString contact;
QString account;
//get contact and account out of the stream
stream >> contact >> account;
Tp::AccountPtr accountPtr = mPriv->mAM->accountPtrForPath(account);
//casted pointer is checked below, before first use
contacts.append(qobject_cast<ContactModelItem*>(mPriv->mAM->contactItemForId(accountPtr->uniqueIdentifier(), contact)));
}
foreach (ContactModelItem *contact, contacts) {
Q_ASSERT(contact);
QString group = parent.data(GroupsModel::GroupNameRole).toString();
kDebug() << contact->contact().data()->alias() << "added to group" << group;
if (group != mPriv->m_ungroupedString) {
//FIXME: Should we connect this somewhere?
Tp::PendingOperation *op = contact->contact().data()->manager().data()->addContactsToGroup(group,
QList<Tp::ContactPtr>() << contact->contact());
connect(op, SIGNAL(finished(Tp::PendingOperation*)),
this, SIGNAL(operationFinished(Tp::PendingOperation*)));
}
}
return true;
}
bool GroupsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid()) {
mPriv->node(index)->setData(role, value);
}
return false;
}
QModelIndex GroupsModel::index(int row, int column, const QModelIndex &parent) const
{
TreeNode *parentNode = mPriv->node(parent);
if (row < parentNode->size()) {
return createIndex(row, column, parentNode->childAt(row));
}
return QModelIndex();
}
QModelIndex GroupsModel::index(TreeNode *node) const
{
if (node->parent()) {
return createIndex(node->parent()->indexOf(node), 0, node);
} else {
return QModelIndex();
}
}
QModelIndex GroupsModel::parent(const QModelIndex &index) const
{
if (!index.isValid()) {
return QModelIndex();
}
TreeNode *currentNode = mPriv->node(index);
if (currentNode->parent()) {
return GroupsModel::index(currentNode->parent());
} else {
// no parent: return root node
return QModelIndex();
}
}
void GroupsModel::onItemChanged(TreeNode* node)
{
if (node->parent()) {
//if it is a group item
if (node->parent() == mPriv->mTree) {
GroupsModelItem *groupItem = qobject_cast<GroupsModelItem*>(node);
Q_ASSERT(groupItem);
groupItem->countOnlineContacts();
} else {
GroupsModelItem *groupItem = qobject_cast<GroupsModelItem*>(node->parent());
Q_ASSERT(groupItem);
groupItem->countOnlineContacts();
emit dataChanged(index(node->parent()), index(node->parent()));
}
}
emit dataChanged(index(node), index(node));
}
void GroupsModel::onItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
QModelIndex parentIndex = index(parent);
int currentSize = rowCount(parentIndex);
beginInsertRows(parentIndex, currentSize, currentSize + nodes.size() - 1);
foreach (TreeNode *node, nodes) {
parent->addChild(node);
}
endInsertRows();
}
void GroupsModel::onItemsRemoved(TreeNode *parent, int first, int last)
{
kDebug();
QModelIndex parentIndex = index(parent);
QList<TreeNode *> removedItems;
beginRemoveRows(parentIndex, first, last);
for (int i = last; i >= first; i--) {
parent->childAt(i)->remove();
}
endRemoveRows();
onItemChanged(parent);
}
void GroupsModel::onSourceItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes)
{
kDebug() << "Adding" << nodes.size() << "nodes...";
QModelIndex parentIndex = index(parent);
int currentSize = rowCount(parentIndex);
foreach (TreeNode *node, nodes) {
ContactModelItem *contactItem = qobject_cast<ContactModelItem*>(node);
QStringList groups = contactItem->contact()->groups();
addContactToGroups(contactItem, groups);
}
}
void GroupsModel::onSourceItemsRemoved(TreeNode* parent, int first, int last)
{
}
void GroupsModel::loadAccountsModel()
{
for (int x = 0; x < mPriv->mAM->rowCount(); x++) {
QModelIndex parent = mPriv->mAM->index(x, 0);
for (int i = 0; i < mPriv->mAM->rowCount(parent); i++) {
if (mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>()) {
QStringList groups = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
AccountsModel::GroupsRole).toStringList();
ContactModelItem *contactItem = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent),
AccountsModel::ItemRole).value<ContactModelItem*>();
addContactToGroups(contactItem, groups);
}
}
//we need to connect accounts onItemsAdded/onItemsRemoved to watch for changes
//and process them directly (directly add/remove the nodes)
AccountsModelItem *accountItem = mPriv->mAM->data(parent, AccountsModel::ItemRole).value<AccountsModelItem*>();
connect(accountItem, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)),
this, SLOT(onSourceItemsAdded(TreeNode*,QList<TreeNode*>)));
connect(accountItem, SIGNAL(childrenRemoved(TreeNode*,int,int)),
this, SLOT(onSourceItemsRemoved(TreeNode*,int,int)));
kDebug() << "Connecting" << accountItem->account()->displayName() << "to groups model";
}
}
void GroupsModel::onContactAddedToGroup(const QString& group)
{
addContactToGroups(qobject_cast<ProxyTreeNode*>(sender()), group);
}
void GroupsModel::onContactRemovedFromGroup(const QString& group)
{
removeContactFromGroup(qobject_cast<ProxyTreeNode*>(sender()), group);
}
void GroupsModel::removeContactFromGroup(ProxyTreeNode* proxyNode, const QString& group)
{
QStringList contactGroups = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->groups();
contactGroups.removeOne(group);
//if the contact really is in that group, remove it
if (qobject_cast<GroupsModelItem*>(proxyNode->parent())->groupName() == group) {
disconnect(proxyNode, SIGNAL(contactAddedToGroup(QString)), 0, 0);
disconnect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), 0, 0);
//if the the contact has no groups left, then put it in Ungrouped group
if (contactGroups.isEmpty()) {
addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), contactGroups);
}
qobject_cast<GroupsModelItem*>(proxyNode->parent())->removeProxyContact(proxyNode);
ContactModelItem *contactItem = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>();
Q_ASSERT(contactItem);
contactItem->contact().data()->manager().data()->removeContactsFromGroup(group, QList<Tp::ContactPtr>() << contactItem->contact());
}
}
void GroupsModel::addContactToGroups(ProxyTreeNode* proxyNode, const QString& group)
{
addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), group);
}
void GroupsModel::addContactToGroups(ContactModelItem* contactItem, const QString& group)
{
addContactToGroups(contactItem, QStringList(group));
}
void GroupsModel::addContactToGroups(ContactModelItem* contactItem, QStringList groups)
{
//check if the contact is in Ungrouped group, if it is, it needs to be removed from there
bool checkUngrouped = false;
//if the contact has no groups, create an 'Ungrouped' group for it
if (groups.isEmpty()) {
groups.append(mPriv->m_ungroupedString);
} else {
checkUngrouped = true;
}
groups.removeDuplicates();
foreach (const QString &group, groups) {
bool groupExists = false;
GroupsModelItem *groupItem;
//check if the group already exists first
for (int i = 0; i < mPriv->mTree->children().size(); i++) {
GroupsModelItem *savedGroupItem = qobject_cast<GroupsModelItem*>(mPriv->mTree->childAt(i));
if (savedGroupItem->groupName() == group) {
groupExists = true;
groupItem = savedGroupItem;
if (!checkUngrouped) {
break;
}
}
if (checkUngrouped) {
if (savedGroupItem->groupName() == mPriv->m_ungroupedString) {
for (int i = 0; i < savedGroupItem->size(); i++) {
ProxyTreeNode *tmpNode = qobject_cast<ProxyTreeNode*>(savedGroupItem->childAt(i));
if (tmpNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->id() == contactItem->contact()->id()) {
removeContactFromGroup(tmpNode, mPriv->m_ungroupedString);
if (groupExists) {
break;
}
}
}
}
}
}
if (!groupExists) {
groupItem = new GroupsModelItem(group);
onItemsAdded(mPriv->mTree, QList<TreeNode *>() << groupItem);
}
ProxyTreeNode *proxyNode = new ProxyTreeNode(contactItem);
groupItem->addProxyContact(proxyNode);
connect(proxyNode, SIGNAL(contactAddedToGroup(QString)),
this, SLOT(onContactAddedToGroup(QString)));
connect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)),
this, SLOT(onContactRemovedFromGroup(QString)));
}
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreRenderingModule.h"
#include <Ogre.h>
namespace OgreRenderer
{
OgreMaterialResource::OgreMaterialResource(const std::string& id) :
ResourceInterface(id)
{
}
OgreMaterialResource::OgreMaterialResource(const std::string& id, Foundation::AssetPtr source) :
ResourceInterface(id)
{
SetData(source);
}
OgreMaterialResource::~OgreMaterialResource()
{
RemoveMaterial();
}
bool OgreMaterialResource::SetData(Foundation::AssetPtr source)
{
if (!source)
{
OgreRenderingModule::LogError("Null source asset data pointer");
return false;
}
if (!source->GetSize())
{
OgreRenderingModule::LogError("Zero sized material asset");
return false;
}
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
try
{
Ogre::MaterialManager::getSingleton().parseScript(data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::MaterialManager::getSingleton().create(source->GetId(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
OgreRenderingModule::LogDebug("Ogre material " + id_ + " created");
} catch (Ogre::Exception &e)
{
OgreRenderingModule::LogWarning(e.what());
OgreRenderingModule::LogWarning("Failed to parse Ogre material " + id_ + ".");
}
return true;
}
static const std::string type_name("OgreMaterial");
const std::string& OgreMaterialResource::GetType() const
{
return type_name;
}
const std::string& OgreMaterialResource::GetTypeStatic()
{
return type_name;
}
void OgreMaterialResource::RemoveMaterial()
{
if (!ogre_material_.isNull())
{
std::string material_name = ogre_material_->getName();
ogre_material_.setNull();
try
{
Ogre::MaterialManager::getSingleton().remove(material_name);
}
catch (...)
{
OgreRenderingModule::LogDebug("Warning: Ogre::MaterialManager::getSingleton().remove(material_name); failed in OgreMaterialResource.cpp.");
}
}
}
}<commit_msg>OgreMaterialResource::SetData() now properly returns false if material parsing or creation fails for some reason.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreRenderingModule.h"
#include <Ogre.h>
namespace OgreRenderer
{
OgreMaterialResource::OgreMaterialResource(const std::string& id) :
ResourceInterface(id)
{
}
OgreMaterialResource::OgreMaterialResource(const std::string& id, Foundation::AssetPtr source) :
ResourceInterface(id)
{
SetData(source);
}
OgreMaterialResource::~OgreMaterialResource()
{
RemoveMaterial();
}
bool OgreMaterialResource::SetData(Foundation::AssetPtr source)
{
if (!source)
{
OgreRenderingModule::LogError("Null source asset data pointer");
return false;
}
if (!source->GetSize())
{
OgreRenderingModule::LogError("Zero sized material asset");
return false;
}
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
try
{
Ogre::MaterialManager::getSingleton().parseScript(data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::MaterialManager::getSingleton().create(source->GetId(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
OgreRenderingModule::LogDebug("Ogre material " + id_ + " created");
} catch (Ogre::Exception &e)
{
OgreRenderingModule::LogWarning(e.what());
OgreRenderingModule::LogWarning("Failed to parse Ogre material " + id_ + ".");
return false;
}
return true;
}
static const std::string type_name("OgreMaterial");
const std::string& OgreMaterialResource::GetType() const
{
return type_name;
}
const std::string& OgreMaterialResource::GetTypeStatic()
{
return type_name;
}
void OgreMaterialResource::RemoveMaterial()
{
if (!ogre_material_.isNull())
{
std::string material_name = ogre_material_->getName();
ogre_material_.setNull();
try
{
Ogre::MaterialManager::getSingleton().remove(material_name);
}
catch (...)
{
OgreRenderingModule::LogDebug("Warning: Ogre::MaterialManager::getSingleton().remove(material_name); failed in OgreMaterialResource.cpp.");
}
}
}
}<|endoftext|> |
<commit_before>#include "ToolBase.h"
#include "TSVFileStream.h"
#include "Helper.h"
#include "BasicStatistics.h"
#include <QFileInfo>
#include <QBitArray>
class ConcreteTool
: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
ops << ">" << ">=" << "=" << "<=" << "<" << "is" << "contains";
}
virtual void setup()
{
setDescription("Filters the rows of a TSV file according to the value of a specific column.");
addString("filter", "Filter string with column name, operation and value,e.g. 'depth > 17'.\nValid operations are '" + ops.join("','") + "'.", false);
//optional
addInfile("in", "Input TSV file. If unset, reads from STDIN.", true);
addOutfile("out", "Output TSV file. If unset, writes to STDOUT.", true);
addFlag("numeric", "If set, column name is interpreted as a 1-based column number.");
addFlag("v", "Invert filter.");
}
virtual void main()
{
//init
QString in = getInfile("in");
QString out = getOutfile("out");
if(in!="" && in==out)
{
THROW(ArgumentException, "Input and output files must be different when streaming!");
}
TSVFileStream instream(in);
QSharedPointer<QFile> outstream = Helper::openFileForWriting(out, true);
bool v = getFlag("v");
//split filter
QString filter = getString("filter");
QStringList parts = filter.split(" ");
if (parts.count()<3)
{
THROW(CommandLineParsingException, "Could not split filter '" + filter + "' in three or more parts (by space)!");
}
//re-join string values with spaces
while(parts.count()>3)
{
int count = parts.count();
parts[count-2] += " " +parts[count];
parts.removeLast();
}
//check column
QVector<int> cols = instream.checkColumns(parts[0].toLatin1().split(','), getFlag("numeric"));
if (cols.count()!=1)
{
THROW(CommandLineParsingException, "Could not determine column name/index '" + parts[0] + "'!");
}
int col = cols[0];
//check operation
QByteArray op = parts[1].toLatin1();
int op_index = ops.indexOf(op);
if(op_index==-1)
{
THROW(CommandLineParsingException, "Invalid operation '" + op + "'!");
}
//check value
QByteArray value = parts[2].toLatin1();
double value_num = 0;
if (op_index<5)
{
if(!BasicStatistics::isValidFloat(value))
{
THROW(CommandLineParsingException, "Non-numeric filter value '" + value + "' for numeric filter operation '" + op + " given!");
}
value_num = value.toDouble();
}
//write comments
foreach (QByteArray comment, instream.comments())
{
outstream->write(comment);
outstream->write("\n");
}
//write header
const int col_count = instream.header().count();
outstream->write("#");
for(int i=0; i<col_count; ++i)
{
outstream->write(instream.header()[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
//write content
while(!instream.atEnd())
{
QList<QByteArray> parts = instream.readLine();
if (parts.count()==0) continue;
QByteArray value2 = parts[col];
double value2_num = 0;
if (op_index<5)
{
bool ok = true;
value2_num = value2.toDouble(&ok);
if (!ok)
{
THROW(CommandLineParsingException, "Non-numeric value '" + value2 + "' for numeric filter operation '" + op + " in line " + QString::number(instream.lineIndex()+1) + "!");
}
}
bool pass_filter = true;
switch(op_index)
{
case 0: //">"
pass_filter = value2_num>value_num;
break;
case 1: //">="
pass_filter = value2_num>=value_num;
break;
case 2: //"="
pass_filter = value2_num==value_num;
break;
case 3: //"<="
pass_filter = value2_num<=value_num;
break;
case 4: //"<"
pass_filter = value2_num<value_num;
break;
case 5: //"is"
pass_filter = value2 == value;
break;
case 6: //"contains"
pass_filter = value2.contains(value);
break;
default:
THROW(ProgrammingException, "Invalid filter operation index " + QString::number(op_index) + "!");
};
if ((!v && !pass_filter) || (v && pass_filter))
{
continue;
}
for(int i=0; i<col_count; ++i)
{
outstream->write(parts[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
}
}
//valid operations list
QStringList ops;
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<commit_msg>src/TsvFilter/main.cpp: Bugfix: Fixed support for values with spaces<commit_after>#include "ToolBase.h"
#include "TSVFileStream.h"
#include "Helper.h"
#include "BasicStatistics.h"
#include <QFileInfo>
#include <QBitArray>
class ConcreteTool
: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
ops << ">" << ">=" << "=" << "<=" << "<" << "is" << "contains";
}
virtual void setup()
{
setDescription("Filters the rows of a TSV file according to the value of a specific column.");
addString("filter", "Filter string with column name, operation and value,e.g. 'depth > 17'.\nValid operations are '" + ops.join("','") + "'.", false);
//optional
addInfile("in", "Input TSV file. If unset, reads from STDIN.", true);
addOutfile("out", "Output TSV file. If unset, writes to STDOUT.", true);
addFlag("numeric", "If set, column name is interpreted as a 1-based column number.");
addFlag("v", "Invert filter.");
}
virtual void main()
{
//init
QString in = getInfile("in");
QString out = getOutfile("out");
if(in!="" && in==out)
{
THROW(ArgumentException, "Input and output files must be different when streaming!");
}
TSVFileStream instream(in);
QSharedPointer<QFile> outstream = Helper::openFileForWriting(out, true);
bool v = getFlag("v");
//split filter
QString filter = getString("filter");
QStringList parts = filter.split(" ");
if (parts.count()<3)
{
THROW(CommandLineParsingException, "Could not split filter '" + filter + "' in three or more parts (by space)!");
}
//re-join string values with spaces
while(parts.count()>3)
{
int count = parts.count();
parts[count-2] += " " +parts[count-1];
parts.removeLast();
}
//check column
QVector<int> cols = instream.checkColumns(parts[0].toLatin1().split(','), getFlag("numeric"));
if (cols.count()!=1)
{
THROW(CommandLineParsingException, "Could not determine column name/index '" + parts[0] + "'!");
}
int col = cols[0];
//check operation
QByteArray op = parts[1].toLatin1();
int op_index = ops.indexOf(op);
if(op_index==-1)
{
THROW(CommandLineParsingException, "Invalid operation '" + op + "'!");
}
//check value
QByteArray value = parts[2].toLatin1();
double value_num = 0;
if (op_index<5)
{
if(!BasicStatistics::isValidFloat(value))
{
THROW(CommandLineParsingException, "Non-numeric filter value '" + value + "' for numeric filter operation '" + op + " given!");
}
value_num = value.toDouble();
}
//write comments
foreach (QByteArray comment, instream.comments())
{
outstream->write(comment);
outstream->write("\n");
}
//write header
const int col_count = instream.header().count();
outstream->write("#");
for(int i=0; i<col_count; ++i)
{
outstream->write(instream.header()[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
qDebug() << parts[0] << " " << op << " " << parts[2];
//write content
while(!instream.atEnd())
{
QList<QByteArray> parts = instream.readLine();
if (parts.count()==0) continue;
QByteArray value2 = parts[col];
double value2_num = 0;
if (op_index<5)
{
bool ok = true;
value2_num = value2.toDouble(&ok);
if (!ok)
{
THROW(CommandLineParsingException, "Non-numeric value '" + value2 + "' for numeric filter operation '" + op + " in line " + QString::number(instream.lineIndex()+1) + "!");
}
}
bool pass_filter = true;
switch(op_index)
{
case 0: //">"
pass_filter = value2_num>value_num;
break;
case 1: //">="
pass_filter = value2_num>=value_num;
break;
case 2: //"="
pass_filter = value2_num==value_num;
break;
case 3: //"<="
pass_filter = value2_num<=value_num;
break;
case 4: //"<"
pass_filter = value2_num<value_num;
break;
case 5: //"is"
pass_filter = value2 == value;
break;
case 6: //"contains"
pass_filter = value2.contains(value);
break;
default:
THROW(ProgrammingException, "Invalid filter operation index " + QString::number(op_index) + "!");
};
if ((!v && !pass_filter) || (v && pass_filter))
{
continue;
}
for(int i=0; i<col_count; ++i)
{
outstream->write(parts[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
}
}
//valid operations list
QStringList ops;
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<|endoftext|> |
<commit_before>#include "VirtualMachine.h"
VirtualMachine::VirtualMachine()
{
//ctor
stackSize = 0;
}
VirtualMachine::~VirtualMachine()
{
//dtor
}
void VirtualMachine::interpret(unsigned char bytecode[], int byteSize)
{
for(int a = 0; a < byteSize; a++)
{
int currentInstruction = bytecode[a];
switch(currentInstruction)
{
case Instruction::CONSOLE_OUT:
{
Type variable = pop();
switch(variable.type)
{
case DataType::INT:
std::cout << variable.intData;
break;
case DataType::CHAR:
std::cout << variable.charData;
break;
case DataType::BOOL:
std::cout << variable.boolData;
break;
case DataType::STRING:
std::cout << *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_OUT, Unknown data type '" + std::to_string(variable.type) + "'"));
}
}
break;
case Instruction::CREATE_INT:
push_integer(bytecode[++a]);
break;
case Instruction::CREATE_CHAR:
push_char(bytecode[++a]);
break;
case Instruction::CREATE_BOOL:
push_bool(bytecode[++a]);
break;
case Instruction::CREATE_STRING:
{
unsigned int stringSize = bytecode[++a]; //String length stored in next byte
std::string wholeString;
wholeString.resize(stringSize);
for(unsigned int cChar = 0; cChar < stringSize; cChar++) //Read in the string from the bytecode into the allocated memory
wholeString[cChar] = bytecode[++a];
push_string(wholeString); //Push the resulting char*
break;
}
case Instruction::GOTO:
a = static_cast<int>(bytecode[a+1])-1;
break;
case Instruction::CONSOLE_IN:
{
Type &variable = stack[bytecode[++a]];
switch(variable.type)
{
case DataType::INT:
std::cin >> variable.intData;
break;
case DataType::CHAR:
std::cin >> variable.charData;
break;
case DataType::BOOL:
std::cin >> variable.boolData;
break;
case DataType::STRING:
std::cin >> *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_IN, Unknown data type '" + std::to_string(variable.type) + "'"));
}
break;
}
case Instruction::MATH_ADD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result += *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_SUBTRACT:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result -= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MULTIPLY:
{
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result *= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_DIVIDE:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result /= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MOD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
{
result %= *iter;
}
push_integer(result); //Push the result to the stack
break;
}
case Instruction::CLONE_TOP:
{
push_type(stack[bytecode[++a]]); //Clone a variable from a position in the stack to the top of the stack
break;
}
case Instruction::CONCENTRATE_STRINGS:
{
//Pop strings off first that need to be concentrated
unsigned int numberOfStrings = bytecode[++a];
std::string stringBuffer;
std::vector<std::string> poppedStrings;
for(unsigned int a = 0; a < numberOfStrings; a++)
poppedStrings.emplace_back(*pop().stringData);
//Now add the strings to a buffer in reverse, as we need the first one to be first in the string, not last
for(auto iter = poppedStrings.rbegin(); iter != poppedStrings.rend(); iter++)
stringBuffer += *iter;
//Push to stack
push_string(stringBuffer);
break;
}
case Instruction::COMPARE_EQUAL:
{
unsigned int compareCount = bytecode[++a]; //Number of things to compare
if(isEqual({pop(), pop()}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::CONDITIONAL_IF:
{
//Move bytecode offset to the one specified in the bytecode.
//bytecode[a+1] = position to set if false
Type val = pop();
if(val.type != DataType::BOOL)
{
throwError(std::string("Can't convert type " + std::to_string(val.type) + " to boolean for comparison"));
}
if(!val.boolData)
{
a = bytecode[a+1];
}
else //Else move past the false position and continue running the bytecode
{
a++;
}
break;
}
case Instruction::SET_VARIABLE:
{
Type val = pop(); //Value to set it to
unsigned int variableStackOffset = bytecode[++a]; //Find which variable to set
stack[variableStackOffset] = val; //Update the value
break;
}
case Instruction::COMPARE_UNEQUAL: //Compares last two things on the stack, returns true if they don't match
{
a++; //Skip number of things to compare, not currently used
if(!isEqual({pop(), pop()}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_LESS_THAN:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(!isLessThan(v1, v2) && !isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_MORE_THAN:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(isLessThan(v1, v2) && !isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_MORE_THAN_OR_EQUAL:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(isLessThan(v1, v2) || isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_LESS_THAN_OR_EQUAL:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(!isLessThan(v1, v2) || isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_AND:
{
std::cout << "\nCompare &&";
break;
}
default:
throwError("Unknown instruction '" + std::to_string(currentInstruction) + "'");
}
}
}
bool VirtualMachine::isLessThan(const Type& v1, const Type& v2)
{
//Ensure that they're the same type or the union comparison will screw up
if(v2.type != v1.type)
{
throwError("Can't compare different data types!");
}
//Compare different things depending on the variable types
switch(v1.type)
{
case INT:
if(v1.intData < v2.intData)
return true;
else
return false;
break;
case CHAR:
if(v1.charData < v2.charData)
return true;
else
return false;
break;
case STRING:
if(v1.stringData->size() < v2.stringData->size())
return true;
else
return false;
break;
case BOOL:
if(v1.boolData < v2.boolData)
return true;
else
return false;
default:
throwError("Internal error, attempt to compare unknown data type");
}
throwError("Internal error, isEqual comparison failed for unknown reason");
return false;
}
bool VirtualMachine::isEqual(const std::vector<Type> &vals)
{
//Ensure that they're the same type or the union comparison will screw up
DataType commonType = vals[0].type;
for(unsigned int a = 1; a < vals.size(); a++)
{
if(vals[a].type != commonType)
throwError("Can't compare different data types!");
}
//Temp
Type v1 = vals[0];
Type v2 = vals[1];
//Compare different things depending on the variable types
switch(v1.type)
{
case INT:
if(v1.intData == v2.intData)
return true;
else
return false;
break;
case CHAR:
if(v1.charData == v2.charData)
return true;
else
return false;
break;
case STRING:
if(*v1.stringData == *v2.stringData)
return true;
else
return false;
break;
case BOOL:
if(v1.boolData == v2.boolData)
return true;
else
return false;
default:
throwError("Internal error, attempt to compare unknown data type");
}
throwError("Internal error, isEqual comparison failed for unknown reason");
return false;
}
void VirtualMachine::push_integer(int value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_char(unsigned char value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_bool(bool value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_string(const std::string &value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_type(Type value)
{
pushStackCheck();
stack[stackSize++] = value;
}
Type VirtualMachine::pop()
{
popStackCheck();
return stack[--stackSize];
}
void VirtualMachine::popStackCheck()
{
if(stackSize == 0)
{
throwError("\nCouldn't pop from stack, stack empty!");
}
}
void VirtualMachine::pushStackCheck()
{
if(stackSize == maxStackSize)
{
throwError("\nCouldn't push to stack, stack full!");
}
}
void VirtualMachine::throwError(const std::string& reason)
{
throw std::string(reason);
}
<commit_msg>isEqual now supports multiple values to compare<commit_after>#include "VirtualMachine.h"
VirtualMachine::VirtualMachine()
{
//ctor
stackSize = 0;
}
VirtualMachine::~VirtualMachine()
{
//dtor
}
void VirtualMachine::interpret(unsigned char bytecode[], int byteSize)
{
for(int a = 0; a < byteSize; a++)
{
int currentInstruction = bytecode[a];
switch(currentInstruction)
{
case Instruction::CONSOLE_OUT:
{
Type variable = pop();
switch(variable.type)
{
case DataType::INT:
std::cout << variable.intData;
break;
case DataType::CHAR:
std::cout << variable.charData;
break;
case DataType::BOOL:
std::cout << variable.boolData;
break;
case DataType::STRING:
std::cout << *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_OUT, Unknown data type '" + std::to_string(variable.type) + "'"));
}
}
break;
case Instruction::CREATE_INT:
push_integer(bytecode[++a]);
break;
case Instruction::CREATE_CHAR:
push_char(bytecode[++a]);
break;
case Instruction::CREATE_BOOL:
push_bool(bytecode[++a]);
break;
case Instruction::CREATE_STRING:
{
unsigned int stringSize = bytecode[++a]; //String length stored in next byte
std::string wholeString;
wholeString.resize(stringSize);
for(unsigned int cChar = 0; cChar < stringSize; cChar++) //Read in the string from the bytecode into the allocated memory
wholeString[cChar] = bytecode[++a];
push_string(wholeString); //Push the resulting char*
break;
}
case Instruction::GOTO:
a = static_cast<int>(bytecode[a+1])-1;
break;
case Instruction::CONSOLE_IN:
{
Type &variable = stack[bytecode[++a]];
switch(variable.type)
{
case DataType::INT:
std::cin >> variable.intData;
break;
case DataType::CHAR:
std::cin >> variable.charData;
break;
case DataType::BOOL:
std::cin >> variable.boolData;
break;
case DataType::STRING:
std::cin >> *variable.stringData;
break;
default:
throwError(std::string("Failed to CONSOLE_IN, Unknown data type '" + std::to_string(variable.type) + "'"));
}
break;
}
case Instruction::MATH_ADD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result += *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_SUBTRACT:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result -= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MULTIPLY:
{
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result *= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_DIVIDE:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
result /= *iter;
push_integer(result); //Push the result to the stack
break;
}
case Instruction::MATH_MOD:
{
//TEMPORARY
unsigned int numberCount = bytecode[++a]; //Get number of bytes to subtract from bytecode
std::vector<int> values;
int result = 0;
for(unsigned int a = 0; a < numberCount; a++) //For the number of arguments specified, pop them all off the stack and subtract from 'result'
values.emplace_back(pop().intData);
result = values.back();
values.pop_back();
for(auto iter = values.rbegin(); iter != values.rend(); iter++)
{
result %= *iter;
}
push_integer(result); //Push the result to the stack
break;
}
case Instruction::CLONE_TOP:
{
push_type(stack[bytecode[++a]]); //Clone a variable from a position in the stack to the top of the stack
break;
}
case Instruction::CONCENTRATE_STRINGS:
{
//Pop strings off first that need to be concentrated
unsigned int numberOfStrings = bytecode[++a];
std::string stringBuffer;
std::vector<std::string> poppedStrings;
for(unsigned int a = 0; a < numberOfStrings; a++)
poppedStrings.emplace_back(*pop().stringData);
//Now add the strings to a buffer in reverse, as we need the first one to be first in the string, not last
for(auto iter = poppedStrings.rbegin(); iter != poppedStrings.rend(); iter++)
stringBuffer += *iter;
//Push to stack
push_string(stringBuffer);
break;
}
case Instruction::COMPARE_EQUAL:
{
unsigned int compareCount = bytecode[++a]; //Number of things to compare
std::vector<Type> thingsToCompare;
for(unsigned int a = 0; a < compareCount; a++)
thingsToCompare.emplace_back(pop());
push_bool(isEqual(thingsToCompare));
break;
}
case Instruction::CONDITIONAL_IF:
{
//Move bytecode offset to the one specified in the bytecode.
//bytecode[a+1] = position to set if false
Type val = pop();
if(val.type != DataType::BOOL)
{
throwError(std::string("Can't convert type " + std::to_string(val.type) + " to boolean for comparison"));
}
if(!val.boolData)
{
a = bytecode[a+1];
}
else //Else move past the false position and continue running the bytecode
{
a++;
}
break;
}
case Instruction::SET_VARIABLE:
{
Type val = pop(); //Value to set it to
unsigned int variableStackOffset = bytecode[++a]; //Find which variable to set
stack[variableStackOffset] = val; //Update the value
break;
}
case Instruction::COMPARE_UNEQUAL: //Compares last two things on the stack, returns true if they don't match
{
a++; //Skip number of things to compare, not currently used
if(!isEqual({pop(), pop()}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_LESS_THAN:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(!isLessThan(v1, v2) && !isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_MORE_THAN:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(isLessThan(v1, v2) && !isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_MORE_THAN_OR_EQUAL:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(isLessThan(v1, v2) || isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_LESS_THAN_OR_EQUAL:
{
a++; //Skip number of things to compare, not currently used
const Type &v1 = pop(), v2 = pop();
if(!isLessThan(v1, v2) || isEqual({v1, v2}))
push_bool(true);
else
push_bool(false);
break;
}
case Instruction::COMPARE_AND:
{
std::cout << "\nCompare &&";
break;
}
default:
throwError("Unknown instruction '" + std::to_string(currentInstruction) + "'");
}
}
}
bool VirtualMachine::isLessThan(const Type& v1, const Type& v2)
{
//Ensure that they're the same type or the union comparison will screw up
if(v2.type != v1.type)
{
throwError("Can't compare different data types!");
}
//Compare different things depending on the variable types
switch(v1.type)
{
case INT:
if(v1.intData < v2.intData)
return true;
else
return false;
break;
case CHAR:
if(v1.charData < v2.charData)
return true;
else
return false;
break;
case STRING:
if(v1.stringData->size() < v2.stringData->size())
return true;
else
return false;
break;
case BOOL:
if(v1.boolData < v2.boolData)
return true;
else
return false;
default:
throwError("Internal error, attempt to compare unknown data type");
}
throwError("Internal error, isEqual comparison failed for unknown reason");
return false;
}
bool VirtualMachine::isEqual(const std::vector<Type> &vals)
{
//Ensure that they're the same type or the union comparison will screw up
DataType commonType = vals[0].type;
for(unsigned int a = 1; a < vals.size(); a++)
{
if(vals[a].type != commonType)
throwError("Can't compare different data types!");
}
auto compare = [] (const Type &v1, const Type &v2) -> bool
{
//Compare different things depending on the variable types
switch(v1.type)
{
case INT:
if(v1.intData == v2.intData)
return true;
else
return false;
break;
case CHAR:
if(v1.charData == v2.charData)
return true;
else
return false;
break;
case STRING:
if(*v1.stringData == *v2.stringData)
return true;
else
return false;
break;
case BOOL:
if(v1.boolData == v2.boolData)
return true;
else
return false;
default:
return false;
}
return false;
};
//Compare the first value against the rest
for(unsigned int a = 1; a < vals.size(); a++)
{
if(!compare(vals[0], vals[a])) //If not matching
return false;
}
return true;
}
void VirtualMachine::push_integer(int value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_char(unsigned char value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_bool(bool value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_string(const std::string &value)
{
pushStackCheck();
stack[stackSize++] = Type(value);
}
void VirtualMachine::push_type(Type value)
{
pushStackCheck();
stack[stackSize++] = value;
}
Type VirtualMachine::pop()
{
popStackCheck();
return stack[--stackSize];
}
void VirtualMachine::popStackCheck()
{
if(stackSize == 0)
{
throwError("\nCouldn't pop from stack, stack empty!");
}
}
void VirtualMachine::pushStackCheck()
{
if(stackSize == maxStackSize)
{
throwError("\nCouldn't push to stack, stack full!");
}
}
void VirtualMachine::throwError(const std::string& reason)
{
throw std::string(reason);
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program 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 this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Declarations for unit tester interface.
*/
#ifndef NTA_TESTER_HPP
#define NTA_TESTER_HPP
//----------------------------------------------------------------------
#include "gtest/gtest.h"
#include <sstream>
#include <vector>
#include <cmath> // fabs
#include <nta/utils/Log.hpp>
//----------------------------------------------------------------------
namespace nta {
/** Abstract base class for unit testers.
*
* This class specifies a simple interface for unit testing all Numenta classes.
* A unit test is created by subclassing from Tester and implementing RunTests().
*
*/
class Tester {
public:
/** Default constructor */
Tester();
virtual ~Tester();
/// This is the main method that subclasses should implement.
/// It is expected that this method will thoroughly test the target class by calling
/// each method and testing boundary conditions.
/// @todo change capitalization. Must be changed in all tests.
virtual void RunTests() {}
static void init();
/*
* All tests have access to a standard input dir (read only) and output dir
* Make these static so that they can be accessed even if you don't have a tester object.
*/
static std::string testInputDir_;
static std::string testOutputDir_;
static std::string fromTestInputDir(const std::string& path);
static std::string fromTestOutputDir(const std::string& path);
private:
// Default copy ctor and assignment operator forbidden by default
Tester(const Tester&);
Tester& operator=(const Tester&);
}; // end class Tester
} // end namespace nta
#define TESTEQUAL(expected, actual) \
EXPECT_EQ(expected, actual);
#define TESTEQUAL_FLOAT(expected, actual) \
EXPECT_TRUE(::fabs(expected - actual) < 0.000001) << "assertion \"" << #expected " == " #actual << "\" failed at " << __FILE__ << ":" << __LINE__ ;
#define TESTEQUAL2(name, expected, actual) \
EXPECT_EQ(expected, actual) << "assertion \"" << #name << "\" failed at " << __FILE__ << ":" << __LINE__ ;
#undef TEST
#define TEST(condition)
EXPECT_TRUE(condition) << "assertion \"" << #condition << "\" failed at " << __FILE__ << ":" << __LINE__ ;
#define TEST2(name, condition)
EXPECT_TRUE(condition) << "assertion \"" << #name << ": " << #condition << "\" failed at " << __FILE__ << ":" << __LINE__ ;
// http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Exception_Assertions
#define SHOULDFAIL(statement) \
EXPECT_THROW(statement, std::exception);
// { \
// if (!disableNegativeTests_) \
// { \
// bool caughtException = false; \
// try { \
// statement; \
// } catch(std::exception& ) { \
// caughtException = true; \
// } \
// testEqual("statement '" #statement "' should fail", __FILE__, __LINE__, true, caughtException); \
// } else { \
// disable("statement '" #statement "' should fail", __FILE__, __LINE__); \
// } \
// }
#define SHOULDFAIL_WITH_MESSAGE(statement, message) \
{ \
bool caughtException = false; \
try { \
statement; \
} catch(nta::LoggingException& e) { \
caughtException = true; \
EXPECT_STREQ(message, e.getMessage()) << "statement '" #statement "' should fail with message \"" \
<< message << "\", but failed with message \"" << e.getMessage() << "\""; \
} catch(...) { \
FAIL() << "statement '" #statement "' did not generate a logging exception"; \
} \
EXPECT_EQ(true, caughtException) << "statement '" #statement "' should fail"; \
}
#define ADD_TEST(testname) \
GTEST_TEST(#testname "Case", #testname) { \
testname t; \
t.RunTests(); \
}
#endif // NTA_TESTER_HPP
<commit_msg>Correct the usage of #<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program 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 this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Declarations for unit tester interface.
*/
#ifndef NTA_TESTER_HPP
#define NTA_TESTER_HPP
//----------------------------------------------------------------------
#include "gtest/gtest.h"
#include <sstream>
#include <vector>
#include <cmath> // fabs
#include <nta/utils/Log.hpp>
//----------------------------------------------------------------------
namespace nta {
/** Abstract base class for unit testers.
*
* This class specifies a simple interface for unit testing all Numenta classes.
* A unit test is created by subclassing from Tester and implementing RunTests().
*
*/
class Tester {
public:
/** Default constructor */
Tester();
virtual ~Tester();
/// This is the main method that subclasses should implement.
/// It is expected that this method will thoroughly test the target class by calling
/// each method and testing boundary conditions.
/// @todo change capitalization. Must be changed in all tests.
virtual void RunTests() {}
static void init();
/*
* All tests have access to a standard input dir (read only) and output dir
* Make these static so that they can be accessed even if you don't have a tester object.
*/
static std::string testInputDir_;
static std::string testOutputDir_;
static std::string fromTestInputDir(const std::string& path);
static std::string fromTestOutputDir(const std::string& path);
private:
// Default copy ctor and assignment operator forbidden by default
Tester(const Tester&);
Tester& operator=(const Tester&);
}; // end class Tester
} // end namespace nta
#define TESTEQUAL(expected, actual) \
EXPECT_EQ(expected, actual);
#define TESTEQUAL_FLOAT(expected, actual) \
EXPECT_TRUE(::fabs(expected - actual) < 0.000001) << "assertion \"" #expected " == " #actual << "\" failed at " << __FILE__ << ":" << __LINE__ ;
#define TESTEQUAL2(name, expected, actual) \
EXPECT_EQ(expected, actual) << "assertion \"" #name "\" failed at " << __FILE__ << ":" << __LINE__ ;
#undef TEST
#define TEST(condition)
EXPECT_TRUE(condition) << "assertion \"" #condition "\" failed at " << __FILE__ << ":" << __LINE__ ;
#define TEST2(name, condition)
EXPECT_TRUE(condition) << "assertion \"" #name ": " #condition "\" failed at " << __FILE__ << ":" << __LINE__ ;
// http://code.google.com/p/googletest/wiki/V1_7_AdvancedGuide#Exception_Assertions
#define SHOULDFAIL(statement) \
EXPECT_THROW(statement, std::exception);
// { \
// if (!disableNegativeTests_) \
// { \
// bool caughtException = false; \
// try { \
// statement; \
// } catch(std::exception& ) { \
// caughtException = true; \
// } \
// testEqual("statement '" #statement "' should fail", __FILE__, __LINE__, true, caughtException); \
// } else { \
// disable("statement '" #statement "' should fail", __FILE__, __LINE__); \
// } \
// }
#define SHOULDFAIL_WITH_MESSAGE(statement, message) \
{ \
bool caughtException = false; \
try { \
statement; \
} catch(nta::LoggingException& e) { \
caughtException = true; \
EXPECT_STREQ(message, e.getMessage()) << "statement '" #statement "' should fail with message \"" \
<< message << "\", but failed with message \"" << e.getMessage() << "\""; \
} catch(...) { \
FAIL() << "statement '" #statement "' did not generate a logging exception"; \
} \
EXPECT_EQ(true, caughtException) << "statement '" #statement "' should fail"; \
}
#define ADD_TEST(testname) \
GTEST_TEST(#testname "Case", #testname) { \
testname t; \
t.RunTests(); \
}
#endif // NTA_TESTER_HPP
<|endoftext|> |
<commit_before>#include <stdafx.h>
#include "CDrawableBuilder.h"
void CDrawableBuilder::CDrawableRedable(CDrawableStruct* self) {
self->color = RGB(255, 0, 0);
}
void CDrawableBuilder::CDrawableDealloc(CDrawableStruct* self) {
Py_TYPE(self)->tp_free((PyObject*)self);
}
int CDrawableBuilder::CDrawableInit(CDrawableStruct *self, PyObject *args,
PyObject *kwds) {
static char *kwlist[] = { "color", "xPos", "yPos", "width", "heigh", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
&self->color, &self->xPos, &self->yPos, &self->width, &self->height)) {
return -1;
}
return 0;
}
PyMemberDef CDrawableBuilder::CDrawableMembers[] = {
{ "color", T_ULONG, offsetof(CDrawableStruct, color), 0, "color" },
{ "xPos", T_INT, offsetof(CDrawableStruct, xPos), 0, "xPos of left top corner" },
{ "yPos", T_INT, offsetof(CDrawableStruct, yPos), 0, "yPos of left top corner" },
{ "width", T_INT, offsetof(CDrawableStruct, width), 0, "width of rect" },
{ "heigh", T_INT, offsetof(CDrawableStruct, height), 0, "heigh of rect" },
{ NULL } /* Sentinel */
};
PyMethodDef CDrawableBuilder::CDrawableMethods[] = {
{ "Redable", (PyCFunction)CDrawableRedable, METH_VARARGS, "Make the object red" },
{ NULL } /* Sentinel */
};
PyTypeObject CDrawableBuilder::CDrawableType = {
PyVarObject_HEAD_INIT(NULL, 0)
"CDrawable", /* tp_name */
sizeof(CDrawableStruct), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)CDrawableDealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_GC, /* tp_flags */
"CDrawable objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
CDrawableMethods, /* tp_methods */
CDrawableMembers, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)CDrawableInit, /* tp_init */
};
CDrawableBuilder::CDrawableBuilder(std::shared_ptr<IDrawable> object) {
std::shared_ptr<CDrawable> castedObject =
std::static_pointer_cast<CDrawable>(object);
if (PyType_Ready(&CDrawableType) < 0) {
pObject = nullptr;
}
else {
RECT rect = object->GetContainingBox();
pObject = std::shared_ptr<PyObject>( (PyObject*)PyObject_NEW( CDrawableStruct, &CDrawableType ) );
PyObject* args = PyTuple_New(5);
PyTuple_SetItem(args, 0, PyLong_FromUnsignedLong(object->GetColor()));
PyTuple_SetItem(args, 1, PyLong_FromLong(rect.left));
PyTuple_SetItem(args, 2, PyLong_FromLong(rect.top));
PyTuple_SetItem(args, 3, PyLong_FromLong(rect.right - rect.left));
PyTuple_SetItem(args, 4, PyLong_FromLong(rect.bottom - rect.top));
PyObject* kwds = PyTuple_New(5);
PyTuple_SetItem(args, 0, PyUnicode_FromString("color"));
PyTuple_SetItem(args, 1, PyUnicode_FromString("xPos"));
PyTuple_SetItem(args, 2, PyUnicode_FromString("yPos"));
PyTuple_SetItem(args, 3, PyUnicode_FromString("width"));
PyTuple_SetItem(args, 4, PyUnicode_FromString("heigh"));
pObject->ob_type->tp_init(pObject.get(), args, kwds);
}
}
std::shared_ptr<PyObject> CDrawableBuilder::GetpObject() {
return pObject;
}
<commit_msg>Added decoder function prototype<commit_after>#include <stdafx.h>
#include "CDrawableBuilder.h"
void CDrawableBuilder::CDrawableRedable(CDrawableStruct* self) {
self->color = RGB(255, 0, 0);
}
void CDrawableBuilder::CDrawableDealloc(CDrawableStruct* self) {
Py_TYPE(self)->tp_free((PyObject*)self);
}
int CDrawableBuilder::CDrawableInit(CDrawableStruct *self, PyObject *args,
PyObject *kwds) {
static char *kwlist[] = { "color", "xPos", "yPos", "width", "heigh", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
&self->color, &self->xPos, &self->yPos, &self->width, &self->height)) {
return -1;
}
return 0;
}
PyMemberDef CDrawableBuilder::CDrawableMembers[] = {
{ "color", T_ULONG, offsetof(CDrawableStruct, color), 0, "color" },
{ "xPos", T_INT, offsetof(CDrawableStruct, xPos), 0, "xPos of left top corner" },
{ "yPos", T_INT, offsetof(CDrawableStruct, yPos), 0, "yPos of left top corner" },
{ "width", T_INT, offsetof(CDrawableStruct, width), 0, "width of rect" },
{ "heigh", T_INT, offsetof(CDrawableStruct, height), 0, "heigh of rect" },
{ NULL } /* Sentinel */
};
PyMethodDef CDrawableBuilder::CDrawableMethods[] = {
{ "Redable", (PyCFunction)CDrawableRedable, METH_VARARGS, "Make the object red" },
{ NULL } /* Sentinel */
};
PyTypeObject CDrawableBuilder::CDrawableType = {
PyVarObject_HEAD_INIT(NULL, 0)
"CDrawable", /* tp_name */
sizeof(CDrawableStruct), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)CDrawableDealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_GC, /* tp_flags */
"CDrawable objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
CDrawableMethods, /* tp_methods */
CDrawableMembers, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)CDrawableInit, /* tp_init */
};
CDrawableBuilder::CDrawableBuilder(std::shared_ptr<IDrawable> object) {
std::shared_ptr<CDrawable> castedObject =
std::static_pointer_cast<CDrawable>(object);
if (PyType_Ready(&CDrawableType) < 0) {
pObject = nullptr;
}
else {
RECT rect = object->GetContainingBox();
pObject = std::shared_ptr<PyObject>( (PyObject*)PyObject_NEW( CDrawableStruct, &CDrawableType ) );
PyObject* args = PyTuple_New(5);
PyTuple_SetItem(args, 0, PyLong_FromUnsignedLong(object->GetColor()));
PyTuple_SetItem(args, 1, PyLong_FromLong(rect.left));
PyTuple_SetItem(args, 2, PyLong_FromLong(rect.top));
PyTuple_SetItem(args, 3, PyLong_FromLong(rect.right - rect.left));
PyTuple_SetItem(args, 4, PyLong_FromLong(rect.bottom - rect.top));
PyObject* kwds = PyTuple_New(5);
PyTuple_SetItem(args, 0, PyUnicode_FromString("color"));
PyTuple_SetItem(args, 1, PyUnicode_FromString("xPos"));
PyTuple_SetItem(args, 2, PyUnicode_FromString("yPos"));
PyTuple_SetItem(args, 3, PyUnicode_FromString("width"));
PyTuple_SetItem(args, 4, PyUnicode_FromString("height"));
pObject->ob_type->tp_init(pObject.get(), args, kwds);
}
}
std::shared_ptr<PyObject> CDrawableBuilder::GetpObject() {
return pObject;
}
bool decoderAndSetter(PyObject* obj, std::shared_ptr<IDrawable> toChange)
{
int color, xPos, yPos, width, height;
if ( PyArg_ParseTuple(obj, "liii:decoder", &color, &xPos, &yPos, &width, &height) == 0)
{
return false;
}
toChange->SetColor(color);
RECT rect;
rect.top = yPos;
rect.left = xPos;
rect.bottom = rect.top + height;
rect.right = rect.left + width;
toChange->SetContainingBox(rect);
return true;
}<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Support.h"
#include "OgreLogManager.h"
namespace Ogre {
void GLES2Support::setConfigOption(const String &name, const String &value)
{
ConfigOptionMap::iterator it = mOptions.find(name);
if (it == mOptions.end())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Option named " + name + " does not exist.",
"GLESSupport::setConfigOption");
}
else
{
it->second.currentValue = value;
}
}
ConfigOptionMap& GLES2Support::getConfigOptions(void)
{
return mOptions;
}
void GLES2Support::initialiseExtensions(void)
{
// Set version string
const GLubyte* pcVer = glGetString(GL_VERSION);
assert(pcVer && "Problems getting GL version string using glGetString");
String tmpStr = (const char*)pcVer;
LogManager::getSingleton().logMessage("GL_VERSION = " + tmpStr);
mVersion = tmpStr.substr(0, tmpStr.find(" "));
// Get vendor
const GLubyte* pcVendor = glGetString(GL_VENDOR);
tmpStr = (const char*)pcVendor;
LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr);
mVendor = tmpStr.substr(0, tmpStr.find(" "));
// Get renderer
const GLubyte* pcRenderer = glGetString(GL_RENDERER);
tmpStr = (const char*)pcRenderer;
LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr);
// Set extension list
std::stringstream ext;
String str;
const GLubyte* pcExt = glGetString(GL_EXTENSIONS);
LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt));
assert(pcExt && "Problems getting GL extension string using glGetString");
ext << pcExt;
while (ext >> str)
{
LogManager::getSingleton().logMessage("EXT:" + str);
extensionList.insert(str);
}
// Get function pointers on platforms that don't have prototypes
#ifndef GL_GLEXT_PROTOTYPES
// define the GL types if they are not defined
# ifndef PFNGLMAPBUFFEROES
typedef void* (GL_APIENTRY *PFNGLMAPBUFFEROES)(GLenum target, GLenum access);
typedef GLboolean (GL_APIENTRY *PFNGLUNMAPBUFFEROES)(GLenum target);
# endif
# ifndef PFNGLDRAWBUFFERSARB
typedef void (GL_APIENTRY *PFNGLDRAWBUFFERSARB) (GLsizei n, const GLenum *bufs);
# endif
# ifndef PFNGLREADBUFFERNV
typedef void (GL_APIENTRY *PFNGLREADBUFFERNV) (GLenum mode);
# endif
# ifndef PFNGLGETTEXIMAGENV
typedef void (GL_APIENTRY *PFNGLGETTEXIMAGENV) (GLenum target, GLint level, GLenum format, GLenum type, GLvoid* img);
typedef void (GL_APIENTRY *PFNGLGETCOMPRESSEDTEXIMAGENV) (GLenum target, GLint level, GLvoid* img);
typedef void (GL_APIENTRY *PFNGLGETTEXLEVELPARAMETERFVNV) (GLenum target, GLint level, GLenum pname, GLfloat* params);
typedef void (GL_APIENTRY *PFNGLGETTEXLEVELPARAMETERiVNV) (GLenum target, GLint level, GLenum pname, GLint* params);
# endif
glMapBufferOES = (PFNGLMAPBUFFEROES)getProcAddress("glMapBufferOES");
glUnmapBufferOES = (PFNGLUNMAPBUFFEROES)getProcAddress("glUnmapBufferOES");
glDrawBuffersARB = (PFNGLDRAWBUFFERSARB)getProcAddress("glDrawBuffersARB");
glReadBufferNV = (PFNGLREADBUFFERNV)getProcAddress("glReadBufferNV");
glGetTexImageNV = (PFNGLGETTEXIMAGENV)getProcAddress("glGetTexImageNV");
glGetCompressedTexImageNV = (PFNGLGETCOMPRESSEDTEXIMAGENV)getProcAddress("glGetCompressedTexImageNV");
glGetTexLevelParameterfvNV = (PFNGLGETTEXLEVELPARAMETERFVNV)getProcAddress("glGetTexLevelParameterfvNV");
glGetTexLevelParameterivNV = (PFNGLGETTEXLEVELPARAMETERiVNV)getProcAddress("glGetTexLevelParameterivNV");
#endif
}
bool GLES2Support::checkExtension(const String& ext) const
{
if(extensionList.find(ext) == extensionList.end())
return false;
return true;
}
}
<commit_msg>Fix spelling error<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Support.h"
#include "OgreLogManager.h"
namespace Ogre {
void GLES2Support::setConfigOption(const String &name, const String &value)
{
ConfigOptionMap::iterator it = mOptions.find(name);
if (it == mOptions.end())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Option named " + name + " does not exist.",
"GLES2Support::setConfigOption");
}
else
{
it->second.currentValue = value;
}
}
ConfigOptionMap& GLES2Support::getConfigOptions(void)
{
return mOptions;
}
void GLES2Support::initialiseExtensions(void)
{
// Set version string
const GLubyte* pcVer = glGetString(GL_VERSION);
assert(pcVer && "Problems getting GL version string using glGetString");
String tmpStr = (const char*)pcVer;
LogManager::getSingleton().logMessage("GL_VERSION = " + tmpStr);
mVersion = tmpStr.substr(0, tmpStr.find(" "));
// Get vendor
const GLubyte* pcVendor = glGetString(GL_VENDOR);
tmpStr = (const char*)pcVendor;
LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr);
mVendor = tmpStr.substr(0, tmpStr.find(" "));
// Get renderer
const GLubyte* pcRenderer = glGetString(GL_RENDERER);
tmpStr = (const char*)pcRenderer;
LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr);
// Set extension list
std::stringstream ext;
String str;
const GLubyte* pcExt = glGetString(GL_EXTENSIONS);
LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt));
assert(pcExt && "Problems getting GL extension string using glGetString");
ext << pcExt;
while (ext >> str)
{
LogManager::getSingleton().logMessage("EXT:" + str);
extensionList.insert(str);
}
// Get function pointers on platforms that don't have prototypes
#ifndef GL_GLEXT_PROTOTYPES
// define the GL types if they are not defined
# ifndef PFNGLMAPBUFFEROES
typedef void* (GL_APIENTRY *PFNGLMAPBUFFEROES)(GLenum target, GLenum access);
typedef GLboolean (GL_APIENTRY *PFNGLUNMAPBUFFEROES)(GLenum target);
# endif
# ifndef PFNGLDRAWBUFFERSARB
typedef void (GL_APIENTRY *PFNGLDRAWBUFFERSARB) (GLsizei n, const GLenum *bufs);
# endif
# ifndef PFNGLREADBUFFERNV
typedef void (GL_APIENTRY *PFNGLREADBUFFERNV) (GLenum mode);
# endif
# ifndef PFNGLGETTEXIMAGENV
typedef void (GL_APIENTRY *PFNGLGETTEXIMAGENV) (GLenum target, GLint level, GLenum format, GLenum type, GLvoid* img);
typedef void (GL_APIENTRY *PFNGLGETCOMPRESSEDTEXIMAGENV) (GLenum target, GLint level, GLvoid* img);
typedef void (GL_APIENTRY *PFNGLGETTEXLEVELPARAMETERFVNV) (GLenum target, GLint level, GLenum pname, GLfloat* params);
typedef void (GL_APIENTRY *PFNGLGETTEXLEVELPARAMETERiVNV) (GLenum target, GLint level, GLenum pname, GLint* params);
# endif
glMapBufferOES = (PFNGLMAPBUFFEROES)getProcAddress("glMapBufferOES");
glUnmapBufferOES = (PFNGLUNMAPBUFFEROES)getProcAddress("glUnmapBufferOES");
glDrawBuffersARB = (PFNGLDRAWBUFFERSARB)getProcAddress("glDrawBuffersARB");
glReadBufferNV = (PFNGLREADBUFFERNV)getProcAddress("glReadBufferNV");
glGetTexImageNV = (PFNGLGETTEXIMAGENV)getProcAddress("glGetTexImageNV");
glGetCompressedTexImageNV = (PFNGLGETCOMPRESSEDTEXIMAGENV)getProcAddress("glGetCompressedTexImageNV");
glGetTexLevelParameterfvNV = (PFNGLGETTEXLEVELPARAMETERFVNV)getProcAddress("glGetTexLevelParameterfvNV");
glGetTexLevelParameterivNV = (PFNGLGETTEXLEVELPARAMETERiVNV)getProcAddress("glGetTexLevelParameterivNV");
#endif
}
bool GLES2Support::checkExtension(const String& ext) const
{
if(extensionList.find(ext) == extensionList.end())
return false;
return true;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.