text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Copyright (C) 2014 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:
*
* * 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 Google 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.
*/
#include "config.h"
#include "core/loader/WorkerLoaderClientBridgeSyncHelper.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerLoaderProxy.h"
#include "public/platform/WebWaitableEvent.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/Functional.h"
#include "wtf/MainThread.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
PassOwnPtr<WorkerLoaderClientBridgeSyncHelper> WorkerLoaderClientBridgeSyncHelper::create(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
{
return adoptPtr(new WorkerLoaderClientBridgeSyncHelper(client, event));
}
WorkerLoaderClientBridgeSyncHelper::~WorkerLoaderClientBridgeSyncHelper()
{
ASSERT(isMainThread());
for (size_t i = 0; i < m_receivedData.size(); ++i)
delete m_receivedData[i];
}
void WorkerLoaderClientBridgeSyncHelper::run()
{
// This must be called only after m_event is signalled.
ASSERT(m_done);
for (size_t i = 0; i < m_clientTasks.size(); ++i)
m_clientTasks[i]();
}
void WorkerLoaderClientBridgeSyncHelper::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didSendData, &m_client, bytesSent, totalBytesToBeSent));
}
static void didReceiveResponseAdapter(ThreadableLoaderClient* client, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
{
OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
client->didReceiveResponse(identifier, *response);
}
void WorkerLoaderClientBridgeSyncHelper::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&didReceiveResponseAdapter, &m_client, identifier, response.copyData()));
}
void WorkerLoaderClientBridgeSyncHelper::didReceiveData(const char* data, int dataLength)
{
ASSERT(isMainThread());
Vector<char>* buffer = new Vector<char>(dataLength);
memcpy(buffer->data(), data, dataLength);
m_receivedData.append(buffer);
m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveData, &m_client, static_cast<const char*>(buffer->data()), dataLength));
}
void WorkerLoaderClientBridgeSyncHelper::didDownloadData(int dataLength)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didDownloadData, &m_client, dataLength));
}
void WorkerLoaderClientBridgeSyncHelper::didReceiveCachedMetadata(const char* data, int dataLength)
{
ASSERT(isMainThread());
Vector<char>* buffer = new Vector<char>(dataLength);
memcpy(buffer->data(), data, dataLength);
m_receivedData.append(buffer);
m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveCachedMetadata, &m_client, static_cast<const char*>(buffer->data()), dataLength));
}
void WorkerLoaderClientBridgeSyncHelper::didFinishLoading(unsigned long identifier, double finishTime)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFinishLoading, &m_client, identifier, finishTime));
m_done = true;
m_event->signal();
}
void WorkerLoaderClientBridgeSyncHelper::didFail(const ResourceError& error)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFail, &m_client, error));
m_done = true;
m_event->signal();
}
void WorkerLoaderClientBridgeSyncHelper::didFailAccessControlCheck(const ResourceError& error)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFailAccessControlCheck, &m_client, error));
m_done = true;
m_event->signal();
}
void WorkerLoaderClientBridgeSyncHelper::didFailRedirectCheck()
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFailRedirectCheck, &m_client));
m_done = true;
m_event->signal();
}
WorkerLoaderClientBridgeSyncHelper::WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
: m_done(false)
, m_client(client)
, m_event(event)
{
ASSERT(m_event);
}
} // namespace WebCore
<commit_msg>Call ResourceError::copy() when passed across threads for thread safety.<commit_after>/*
* Copyright (C) 2014 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:
*
* * 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 Google 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.
*/
#include "config.h"
#include "core/loader/WorkerLoaderClientBridgeSyncHelper.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerLoaderProxy.h"
#include "public/platform/WebWaitableEvent.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/Functional.h"
#include "wtf/MainThread.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
PassOwnPtr<WorkerLoaderClientBridgeSyncHelper> WorkerLoaderClientBridgeSyncHelper::create(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
{
return adoptPtr(new WorkerLoaderClientBridgeSyncHelper(client, event));
}
WorkerLoaderClientBridgeSyncHelper::~WorkerLoaderClientBridgeSyncHelper()
{
ASSERT(isMainThread());
for (size_t i = 0; i < m_receivedData.size(); ++i)
delete m_receivedData[i];
}
void WorkerLoaderClientBridgeSyncHelper::run()
{
// This must be called only after m_event is signalled.
ASSERT(m_done);
for (size_t i = 0; i < m_clientTasks.size(); ++i)
m_clientTasks[i]();
}
void WorkerLoaderClientBridgeSyncHelper::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didSendData, &m_client, bytesSent, totalBytesToBeSent));
}
static void didReceiveResponseAdapter(ThreadableLoaderClient* client, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
{
OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
client->didReceiveResponse(identifier, *response);
}
void WorkerLoaderClientBridgeSyncHelper::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&didReceiveResponseAdapter, &m_client, identifier, response.copyData()));
}
void WorkerLoaderClientBridgeSyncHelper::didReceiveData(const char* data, int dataLength)
{
ASSERT(isMainThread());
Vector<char>* buffer = new Vector<char>(dataLength);
memcpy(buffer->data(), data, dataLength);
m_receivedData.append(buffer);
m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveData, &m_client, static_cast<const char*>(buffer->data()), dataLength));
}
void WorkerLoaderClientBridgeSyncHelper::didDownloadData(int dataLength)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didDownloadData, &m_client, dataLength));
}
void WorkerLoaderClientBridgeSyncHelper::didReceiveCachedMetadata(const char* data, int dataLength)
{
ASSERT(isMainThread());
Vector<char>* buffer = new Vector<char>(dataLength);
memcpy(buffer->data(), data, dataLength);
m_receivedData.append(buffer);
m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveCachedMetadata, &m_client, static_cast<const char*>(buffer->data()), dataLength));
}
void WorkerLoaderClientBridgeSyncHelper::didFinishLoading(unsigned long identifier, double finishTime)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFinishLoading, &m_client, identifier, finishTime));
m_done = true;
m_event->signal();
}
void WorkerLoaderClientBridgeSyncHelper::didFail(const ResourceError& error)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFail, &m_client, error.copy()));
m_done = true;
m_event->signal();
}
void WorkerLoaderClientBridgeSyncHelper::didFailAccessControlCheck(const ResourceError& error)
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFailAccessControlCheck, &m_client, error.copy()));
m_done = true;
m_event->signal();
}
void WorkerLoaderClientBridgeSyncHelper::didFailRedirectCheck()
{
ASSERT(isMainThread());
m_clientTasks.append(bind(&ThreadableLoaderClient::didFailRedirectCheck, &m_client));
m_done = true;
m_event->signal();
}
WorkerLoaderClientBridgeSyncHelper::WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
: m_done(false)
, m_client(client)
, m_event(event)
{
ASSERT(m_event);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>/* Autogenerated with kurento-module-creator */
#include "TelmateFrameGrabberOpenCVImpl.hpp"
#include <KurentoException.hpp>
namespace pt = boost::posix_time;
namespace kurento {
TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl()
{
this->thrLoop = true;
this->frameQueue = new boost::lockfree::queue<VideoFrame *>(0);
this->snapInterval = 1000;
this->epName = "EP_NAME_UNINITIALIZED";
this->storagePath = "/tmp";
this->framesCounter = 0;
this->outputFormat = FGFMT_JPEG;
this->thr = new boost::thread(boost::bind(&TelmateFrameGrabberOpenCVImpl::queueHandler, this));
GST_DEBUG("TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl() called");
}
TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl()
{
this->thrLoop = false;
this->thr->join();
delete this->frameQueue;
this->frameQueue = NULL;
delete this->thr;
this->thr = NULL;
GST_DEBUG("TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl() called");
}
/*
* This function will be called with each new frame. mat variable
* contains the current frame. You should insert your image processing code
* here. Any changes in mat, will be sent through the Media Pipeline.
*/
void TelmateFrameGrabberOpenCVImpl::process(cv::Mat &mat)
{
if ((this->getCurrentTimestampLong() - this->lastQueueTimeStamp) > this->snapInterval) {
VideoFrame *ptrVf = new VideoFrame();
ptrVf->mat = mat.clone();
ptrVf->ts = this->getCurrentTimestampString();
this->lastQueueTimeStamp = this->getCurrentTimestampLong();
this->frameQueue->push(ptrVf);
++this->queueLength;
++this->framesCounter;
}
}
/*
* This function is executed inside the queueHandler thread as a main() function.
* It pops a VideoFrame from the framequeue and saves it to disk.
* a boost scoped_lock is implemented to ensure the queue is emptied to disk before
* the destructor is executed. a 1 second sleep is implemented inside the while() loop
* to ensure the cpu isn't exhausted while the queue is empty.
*/
void TelmateFrameGrabberOpenCVImpl::queueHandler()
{
VideoFrame *ptrVf;
cv::Mat image;
boost::mutex::scoped_lock lock(workerThreadMutex);
while(this->thrLoop) {
if (!this->frameQueue->empty()) {
empty_queue:
std::vector<int> params;
std::string image_extension;
this->frameQueue->pop(ptrVf);
--this->queueLength;
switch(this->outputFormat) {
case FGFMT_JPEG:
/* Set jpeg params */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
case FGFMT_PNG:
/* Set PNG parameters, compression etc. */
params.push_back(CV_IMWRITE_PNG_COMPRESSION);
params.push_back(FG_PNG_QUALITY);
image_extension = ".png";
break;
default:
/* Defaults to jpeg */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
}
std::string filename = std::to_string(this->framesCounter) + "_" + ptrVf->ts + image_extension;
if(this->storagePathSubdir.size() == 0) {
this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
}
boost::filesystem::path dir(this->storagePathSubdir.c_str());
if(!boost::filesystem::is_directory(dir)) {
/* Directory does not exist, create it */
boost::filesystem::create_directories(dir);
}
std::string fullpath = this->storagePathSubdir + "/" + filename;
try {
cv::imwrite(fullpath.c_str(),ptrVf->mat,params);
}
catch (...) {
throw KurentoException (NOT_IMPLEMENTED, "TelmateFrameGrabberOpenCVImpl::queueHandler() imgwrite() failed.\n");
}
ptrVf->mat.release();
delete ptrVf;
ptrVf = NULL;
}
else {
boost::this_thread::sleep( boost::posix_time::seconds(1) );
}
}
while(!this->frameQueue->empty()) {
goto empty_queue;
GST_DEBUG("Emptying frameQueue..");
}
lock.unlock();
}
std::string TelmateFrameGrabberOpenCVImpl::getCurrentTimestampString()
{
struct timeval tp;
long int ms;
std::stringstream sstr_ts;
gettimeofday(&tp, NULL);
ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
sstr_ts << ms;
return sstr_ts.str();
}
long TelmateFrameGrabberOpenCVImpl::getCurrentTimestampLong()
{
struct timeval tp;
std::stringstream sstr_ts;
gettimeofday(&tp, NULL);
return (tp.tv_sec * 1000 + tp.tv_usec / 1000);
}
} /* kurento */
<commit_msg>Fix filesystem sync issues when creating directory<commit_after>/* Autogenerated with kurento-module-creator */
#include "TelmateFrameGrabberOpenCVImpl.hpp"
#include <KurentoException.hpp>
namespace pt = boost::posix_time;
namespace kurento {
TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl()
{
this->thrLoop = true;
this->frameQueue = new boost::lockfree::queue<VideoFrame *>(0);
this->snapInterval = 1000;
this->epName = "EP_NAME_UNINITIALIZED";
this->storagePath = "/tmp";
this->framesCounter = 0;
this->outputFormat = FGFMT_JPEG;
this->thr = new boost::thread(boost::bind(&TelmateFrameGrabberOpenCVImpl::queueHandler, this));
GST_ERROR("TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl() called");
}
TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl()
{
this->thrLoop = false;
this->thr->join();
delete this->frameQueue;
this->frameQueue = NULL;
delete this->thr;
this->thr = NULL;
GST_ERROR("TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl() called");
}
/*
* This function will be called with each new frame. mat variable
* contains the current frame. You should insert your image processing code
* here. Any changes in mat, will be sent through the Media Pipeline.
*/
void TelmateFrameGrabberOpenCVImpl::process(cv::Mat &mat)
{
if ((this->getCurrentTimestampLong() - this->lastQueueTimeStamp) > this->snapInterval) {
VideoFrame *ptrVf = new VideoFrame();
ptrVf->mat = mat.clone();
ptrVf->ts = this->getCurrentTimestampString();
this->lastQueueTimeStamp = this->getCurrentTimestampLong();
this->frameQueue->push(ptrVf);
++this->queueLength;
++this->framesCounter;
}
}
/*
* This function is executed inside the queueHandler thread as a main() function.
* It pops a VideoFrame from the framequeue and saves it to disk.
* a boost scoped_lock is implemented to ensure the queue is emptied to disk before
* the destructor is executed. a 1 second sleep is implemented inside the while() loop
* to ensure the cpu isn't exhausted while the queue is empty.
*/
void TelmateFrameGrabberOpenCVImpl::queueHandler()
{
VideoFrame *ptrVf;
cv::Mat image;
boost::mutex::scoped_lock lock(workerThreadMutex);
while(this->thrLoop) {
if (!this->frameQueue->empty()) {
empty_queue:
std::vector<int> params;
std::string image_extension;
this->frameQueue->pop(ptrVf);
--this->queueLength;
switch(this->outputFormat) {
case FGFMT_JPEG:
/* Set jpeg params */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
case FGFMT_PNG:
/* Set PNG parameters, compression etc. */
params.push_back(CV_IMWRITE_PNG_COMPRESSION);
params.push_back(FG_PNG_QUALITY);
image_extension = ".png";
break;
default:
/* Defaults to jpeg */
params.push_back(CV_IMWRITE_JPEG_QUALITY);
params.push_back(FG_JPEG_QUALITY);
image_extension = ".jpeg";
break;
}
std::string filename = std::to_string(this->framesCounter) + "_" + ptrVf->ts + image_extension;
if(this->storagePathSubdir.size() == 0) {
this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
}
boost::filesystem::path dir(this->storagePathSubdir.c_str());
boost::filesystem::create_directories(dir);
GST_ERROR("boost::filesystem::create_directories(dir);");
std::string fullpath = this->storagePathSubdir + "/" + filename;
try {
cv::imwrite(fullpath.c_str(),ptrVf->mat,params);
}
catch (...) {
throw KurentoException (NOT_IMPLEMENTED, "TelmateFrameGrabberOpenCVImpl::queueHandler() imgwrite() failed.\n");
GST_ERROR("TelmateFrameGrabberOpenCVImpl::queueHandler() imgwrite() failed.");
}
ptrVf->mat.release();
delete ptrVf;
ptrVf = NULL;
}
else {
boost::this_thread::sleep( boost::posix_time::seconds(1) );
}
}
while(!this->frameQueue->empty()) {
goto empty_queue;
GST_ERROR("Emptying frameQueue..");
}
lock.unlock();
}
std::string TelmateFrameGrabberOpenCVImpl::getCurrentTimestampString()
{
struct timeval tp;
long int ms;
std::stringstream sstr_ts;
gettimeofday(&tp, NULL);
ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
sstr_ts << ms;
return sstr_ts.str();
}
long TelmateFrameGrabberOpenCVImpl::getCurrentTimestampLong()
{
struct timeval tp;
std::stringstream sstr_ts;
gettimeofday(&tp, NULL);
return (tp.tv_sec * 1000 + tp.tv_usec / 1000);
}
} /* kurento */
<|endoftext|> |
<commit_before>#pragma once
#ifndef __VALIJSON_CONSTRAINTS_CONSTRAINT_VISITOR_HPP
#define __VALIJSON_CONSTRAINTS_CONSTRAINT_VISITOR_HPP
namespace valijson {
namespace constraints {
struct FormatConstraint;
class AllOfConstraint;
class AnyOfConstraint;
class DependenciesConstraint;
class EnumConstraint;
class LinearItemsConstraint;
class MaxItemsConstraint;
class MaximumConstraint;
class MaxLengthConstraint;
class MaxPropertiesConstraint;
class MinItemsConstraint;
class MinimumConstraint;
class MinLengthConstraint;
class MinPropertiesConstraint;
class MultipleOfDoubleConstraint;
class MultipleOfIntConstraint;
class NotConstraint;
class OneOfConstraint;
class PatternConstraint;
class PropertiesConstraint;
class RequiredConstraint;
class SingularItemsConstraint;
class TypeConstraint;
class UniqueItemsConstraint;
/// Interface to allow usage of the visitor pattern with Constraints
class ConstraintVisitor
{
protected:
// Shorten type names for derived classes outside of this namespace
typedef constraints::AllOfConstraint AllOfConstraint;
typedef constraints::AnyOfConstraint AnyOfConstraint;
typedef constraints::DependenciesConstraint DependenciesConstraint;
typedef constraints::EnumConstraint EnumConstraint;
typedef constraints::LinearItemsConstraint LinearItemsConstraint;
typedef constraints::MaximumConstraint MaximumConstraint;
typedef constraints::MaxItemsConstraint MaxItemsConstraint;
typedef constraints::MaxLengthConstraint MaxLengthConstraint;
typedef constraints::MaxPropertiesConstraint MaxPropertiesConstraint;
typedef constraints::MinimumConstraint MinimumConstraint;
typedef constraints::MinItemsConstraint MinItemsConstraint;
typedef constraints::MinLengthConstraint MinLengthConstraint;
typedef constraints::MinPropertiesConstraint MinPropertiesConstraint;
typedef constraints::MultipleOfDoubleConstraint MultipleOfDoubleConstraint;
typedef constraints::MultipleOfIntConstraint MultipleOfIntConstraint;
typedef constraints::NotConstraint NotConstraint;
typedef constraints::OneOfConstraint OneOfConstraint;
typedef constraints::PatternConstraint PatternConstraint;
typedef constraints::PropertiesConstraint PropertiesConstraint;
typedef constraints::RequiredConstraint RequiredConstraint;
typedef constraints::SingularItemsConstraint SingularItemsConstraint;
typedef constraints::TypeConstraint TypeConstraint;
typedef constraints::UniqueItemsConstraint UniqueItemsConstraint;
public:
virtual bool visit(const AllOfConstraint &) = 0;
virtual bool visit(const AnyOfConstraint &) = 0;
virtual bool visit(const DependenciesConstraint &) = 0;
virtual bool visit(const EnumConstraint &) = 0;
virtual bool visit(const LinearItemsConstraint &) = 0;
virtual bool visit(const MaximumConstraint &) = 0;
virtual bool visit(const MaxItemsConstraint &) = 0;
virtual bool visit(const MaxLengthConstraint &) = 0;
virtual bool visit(const MaxPropertiesConstraint &) = 0;
virtual bool visit(const MinimumConstraint &) = 0;
virtual bool visit(const MinItemsConstraint &) = 0;
virtual bool visit(const MinLengthConstraint &) = 0;
virtual bool visit(const MinPropertiesConstraint &) = 0;
virtual bool visit(const MultipleOfDoubleConstraint &) = 0;
virtual bool visit(const MultipleOfIntConstraint &) = 0;
virtual bool visit(const NotConstraint &) = 0;
virtual bool visit(const OneOfConstraint &) = 0;
virtual bool visit(const PatternConstraint &) = 0;
virtual bool visit(const PropertiesConstraint &) = 0;
virtual bool visit(const RequiredConstraint &) = 0;
virtual bool visit(const SingularItemsConstraint &) = 0;
virtual bool visit(const TypeConstraint &) = 0;
virtual bool visit(const UniqueItemsConstraint &) = 0;
};
} // namespace constraints
} // namespace valijson
#endif
<commit_msg>Remove unused forward declaration of FormatConstraint struct<commit_after>#pragma once
#ifndef __VALIJSON_CONSTRAINTS_CONSTRAINT_VISITOR_HPP
#define __VALIJSON_CONSTRAINTS_CONSTRAINT_VISITOR_HPP
namespace valijson {
namespace constraints {
class AllOfConstraint;
class AnyOfConstraint;
class DependenciesConstraint;
class EnumConstraint;
class LinearItemsConstraint;
class MaxItemsConstraint;
class MaximumConstraint;
class MaxLengthConstraint;
class MaxPropertiesConstraint;
class MinItemsConstraint;
class MinimumConstraint;
class MinLengthConstraint;
class MinPropertiesConstraint;
class MultipleOfDoubleConstraint;
class MultipleOfIntConstraint;
class NotConstraint;
class OneOfConstraint;
class PatternConstraint;
class PropertiesConstraint;
class RequiredConstraint;
class SingularItemsConstraint;
class TypeConstraint;
class UniqueItemsConstraint;
/// Interface to allow usage of the visitor pattern with Constraints
class ConstraintVisitor
{
protected:
// Shorten type names for derived classes outside of this namespace
typedef constraints::AllOfConstraint AllOfConstraint;
typedef constraints::AnyOfConstraint AnyOfConstraint;
typedef constraints::DependenciesConstraint DependenciesConstraint;
typedef constraints::EnumConstraint EnumConstraint;
typedef constraints::LinearItemsConstraint LinearItemsConstraint;
typedef constraints::MaximumConstraint MaximumConstraint;
typedef constraints::MaxItemsConstraint MaxItemsConstraint;
typedef constraints::MaxLengthConstraint MaxLengthConstraint;
typedef constraints::MaxPropertiesConstraint MaxPropertiesConstraint;
typedef constraints::MinimumConstraint MinimumConstraint;
typedef constraints::MinItemsConstraint MinItemsConstraint;
typedef constraints::MinLengthConstraint MinLengthConstraint;
typedef constraints::MinPropertiesConstraint MinPropertiesConstraint;
typedef constraints::MultipleOfDoubleConstraint MultipleOfDoubleConstraint;
typedef constraints::MultipleOfIntConstraint MultipleOfIntConstraint;
typedef constraints::NotConstraint NotConstraint;
typedef constraints::OneOfConstraint OneOfConstraint;
typedef constraints::PatternConstraint PatternConstraint;
typedef constraints::PropertiesConstraint PropertiesConstraint;
typedef constraints::RequiredConstraint RequiredConstraint;
typedef constraints::SingularItemsConstraint SingularItemsConstraint;
typedef constraints::TypeConstraint TypeConstraint;
typedef constraints::UniqueItemsConstraint UniqueItemsConstraint;
public:
virtual bool visit(const AllOfConstraint &) = 0;
virtual bool visit(const AnyOfConstraint &) = 0;
virtual bool visit(const DependenciesConstraint &) = 0;
virtual bool visit(const EnumConstraint &) = 0;
virtual bool visit(const LinearItemsConstraint &) = 0;
virtual bool visit(const MaximumConstraint &) = 0;
virtual bool visit(const MaxItemsConstraint &) = 0;
virtual bool visit(const MaxLengthConstraint &) = 0;
virtual bool visit(const MaxPropertiesConstraint &) = 0;
virtual bool visit(const MinimumConstraint &) = 0;
virtual bool visit(const MinItemsConstraint &) = 0;
virtual bool visit(const MinLengthConstraint &) = 0;
virtual bool visit(const MinPropertiesConstraint &) = 0;
virtual bool visit(const MultipleOfDoubleConstraint &) = 0;
virtual bool visit(const MultipleOfIntConstraint &) = 0;
virtual bool visit(const NotConstraint &) = 0;
virtual bool visit(const OneOfConstraint &) = 0;
virtual bool visit(const PatternConstraint &) = 0;
virtual bool visit(const PropertiesConstraint &) = 0;
virtual bool visit(const RequiredConstraint &) = 0;
virtual bool visit(const SingularItemsConstraint &) = 0;
virtual bool visit(const TypeConstraint &) = 0;
virtual bool visit(const UniqueItemsConstraint &) = 0;
};
} // namespace constraints
} // namespace valijson
#endif
<|endoftext|> |
<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/svg/Svg.h"
#include "cinder/ip/Fill.h"
//#include "cinder/svg/SvgGl.h"
#include "cinder/cairo/Cairo.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class SimpleViewerApp : public App {
public:
void setup();
void mouseDown( MouseEvent event );
void draw();
void fileDrop( FileDropEvent event );
void load( fs::path path );
bool mUseCairo;
svg::DocRef mDoc;
gl::TextureRef mTex;
};
void SimpleViewerApp::setup()
{
mUseCairo = true;
}
void SimpleViewerApp::mouseDown( MouseEvent event )
{
mUseCairo = ! mUseCairo;
}
void SimpleViewerApp::fileDrop( FileDropEvent event )
{
load( event.getFile( 0 ) );
}
gl::TextureRef renderCairoToTexture( svg::DocRef doc )
{
cairo::SurfaceImage srf( 640, 480, true );
if( doc->getWidth() && doc->getHeight() )
srf = cairo::SurfaceImage( doc->getWidth(), doc->getHeight(), true );
else
srf = cairo::SurfaceImage( 640, 480, true );
cairo::Context ctx( srf );
ctx.render( *doc );
ctx.flush();
return gl::Texture::create( srf.getSurface() );
}
void SimpleViewerApp::load( fs::path path )
{
try {
if( path.extension() != ".svgz" )
mDoc = svg::Doc::create( path );
else // compressed
mDoc = svg::Doc::createFromSvgz( loadFile( path ) );
mTex = renderCairoToTexture( mDoc );
}
catch( ci::Exception &exc ) {
console() << "exception caught parsing svg doc, what: " << exc.what() << endl;
}
}
void SimpleViewerApp::draw()
{
// clear out the window with black
gl::clear( Color::gray( 0.5f ) );
gl::enableAlphaBlending();
if( mDoc ) {
gl::color( Color::white() );
if( mTex ) {
if( mUseCairo )
gl::draw( mTex );
else
;// gl::draw( *mDoc );
}
}
else {
gl::drawStringCentered( "Drag & Drop an SVG file", getWindowCenter() );
gl::drawStringCentered( "Click to toggle between Cairo & OpenGL", getWindowCenter() + vec2( 0, 20 ) );
}
}
CINDER_APP( SimpleViewerApp, RendererGl )
<commit_msg>Reenabling GL drawing in samples/_svg/SimpleViewer<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/svg/Svg.h"
#include "cinder/ip/Fill.h"
#include "cinder/svg/SvgGl.h"
#include "cinder/cairo/Cairo.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class SimpleViewerApp : public App {
public:
void setup();
void mouseDown( MouseEvent event );
void draw();
void fileDrop( FileDropEvent event );
void load( fs::path path );
bool mUseCairo;
svg::DocRef mDoc;
gl::TextureRef mTex;
};
void SimpleViewerApp::setup()
{
mUseCairo = true;
}
void SimpleViewerApp::mouseDown( MouseEvent event )
{
mUseCairo = ! mUseCairo;
}
void SimpleViewerApp::fileDrop( FileDropEvent event )
{
load( event.getFile( 0 ) );
}
gl::TextureRef renderCairoToTexture( svg::DocRef doc )
{
cairo::SurfaceImage srf( 640, 480, true );
if( doc->getWidth() && doc->getHeight() )
srf = cairo::SurfaceImage( doc->getWidth(), doc->getHeight(), true );
else
srf = cairo::SurfaceImage( 640, 480, true );
cairo::Context ctx( srf );
ctx.render( *doc );
ctx.flush();
return gl::Texture::create( srf.getSurface() );
}
void SimpleViewerApp::load( fs::path path )
{
try {
if( path.extension() != ".svgz" )
mDoc = svg::Doc::create( path );
else // compressed
mDoc = svg::Doc::createFromSvgz( loadFile( path ) );
mTex = renderCairoToTexture( mDoc );
}
catch( ci::Exception &exc ) {
console() << "exception caught parsing svg doc, what: " << exc.what() << endl;
}
}
void SimpleViewerApp::draw()
{
// clear out the window with black
gl::clear( Color::gray( 0.5f ) );
gl::enableAlphaBlending();
if( mDoc ) {
gl::color( Color::white() );
if( mTex ) {
if( mUseCairo )
gl::draw( mTex );
else
gl::draw( *mDoc );
}
}
else {
gl::drawStringCentered( "Drag & Drop an SVG file", getWindowCenter() );
gl::drawStringCentered( "Click to toggle between Cairo & OpenGL", getWindowCenter() + vec2( 0, 20 ) );
}
}
CINDER_APP( SimpleViewerApp, RendererGl )
<|endoftext|> |
<commit_before>#include "MipsExecutor.h"
CMipsExecutor::CMipsExecutor(CMIPS& context, uint32 maxAddress)
: m_context(context)
, m_subTableCount(0)
#ifdef DEBUGGER_INCLUDED
, m_breakpointsDisabledOnce(false)
#endif
{
if(maxAddress < 0x10000)
{
maxAddress = 0x10000;
}
assert((maxAddress & 0xFFFF) == 0);
if(maxAddress == 0)
{
m_subTableCount = 0x10000;
}
else
{
m_subTableCount = maxAddress / 0x10000;
}
m_blockTable = new CBasicBlock**[m_subTableCount];
memset(m_blockTable, 0, sizeof(CBasicBlock**) * m_subTableCount);
}
CMipsExecutor::~CMipsExecutor()
{
for(unsigned int i = 0; i < m_subTableCount; i++)
{
CBasicBlock** subTable = m_blockTable[i];
if(subTable != NULL)
{
delete [] subTable;
}
}
delete [] m_blockTable;
}
void CMipsExecutor::Reset()
{
ClearActiveBlocks();
}
void CMipsExecutor::ClearActiveBlocks()
{
for(unsigned int i = 0; i < m_subTableCount; i++)
{
CBasicBlock** subTable = m_blockTable[i];
if(subTable != NULL)
{
delete [] subTable;
m_blockTable[i] = NULL;
}
}
m_blocks.clear();
}
void CMipsExecutor::ClearActiveBlocksInRange(uint32 start, uint32 end)
{
uint32 hiStart = start >> 16;
uint32 hiEnd = end >> 16;
std::set<CBasicBlock*> blocksToDelete;
for(uint32 hi = hiStart; hi <= hiEnd; hi++)
{
CBasicBlock** table = m_blockTable[hi];
if(table == nullptr) continue;
for(uint32 lo = 0; lo < 0x10000; lo += 4)
{
uint32 tableAddress = (hi << 16) | lo;
if(tableAddress < start) continue;
if(tableAddress >= end) continue;
CBasicBlock* block = table[lo / 4];
if(block == nullptr) continue;
table[lo / 4] = nullptr;
blocksToDelete.insert(block);
}
}
if(!blocksToDelete.empty())
{
m_blocks.remove_if([&] (const BasicBlockPtr& block) { return blocksToDelete.find(block.get()) != std::end(blocksToDelete); });
}
}
int CMipsExecutor::Execute(int cycles)
{
CBasicBlock* block(nullptr);
while(cycles > 0)
{
uint32 address = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);
if(!block || address != block->GetBeginAddress())
{
block = FindBlockStartingAt(address);
if(block == NULL)
{
//We need to partition the space and compile the blocks
PartitionFunction(address);
block = FindBlockStartingAt(address);
if(block == NULL)
{
throw std::runtime_error("Couldn't create block starting at address.");
}
}
if(!block->IsCompiled())
{
block->Compile();
}
}
else if(block != NULL)
{
block->SetSelfLoopCount(block->GetSelfLoopCount() + 1);
}
#ifdef DEBUGGER_INCLUDED
if(!m_breakpointsDisabledOnce && MustBreak()) break;
m_breakpointsDisabledOnce = false;
#endif
cycles -= block->Execute();
if(m_context.m_State.nHasException) break;
}
return cycles;
}
#ifdef DEBUGGER_INCLUDED
bool CMipsExecutor::MustBreak() const
{
uint32 currentPc = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);
CBasicBlock* block = FindBlockAt(currentPc);
for(auto breakPointIterator(m_context.m_breakpoints.begin());
breakPointIterator != m_context.m_breakpoints.end(); breakPointIterator++)
{
uint32 breakPointAddress = *breakPointIterator;
if(currentPc == breakPointAddress) return true;
if(block != NULL)
{
if(breakPointAddress >= block->GetBeginAddress() && breakPointAddress <= block->GetEndAddress()) return true;
}
}
return false;
}
void CMipsExecutor::DisableBreakpointsOnce()
{
m_breakpointsDisabledOnce = true;
}
#endif
CBasicBlock* CMipsExecutor::FindBlockAt(uint32 address) const
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
if(subTable == NULL) return NULL;
CBasicBlock* result = subTable[loAddress / 4];
return result;
}
CBasicBlock* CMipsExecutor::FindBlockStartingAt(uint32 address) const
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
if(subTable == NULL) return NULL;
CBasicBlock* result = subTable[loAddress / 4];
if((address != 0) && (FindBlockAt(address - 4) == result))
{
return NULL;
}
return result;
}
void CMipsExecutor::CreateBlock(uint32 start, uint32 end)
{
{
CBasicBlock* block = FindBlockAt(start);
if(block)
{
//If the block starts and ends at the same place, block already exists and doesn't need
//to be re-created
uint32 otherBegin = block->GetBeginAddress();
uint32 otherEnd = block->GetEndAddress();
if((otherBegin == start) && (otherEnd == end))
{
return;
}
if(otherEnd == end)
{
//Repartition the existing block if end of both blocks are the same
DeleteBlock(block);
CreateBlock(otherBegin, start - 4);
assert(FindBlockAt(start) == NULL);
}
else if(otherBegin == start)
{
DeleteBlock(block);
CreateBlock(end + 4, otherEnd);
assert(FindBlockAt(end) == NULL);
}
else
{
//Delete the currently existing block otherwise
printf("MipsExecutor: Warning. Deleting block at %0.8X.\r\n", block->GetEndAddress());
DeleteBlock(block);
}
}
}
assert(FindBlockAt(end) == NULL);
{
BasicBlockPtr block = BlockFactory(m_context, start, end);
for(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
if(subTable == NULL)
{
const uint32 subTableSize = 0x10000 / 4;
subTable = new CBasicBlock*[subTableSize];
memset(subTable, 0, sizeof(CBasicBlock*) * subTableSize);
}
assert(subTable[loAddress / 4] == NULL);
subTable[loAddress / 4] = block.get();
}
m_blocks.push_back(std::move(block));
}
}
void CMipsExecutor::DeleteBlock(CBasicBlock* block)
{
for(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
assert(subTable != NULL);
assert(subTable[loAddress / 4] != NULL);
subTable[loAddress / 4] = NULL;
}
//Remove block from our lists
auto blockIterator = std::find_if(std::begin(m_blocks), std::end(m_blocks), [&] (const BasicBlockPtr& blockPtr) { return blockPtr.get() == block; });
assert(blockIterator != std::end(m_blocks));
m_blocks.erase(blockIterator);
}
CMipsExecutor::BasicBlockPtr CMipsExecutor::BlockFactory(CMIPS& context, uint32 start, uint32 end)
{
return BasicBlockPtr(new CBasicBlock(context, start, end));
}
void CMipsExecutor::PartitionFunction(uint32 functionAddress)
{
typedef std::set<uint32> PartitionPointSet;
uint32 endAddress = 0;
PartitionPointSet partitionPoints;
//Insert begin point
partitionPoints.insert(functionAddress);
//Find the end
for(uint32 address = functionAddress; ; address += 4)
{
//Probably going too far...
if((address - functionAddress) > 0x10000)
{
printf("MipsExecutor: Warning. Found no JR after a big distance.\r\n");
endAddress = address;
partitionPoints.insert(endAddress);
break;
}
uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);
if(opcode == 0x03E00008)
{
//+4 for delay slot
endAddress = address + 4;
partitionPoints.insert(endAddress + 4);
break;
}
}
//Find partition points within the function
for(uint32 address = functionAddress; address <= endAddress; address += 4)
{
uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);
MIPS_BRANCH_TYPE branchType = m_context.m_pArch->IsInstructionBranch(&m_context, address, opcode);
if(branchType == MIPS_BRANCH_NORMAL)
{
partitionPoints.insert(address + 8);
uint32 target = m_context.m_pArch->GetInstructionEffectiveAddress(&m_context, address, opcode);
if(target > functionAddress && target < endAddress)
{
partitionPoints.insert(target);
}
}
else if(branchType == MIPS_BRANCH_NODELAY)
{
partitionPoints.insert(address + 4);
}
//Check if there's a block already exising that this address
if(address != endAddress)
{
CBasicBlock* possibleBlock = FindBlockStartingAt(address);
if(possibleBlock)
{
//assert(possibleBlock->GetEndAddress() <= endAddress);
//Add its beginning and end in the partition points
partitionPoints.insert(possibleBlock->GetBeginAddress());
partitionPoints.insert(possibleBlock->GetEndAddress() + 4);
}
}
}
//Check if blocks are too big
{
uint32 currentPoint = -1;
for(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());
pointIterator != partitionPoints.end(); pointIterator++)
{
if(currentPoint != -1)
{
uint32 startPos = currentPoint;
uint32 endPos = *pointIterator;
uint32 distance = (endPos - startPos);
if(distance > 0x400)
{
uint32 middlePos = ((endPos + startPos) / 2) & ~0x03;
pointIterator = partitionPoints.insert(middlePos).first;
pointIterator--;
continue;
}
}
currentPoint = *pointIterator;
}
}
//Create blocks
{
uint32 currentPoint = -1;
for(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());
pointIterator != partitionPoints.end(); pointIterator++)
{
if(currentPoint != -1)
{
CreateBlock(currentPoint, *pointIterator - 4);
}
currentPoint = *pointIterator;
}
}
}
<commit_msg>Added comment about something that should be done later.<commit_after>#include "MipsExecutor.h"
CMipsExecutor::CMipsExecutor(CMIPS& context, uint32 maxAddress)
: m_context(context)
, m_subTableCount(0)
#ifdef DEBUGGER_INCLUDED
, m_breakpointsDisabledOnce(false)
#endif
{
if(maxAddress < 0x10000)
{
maxAddress = 0x10000;
}
assert((maxAddress & 0xFFFF) == 0);
if(maxAddress == 0)
{
m_subTableCount = 0x10000;
}
else
{
m_subTableCount = maxAddress / 0x10000;
}
m_blockTable = new CBasicBlock**[m_subTableCount];
memset(m_blockTable, 0, sizeof(CBasicBlock**) * m_subTableCount);
}
CMipsExecutor::~CMipsExecutor()
{
for(unsigned int i = 0; i < m_subTableCount; i++)
{
CBasicBlock** subTable = m_blockTable[i];
if(subTable != NULL)
{
delete [] subTable;
}
}
delete [] m_blockTable;
}
void CMipsExecutor::Reset()
{
ClearActiveBlocks();
}
void CMipsExecutor::ClearActiveBlocks()
{
for(unsigned int i = 0; i < m_subTableCount; i++)
{
CBasicBlock** subTable = m_blockTable[i];
if(subTable != NULL)
{
delete [] subTable;
m_blockTable[i] = NULL;
}
}
m_blocks.clear();
}
void CMipsExecutor::ClearActiveBlocksInRange(uint32 start, uint32 end)
{
uint32 hiStart = start >> 16;
uint32 hiEnd = end >> 16;
std::set<CBasicBlock*> blocksToDelete;
for(uint32 hi = hiStart; hi <= hiEnd; hi++)
{
CBasicBlock** table = m_blockTable[hi];
if(table == nullptr) continue;
for(uint32 lo = 0; lo < 0x10000; lo += 4)
{
uint32 tableAddress = (hi << 16) | lo;
if(tableAddress < start) continue;
if(tableAddress >= end) continue;
CBasicBlock* block = table[lo / 4];
if(block == nullptr) continue;
table[lo / 4] = nullptr;
blocksToDelete.insert(block);
}
}
if(!blocksToDelete.empty())
{
//TODO: Actually delete the blocks, because remove_if only rearranges items leaving us a new end iterator
m_blocks.remove_if([&] (const BasicBlockPtr& block) { return blocksToDelete.find(block.get()) != std::end(blocksToDelete); });
}
}
int CMipsExecutor::Execute(int cycles)
{
CBasicBlock* block(nullptr);
while(cycles > 0)
{
uint32 address = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);
if(!block || address != block->GetBeginAddress())
{
block = FindBlockStartingAt(address);
if(block == NULL)
{
//We need to partition the space and compile the blocks
PartitionFunction(address);
block = FindBlockStartingAt(address);
if(block == NULL)
{
throw std::runtime_error("Couldn't create block starting at address.");
}
}
if(!block->IsCompiled())
{
block->Compile();
}
}
else if(block != NULL)
{
block->SetSelfLoopCount(block->GetSelfLoopCount() + 1);
}
#ifdef DEBUGGER_INCLUDED
if(!m_breakpointsDisabledOnce && MustBreak()) break;
m_breakpointsDisabledOnce = false;
#endif
cycles -= block->Execute();
if(m_context.m_State.nHasException) break;
}
return cycles;
}
#ifdef DEBUGGER_INCLUDED
bool CMipsExecutor::MustBreak() const
{
uint32 currentPc = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);
CBasicBlock* block = FindBlockAt(currentPc);
for(auto breakPointIterator(m_context.m_breakpoints.begin());
breakPointIterator != m_context.m_breakpoints.end(); breakPointIterator++)
{
uint32 breakPointAddress = *breakPointIterator;
if(currentPc == breakPointAddress) return true;
if(block != NULL)
{
if(breakPointAddress >= block->GetBeginAddress() && breakPointAddress <= block->GetEndAddress()) return true;
}
}
return false;
}
void CMipsExecutor::DisableBreakpointsOnce()
{
m_breakpointsDisabledOnce = true;
}
#endif
CBasicBlock* CMipsExecutor::FindBlockAt(uint32 address) const
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
if(subTable == NULL) return NULL;
CBasicBlock* result = subTable[loAddress / 4];
return result;
}
CBasicBlock* CMipsExecutor::FindBlockStartingAt(uint32 address) const
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
if(subTable == NULL) return NULL;
CBasicBlock* result = subTable[loAddress / 4];
if((address != 0) && (FindBlockAt(address - 4) == result))
{
return NULL;
}
return result;
}
void CMipsExecutor::CreateBlock(uint32 start, uint32 end)
{
{
CBasicBlock* block = FindBlockAt(start);
if(block)
{
//If the block starts and ends at the same place, block already exists and doesn't need
//to be re-created
uint32 otherBegin = block->GetBeginAddress();
uint32 otherEnd = block->GetEndAddress();
if((otherBegin == start) && (otherEnd == end))
{
return;
}
if(otherEnd == end)
{
//Repartition the existing block if end of both blocks are the same
DeleteBlock(block);
CreateBlock(otherBegin, start - 4);
assert(FindBlockAt(start) == NULL);
}
else if(otherBegin == start)
{
DeleteBlock(block);
CreateBlock(end + 4, otherEnd);
assert(FindBlockAt(end) == NULL);
}
else
{
//Delete the currently existing block otherwise
printf("MipsExecutor: Warning. Deleting block at %0.8X.\r\n", block->GetEndAddress());
DeleteBlock(block);
}
}
}
assert(FindBlockAt(end) == NULL);
{
BasicBlockPtr block = BlockFactory(m_context, start, end);
for(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
if(subTable == NULL)
{
const uint32 subTableSize = 0x10000 / 4;
subTable = new CBasicBlock*[subTableSize];
memset(subTable, 0, sizeof(CBasicBlock*) * subTableSize);
}
assert(subTable[loAddress / 4] == NULL);
subTable[loAddress / 4] = block.get();
}
m_blocks.push_back(std::move(block));
}
}
void CMipsExecutor::DeleteBlock(CBasicBlock* block)
{
for(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)
{
uint32 hiAddress = address >> 16;
uint32 loAddress = address & 0xFFFF;
assert(hiAddress < m_subTableCount);
CBasicBlock**& subTable = m_blockTable[hiAddress];
assert(subTable != NULL);
assert(subTable[loAddress / 4] != NULL);
subTable[loAddress / 4] = NULL;
}
//Remove block from our lists
auto blockIterator = std::find_if(std::begin(m_blocks), std::end(m_blocks), [&] (const BasicBlockPtr& blockPtr) { return blockPtr.get() == block; });
assert(blockIterator != std::end(m_blocks));
m_blocks.erase(blockIterator);
}
CMipsExecutor::BasicBlockPtr CMipsExecutor::BlockFactory(CMIPS& context, uint32 start, uint32 end)
{
return BasicBlockPtr(new CBasicBlock(context, start, end));
}
void CMipsExecutor::PartitionFunction(uint32 functionAddress)
{
typedef std::set<uint32> PartitionPointSet;
uint32 endAddress = 0;
PartitionPointSet partitionPoints;
//Insert begin point
partitionPoints.insert(functionAddress);
//Find the end
for(uint32 address = functionAddress; ; address += 4)
{
//Probably going too far...
if((address - functionAddress) > 0x10000)
{
printf("MipsExecutor: Warning. Found no JR after a big distance.\r\n");
endAddress = address;
partitionPoints.insert(endAddress);
break;
}
uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);
if(opcode == 0x03E00008)
{
//+4 for delay slot
endAddress = address + 4;
partitionPoints.insert(endAddress + 4);
break;
}
}
//Find partition points within the function
for(uint32 address = functionAddress; address <= endAddress; address += 4)
{
uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);
MIPS_BRANCH_TYPE branchType = m_context.m_pArch->IsInstructionBranch(&m_context, address, opcode);
if(branchType == MIPS_BRANCH_NORMAL)
{
partitionPoints.insert(address + 8);
uint32 target = m_context.m_pArch->GetInstructionEffectiveAddress(&m_context, address, opcode);
if(target > functionAddress && target < endAddress)
{
partitionPoints.insert(target);
}
}
else if(branchType == MIPS_BRANCH_NODELAY)
{
partitionPoints.insert(address + 4);
}
//Check if there's a block already exising that this address
if(address != endAddress)
{
CBasicBlock* possibleBlock = FindBlockStartingAt(address);
if(possibleBlock)
{
//assert(possibleBlock->GetEndAddress() <= endAddress);
//Add its beginning and end in the partition points
partitionPoints.insert(possibleBlock->GetBeginAddress());
partitionPoints.insert(possibleBlock->GetEndAddress() + 4);
}
}
}
//Check if blocks are too big
{
uint32 currentPoint = -1;
for(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());
pointIterator != partitionPoints.end(); pointIterator++)
{
if(currentPoint != -1)
{
uint32 startPos = currentPoint;
uint32 endPos = *pointIterator;
uint32 distance = (endPos - startPos);
if(distance > 0x400)
{
uint32 middlePos = ((endPos + startPos) / 2) & ~0x03;
pointIterator = partitionPoints.insert(middlePos).first;
pointIterator--;
continue;
}
}
currentPoint = *pointIterator;
}
}
//Create blocks
{
uint32 currentPoint = -1;
for(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());
pointIterator != partitionPoints.end(); pointIterator++)
{
if(currentPoint != -1)
{
CreateBlock(currentPoint, *pointIterator - 4);
}
currentPoint = *pointIterator;
}
}
}
<|endoftext|> |
<commit_before>#include <android/log.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <jni.h>
#include <stdlib.h>
#include "tango-api/tango_client_api.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include "gtc/matrix_transform.hpp"
#include "gtc/quaternion.hpp"
#include "gtc/type_ptr.hpp"
#define LOG_TAG "tango_motion_tracking"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
GLuint mvp_matrix_id = 0;
GLuint position_id = 0;
GLuint color_id = 0;
GLuint program_id = 0;
static glm::mat4 projection_matrix;
static glm::mat4 modelview_matrix;
static glm::mat4 mvp_matrix;
static const char vertex_shader[] = { "uniform mat4 u_mvp_matrix; \n"
"attribute vec4 a_position; \n"
"attribute vec4 a_color; \n"
"varying vec4 v_color; \n"
"void main() \n"
"{ \n"
" v_color = a_color; \n"
" gl_Position = u_mvp_matrix \n"
" * a_position; \n"
"} \n" };
static const char fragment_shader[] = { "precision mediump float; \n"
"varying vec4 v_color; \n"
"void main() \n"
"{ \n"
" gl_FragColor = v_color; \n"
"} \n" };
static const GLfloat cube_vertices[] = {
// front
-0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,
0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f,
// right
0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f,
// back
0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f,
// left
-0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f,
// top
-0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,
// bottom
-0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f };
static const GLfloat cube_colors[] = {
// front, blue
0.0625f, 0.5742f, 0.9257f, 1.0f, 0.0625f, 0.5742f, 0.9257f, 1.0f,
0.0625f, 0.5742f, 0.9257f, 1.0f, 0.0625f, 0.5742f, 0.9257f, 1.0f,
0.0625f, 0.5742f, 0.9257f, 1.0f, 0.0625f, 0.5742f, 0.9257f, 1.0f,
// right, purple
0.8549f, 0.4471f, 0.9176f, 1.0f, 0.8549f, 0.4471f, 0.9176f, 1.0f,
0.8549f, 0.4471f, 0.9176f, 1.0f, 0.8549f, 0.4471f, 0.9176f, 1.0f,
0.8549f, 0.4471f, 0.9176f, 1.0f, 0.8549f, 0.4471f, 0.9176f, 1.0f,
// back, yellow
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
// left, yellow
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
// top, orange
0.8980f, 0.4627f, 0.1922f, 1.0f, 0.8980f, 0.4627f, 0.1922f, 1.0f,
0.8980f, 0.4627f, 0.1922f, 1.0f, 0.8980f, 0.4627f, 0.1922f, 1.0f,
0.8980f, 0.4627f, 0.1922f, 1.0f, 0.8980f, 0.4627f, 0.1922f, 1.0f,
// bottom, green
0.1921f, 0.8981f, 0.3019f, 1.0f, 0.1921f, 0.8981f, 0.3019f, 1.0f,
0.1921f, 0.8981f, 0.3019f, 1.0f, 0.1921f, 0.8981f, 0.3019f, 1.0f,
0.1921f, 0.8981f, 0.3019f, 1.0f, 0.1921f, 0.8981f, 0.3019f, 1.0f, };
static void CheckGlError(const char* operation) {
for (GLint error = glGetError(); error; error = glGetError()) {
LOGI("after %s() glError (0x%x)", operation, error);
}
}
static void onPoseAvailable(TangoPoseData *pose){
glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f),
glm::vec3(pose->translation[0], pose->translation[1],
pose->translation[2] - 6.0f));
glm::quat rotationQuaterion = glm::quat(pose->orientation[3],
pose->orientation[0], pose->orientation[1],
pose->orientation[2]);
glm::mat4 rotationMatrix = glm::mat4_cast(rotationQuaterion);
modelview_matrix = translateMatrix * rotationMatrix;
}
GLuint LoadShader(GLenum shader_type, const char* shader_source) {
GLuint shader = glCreateShader(shader_type);
if (shader) {
glShaderSource(shader, 1, &shader_source, NULL);
glCompileShader(shader);
GLint status = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
GLint info_length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_length);
if (info_length) {
char* buffer = (char*) malloc(info_length * sizeof(char));
if (buffer) {
glGetShaderInfoLog(shader, info_length, NULL, buffer);
}
}
glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
GLuint CreateProgram(const char* vertex_shader_source,
const char* fragment_shader_source) {
GLuint vertex_shader = LoadShader(GL_VERTEX_SHADER, vertex_shader_source);
if (!vertex_shader) {
return 0;
}
GLuint fragment_shader = LoadShader(GL_FRAGMENT_SHADER,
fragment_shader_source);
if (!fragment_shader) {
return 0;
}
GLuint program = glCreateProgram();
if (program) {
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glBindAttribLocation(program, 0, "a_position");
glBindAttribLocation(program, 1, "a_color");
glLinkProgram(program);
GLint status = 0;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (!status) {
GLint info_length = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_length);
if (info_length) {
char* buffer = (char*) malloc(info_length * sizeof(char));
glGetProgramInfoLog(program, info_length, NULL, buffer);
}
glDeleteProgram(program);
program = 0;
}
}
return program;
}
bool SetupTango() {
int i;
TangoConfig* config;
if (TangoService_initialize() != 0) {
LOGI("TangoService_initialize(): Failed");
return false;
}
//Allocate a TangoConfig instance
if ((config = TangoConfig_alloc()) == NULL) {
LOGI("TangoService_allocConfig(): Failed");
return false;
}
//Report the current TangoConfig
LOGI("TangoConfig:%s", TangoConfig_toString(config));
//Lock in this configuration
if(TangoService_lockConfig(config)!=0){
LOGI("TangoService_lockConfig(): Failed");
return false;
}
//Attach the onPoseAvailable callback.
if(TangoService_connectOnPoseAvailable(onPoseAvailable)!=0){
LOGI("TangoService_connectOnPoseAvailable(): Failed");
return false;
}
//Connect to the Tango Service
TangoService_connect();
LOGI("Tango Service connectOnPoseAvailable success!");
return true;
}
bool SetupGraphics(int w, int h) {
LOGI("SetupGraphics(%d, %d)", w, h);
glClearColor(0, 0, 0, 1.0f);
glEnable (GL_CULL_FACE);
glEnable (GL_DEPTH_TEST);
program_id = CreateProgram(vertex_shader, fragment_shader);
glVertexAttribPointer(position_id, 3, GL_FLOAT, GL_FALSE, 0, cube_vertices);
glEnableVertexAttribArray(position_id);
glVertexAttribPointer(color_id, 4, GL_FLOAT, GL_FALSE, 0, cube_colors);
glEnableVertexAttribArray(color_id);
projection_matrix = glm::perspective(75.0f, (GLfloat) w / h, 0.01f, 10.0f);
glViewport(0, 0, w, h);
return true;
}
bool RenderFrame() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program_id);
mvp_matrix_id = glGetUniformLocation(program_id, "u_mvp_matrix");
position_id = glGetAttribLocation(program_id, "a_position");
color_id = glGetAttribLocation(program_id, "a_color");
mvp_matrix = projection_matrix * modelview_matrix;
glUniformMatrix4fv(mvp_matrix_id, 1, false, glm::value_ptr(mvp_matrix));
glDrawArrays(GL_TRIANGLES, 0, 36);
return true;
}
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_com_google_tango_tangojnimotiontracking_TangoJNINative_init(
JNIEnv * env, jobject obj, jint width, jint height)
{
SetupTango();
SetupGraphics(width, height);
}
JNIEXPORT void JNICALL Java_com_google_tango_tangojnimotiontracking_TangoJNINative_render(
JNIEnv * env, jobject obj)
{
RenderFrame();
}
#ifdef __cplusplus
}
#endif
<commit_msg>Changes for render frame.<commit_after>#include <android/log.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <jni.h>
#include <stdlib.h>
#include "tango-api/tango_client_api.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include "gtc/matrix_transform.hpp"
#include "gtc/quaternion.hpp"
#include "gtc/type_ptr.hpp"
#define LOG_TAG "tango_motion_tracking"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
GLuint mvp_matrix_id = 0;
GLuint position_id = 0;
GLuint color_id = 0;
GLuint program_id = 0;
static glm::mat4 projection_matrix;
static glm::mat4 modelview_matrix;
static glm::mat4 mvp_matrix;
static const char vertex_shader[] = { "uniform mat4 u_mvp_matrix; \n"
"attribute vec4 a_position; \n"
"attribute vec4 a_color; \n"
"varying vec4 v_color; \n"
"void main() \n"
"{ \n"
" v_color = a_color; \n"
" gl_Position = u_mvp_matrix \n"
" * a_position; \n"
"} \n" };
static const char fragment_shader[] = { "precision mediump float; \n"
"varying vec4 v_color; \n"
"void main() \n"
"{ \n"
" gl_FragColor = v_color; \n"
"} \n" };
static const GLfloat cube_vertices[] = {
// front
-0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,
0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f,
// right
0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f,
// back
0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f,
// left
-0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f,
// top
-0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f,
// bottom
-0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f };
static const GLfloat cube_colors[] = {
// front, blue
0.0625f, 0.5742f, 0.9257f, 1.0f, 0.0625f, 0.5742f, 0.9257f, 1.0f,
0.0625f, 0.5742f, 0.9257f, 1.0f, 0.0625f, 0.5742f, 0.9257f, 1.0f,
0.0625f, 0.5742f, 0.9257f, 1.0f, 0.0625f, 0.5742f, 0.9257f, 1.0f,
// right, purple
0.8549f, 0.4471f, 0.9176f, 1.0f, 0.8549f, 0.4471f, 0.9176f, 1.0f,
0.8549f, 0.4471f, 0.9176f, 1.0f, 0.8549f, 0.4471f, 0.9176f, 1.0f,
0.8549f, 0.4471f, 0.9176f, 1.0f, 0.8549f, 0.4471f, 0.9176f, 1.0f,
// back, yellow
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
// left, yellow
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
0.9098f, 0.8706f, 0.4118f, 1.0f, 0.9098f, 0.8706f, 0.4118f, 1.0f,
// top, orange
0.8980f, 0.4627f, 0.1922f, 1.0f, 0.8980f, 0.4627f, 0.1922f, 1.0f,
0.8980f, 0.4627f, 0.1922f, 1.0f, 0.8980f, 0.4627f, 0.1922f, 1.0f,
0.8980f, 0.4627f, 0.1922f, 1.0f, 0.8980f, 0.4627f, 0.1922f, 1.0f,
// bottom, green
0.1921f, 0.8981f, 0.3019f, 1.0f, 0.1921f, 0.8981f, 0.3019f, 1.0f,
0.1921f, 0.8981f, 0.3019f, 1.0f, 0.1921f, 0.8981f, 0.3019f, 1.0f,
0.1921f, 0.8981f, 0.3019f, 1.0f, 0.1921f, 0.8981f, 0.3019f, 1.0f, };
static void CheckGlError(const char* operation) {
for (GLint error = glGetError(); error; error = glGetError()) {
LOGI("after %s() glError (0x%x)", operation, error);
}
}
static void onPoseAvailable(TangoPoseData *pose){
glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f),
glm::vec3(pose->translation[0]*-1.0f, pose->translation[2]*-1.0f,
pose->translation[1] - 6.0f));
glm::quat rotationQuaterion = glm::quat(pose->orientation[3],
pose->orientation[0], pose->orientation[2],
pose->orientation[1]);
glm::mat4 rotationMatrix = glm::mat4_cast(rotationQuaterion);
modelview_matrix = translateMatrix * rotationMatrix;
}
GLuint LoadShader(GLenum shader_type, const char* shader_source) {
GLuint shader = glCreateShader(shader_type);
if (shader) {
glShaderSource(shader, 1, &shader_source, NULL);
glCompileShader(shader);
GLint status = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
GLint info_length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_length);
if (info_length) {
char* buffer = (char*) malloc(info_length * sizeof(char));
if (buffer) {
glGetShaderInfoLog(shader, info_length, NULL, buffer);
}
}
glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
GLuint CreateProgram(const char* vertex_shader_source,
const char* fragment_shader_source) {
GLuint vertex_shader = LoadShader(GL_VERTEX_SHADER, vertex_shader_source);
if (!vertex_shader) {
return 0;
}
GLuint fragment_shader = LoadShader(GL_FRAGMENT_SHADER,
fragment_shader_source);
if (!fragment_shader) {
return 0;
}
GLuint program = glCreateProgram();
if (program) {
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glBindAttribLocation(program, 0, "a_position");
glBindAttribLocation(program, 1, "a_color");
glLinkProgram(program);
GLint status = 0;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (!status) {
GLint info_length = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_length);
if (info_length) {
char* buffer = (char*) malloc(info_length * sizeof(char));
glGetProgramInfoLog(program, info_length, NULL, buffer);
}
glDeleteProgram(program);
program = 0;
}
}
return program;
}
bool SetupTango() {
int i;
TangoConfig* config;
if (TangoService_initialize() != 0) {
LOGI("TangoService_initialize(): Failed");
return false;
}
//Allocate a TangoConfig instance
if ((config = TangoConfig_alloc()) == NULL) {
LOGI("TangoService_allocConfig(): Failed");
return false;
}
//Report the current TangoConfig
LOGI("TangoConfig:%s", TangoConfig_toString(config));
//Lock in this configuration
if(TangoService_lockConfig(config)!=0){
LOGI("TangoService_lockConfig(): Failed");
return false;
}
//Attach the onPoseAvailable callback.
if(TangoService_connectOnPoseAvailable(onPoseAvailable)!=0){
LOGI("TangoService_connectOnPoseAvailable(): Failed");
return false;
}
//Connect to the Tango Service
TangoService_connect();
LOGI("Tango Service connectOnPoseAvailable succeeded!");
return true;
}
bool SetupGraphics(int w, int h) {
glClearColor(0, 0, 0, 1.0f);
glEnable (GL_CULL_FACE);
glEnable (GL_DEPTH_TEST);
program_id = CreateProgram(vertex_shader, fragment_shader);
projection_matrix = glm::perspective(75.0f, (GLfloat) w / h, 0.01f, 10.0f);
glViewport(0, 0, w, h);
LOGI("SetupGraphics(%d, %d): Succeeded", w, h);
return true;
}
bool RenderFrame() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program_id);
glVertexAttribPointer(position_id, 3, GL_FLOAT, GL_FALSE, 0, cube_vertices);
glEnableVertexAttribArray(position_id);
glVertexAttribPointer(color_id, 4, GL_FLOAT, GL_FALSE, 0, cube_colors);
glEnableVertexAttribArray(color_id);
mvp_matrix_id = glGetUniformLocation(program_id, "u_mvp_matrix");
position_id = glGetAttribLocation(program_id, "a_position");
color_id = glGetAttribLocation(program_id, "a_color");
mvp_matrix = projection_matrix * modelview_matrix;
glUniformMatrix4fv(mvp_matrix_id, 1, false, glm::value_ptr(mvp_matrix));
glDrawArrays(GL_TRIANGLES, 0, 36);
return true;
}
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_com_google_tango_tangojnimotiontracking_TangoJNINative_init(
JNIEnv * env, jobject obj, jint width, jint height)
{
SetupTango();
SetupGraphics(width, height);
}
JNIEXPORT void JNICALL Java_com_google_tango_tangojnimotiontracking_TangoJNINative_render(
JNIEnv * env, jobject obj)
{
RenderFrame();
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>//===- Test.cpp -----------------------------------------------------------===//
//
// The pat Team
//
// This file is distributed under the New BSD License.
// See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <pat/pat.h>
#include <pat/Listeners/PrettyResultPrinter.h>
#include <pat/Listeners/CSVResultPrinter.h>
#include <pat/Support/Path.h>
#include <time.h>
#include <cassert>
#include <unistd.h>
#include <string>
#include <cstdlib>
using namespace pat;
//===----------------------------------------------------------------------===//
// Helper Functions
//===----------------------------------------------------------------------===//
static inline void help(int pArgc, char* pArgv[])
{
testing::Log::getOStream() << "Usage:\n"
<< "\t" << pArgv[0] << " [options...]\n\n"
<< "Options:\n"
<< "\t-c [file] toutput CSV to [file]\n"
<< "\t-h Show this help manual\n";
}
//===----------------------------------------------------------------------===//
// Test
//===----------------------------------------------------------------------===//
Test::~Test()
{
// MUST KEEP THIS DESTRUCTOR
}
void Test::run()
{
this->TestBody();
}
void Test::Initialize(int* pArgc, char* pArgv[])
{
// Choice printer
int opt;
std::string csv_file;
while ((opt = getopt(*pArgc, pArgv, "c:h")) != -1 ) {
switch (opt) {
case 'c':
csv_file = optarg;
break;
case 'h':
default:
help(*pArgc, pArgv);
return;
}
}
if (!csv_file.empty()) {
CSVResultPrinter* printer = new CSVResultPrinter();
if (printer->open(csv_file)) {
testing::UnitTest::self()->repeater().add(printer);
}
else {
testing::Log::getOStream() << "Failed to open file `" << csv_file << "`\n";
delete printer;
}
}
else
testing::UnitTest::self()->repeater().add(new PrettyResultPrinter());
// Choice runnable tests
Path progname(pArgv[0]);
progname = progname.filename();
if (!testing::UnitTest::self()->addRunCase(progname.native()))
testing::UnitTest::self()->addAllRunCases();
}
void Test::RunAll()
{
testing::UnitTest::self()->RunAll();
}
void Test::Sleep(int pMS)
{
assert(pMS > 0 && "Cannot sleep zero milliseconds");
struct timespec ts = { pMS / 1000, (pMS % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
}
<commit_msg>Fix typo.<commit_after>//===- Test.cpp -----------------------------------------------------------===//
//
// The pat Team
//
// This file is distributed under the New BSD License.
// See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <pat/pat.h>
#include <pat/Listeners/PrettyResultPrinter.h>
#include <pat/Listeners/CSVResultPrinter.h>
#include <pat/Support/Path.h>
#include <time.h>
#include <cassert>
#include <unistd.h>
#include <string>
#include <cstdlib>
using namespace pat;
//===----------------------------------------------------------------------===//
// Helper Functions
//===----------------------------------------------------------------------===//
static inline void help(int pArgc, char* pArgv[])
{
testing::Log::getOStream() << "Usage:\n"
<< "\t" << pArgv[0] << " [options...]\n\n"
<< "Options:\n"
<< "\t-c [file] toutput CSV to [file]\n"
<< "\t-h Show this help manual\n";
}
//===----------------------------------------------------------------------===//
// Test
//===----------------------------------------------------------------------===//
Test::~Test()
{
// MUST KEEP THIS DESTRUCTOR
}
void Test::run()
{
this->TestBody();
}
void Test::Initialize(int* pArgc, char* pArgv[])
{
// Choose user's printer
int opt;
std::string csv_file;
while ((opt = getopt(*pArgc, pArgv, "c:h")) != -1 ) {
switch (opt) {
case 'c':
csv_file = optarg;
break;
case 'h':
default:
help(*pArgc, pArgv);
return;
}
}
if (!csv_file.empty()) {
CSVResultPrinter* printer = new CSVResultPrinter();
if (printer->open(csv_file)) {
testing::UnitTest::self()->repeater().add(printer);
}
else {
testing::Log::getOStream() << "Failed to open file `" << csv_file << "`\n";
delete printer;
}
}
else
testing::UnitTest::self()->repeater().add(new PrettyResultPrinter());
// Choose runnable tests
Path progname(pArgv[0]);
progname = progname.filename();
if (!testing::UnitTest::self()->addRunCase(progname.native()))
testing::UnitTest::self()->addAllRunCases();
}
void Test::RunAll()
{
testing::UnitTest::self()->RunAll();
}
void Test::Sleep(int pMS)
{
assert(pMS > 0 && "Cannot sleep zero milliseconds");
struct timespec ts = { pMS / 1000, (pMS % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Doxygen plugin for Qt Creator
**
** Copyright (c) 2009 Kevin Tanguy ([email protected]).
**
** This plugin 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 plugin 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 General Public License
** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>.
**/
#include "doxygen.h"
#include <QObject>
#include <plugins/cppeditor/cppeditorconstants.h>
#include <plugins/cpptools/cpptoolsconstants.h>
#include <plugins/cpptools/cppmodelmanagerinterface.h>
#include <plugins/texteditor/basetexteditor.h>
#include <libs/extensionsystem/pluginmanager.h>
#include <plugins/coreplugin/icore.h>
#include <plugins/coreplugin/uniqueidmanager.h>
#include <plugins/coreplugin/mimedatabase.h>
#include <plugins/coreplugin/actionmanager/actionmanager.h>
#include <plugins/coreplugin/editormanager/ieditor.h>
#include <plugins/coreplugin/editormanager/editormanager.h>
#include <libs/cplusplus/Overview.h>
#include <shared/cplusplus/Scope.h>
#include <shared/cplusplus/Symbols.h>
#include <shared/cplusplus/Names.h>
#include <QString>
#include <QStringList>
#include <QFile>
#include <QFileInfo>
#include <QDebug>
#include <QRegExp>
#include <plugins/projectexplorer/project.h>
#include <plugins/projectexplorer/projectexplorer.h>
#include <plugins/projectexplorer/session.h>
#include <plugins/projectexplorer/projectexplorerconstants.h>
#include <cplusplus/CppDocument.h>
#include <cplusplus/CppBindings.h>
using namespace CPlusPlus;
using namespace CppHelper;
using namespace CppHelper::Internal;
using namespace ProjectExplorer;
Doxygen::Doxygen* Doxygen::m_instance = 0;
Doxygen::Doxygen()
{
}
Doxygen* Doxygen::instance()
{
if (!m_instance)
m_instance = new Doxygen();
return m_instance;
}
QStringList scopesForSymbol(const Symbol* symbol)
{
Scope *scope = symbol->scope();
QStringList scopes;
for (; scope; scope = scope->enclosingScope())
{
Symbol *owner = scope->owner();
if (owner && owner->name() && ! scope->isEnumScope())
{
Name *name = owner->name();
Overview overview;
overview.setShowArgumentNames(false);
overview.setShowReturnTypes(false);
scopes.prepend(overview.prettyName(name));
}
}
return scopes;
}
Symbol* currentSymbol(Core::IEditor *editor)
{
int line = editor->currentLine();
int column = editor->currentColumn();
CppTools::CppModelManagerInterface *modelManager =
ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
if (!modelManager)
return 0;
const Snapshot snapshot = modelManager->snapshot();
Document::Ptr doc = snapshot.value(editor->file()->fileName());
if (!doc)
return 0;
return doc->findSymbolAt(line, column);
}
void Doxygen::createDocumentationDoxygen() const
{
const Core::EditorManager *editorManager = Core::EditorManager::instance();
Core::IEditor *editor = editorManager->currentEditor();
// Catch hold of the plugin-manager
ExtensionSystem::PluginManager* pm
= ExtensionSystem::PluginManager::instance();
// Look for the ProjectExplorerPlugin object
ProjectExplorer::ProjectExplorerPlugin* projectExplorerPlugin
= pm->getObject<ProjectExplorer::ProjectExplorerPlugin>();
// Fetch a list of all open projects
QList<ProjectExplorer::Project*> projects
= projectExplorerPlugin->session()->projects();
// Project root directory
QString projectRoot;
// Attempt to find our project
Q_FOREACH(ProjectExplorer::Project* project, projects)
{
QStringList files = project->files(Project::ExcludeGeneratedFiles); // ProjectExplorer::Project::FilesMode::ExcludeGeneratedFiles
// is it our project ?
if(files.contains(editor->file()->fileName()))
{
// YES! get the .pro and remove the directory part from our filename
// TODO, check if it is smart... (it's not really.)
Q_FOREACH(QString f, files)
{
if(f.contains(QRegExp(".pro$")))
{
projectRoot = f.section('/', 0, -2);
if(projectRoot.size()) projectRoot.append("/");
continue;
}
}
if(projectRoot.size()) continue;
}
}
Symbol *lastSymbol = currentSymbol(editor);
if (!lastSymbol || !lastSymbol->scope())
return;
/// scopes.at(0) = class name
/// scopes.at(1) = method name + (...) <-- analyse this
QStringList scopes = scopesForSymbol(lastSymbol);
Overview overview;
overview.setShowArgumentNames(true);
overview.setShowReturnTypes(true);
overview.setShowFullyQualifiedNamed(true);
overview.setShowFunctionSignatures(true);
Name *name = lastSymbol->name();
scopes.append(overview.prettyName(name));
QString genericBeginNoindent = "/**\n* @brief \n*\n";
QString genericBegin = " /**\n * @brief \n *\n";
QString shortBeginNoindent = "/** ";
QString shortBegin = " /** ";
QString docToWrite;
if(lastSymbol->isClass())
{
QString fileName = editor->file()->fileName().remove(0, editor->file()->fileName().lastIndexOf("/") + 1);
QString fileNameProj = editor->file()->fileName().remove(projectRoot);
docToWrite += genericBeginNoindent;
docToWrite += "* @class " + overview.prettyName(name) + " " + fileName + " \"" + fileNameProj + "\"";
docToWrite += "\n*/\n";
}
else if(lastSymbol->isTypedef())
{
docToWrite += shortBeginNoindent;
docToWrite += "@typedef " + overview.prettyName(name);
docToWrite += " */\n";
}
else if(lastSymbol->isEnum())
{
if(lastSymbol->scope()->isClassScope())
{
docToWrite += genericBegin;
docToWrite += " * @enum " + overview.prettyName(name);
docToWrite += " */\n";
}
else
{
docToWrite += genericBeginNoindent;
docToWrite += "@enum " + overview.prettyName(name);
docToWrite += "\n*/\n";
}
}
else if(lastSymbol->isArgument())
{
docToWrite += shortBegin;
docToWrite += " ARG*/\n";
}
// Here comes the bitch.
else if(lastSymbol->isDeclaration())
{
overview.setShowArgumentNames(true);
overview.setShowReturnTypes(false);
overview.setShowFullyQualifiedNamed(true);
overview.setShowFunctionSignatures(true);
QString arglist = overview.prettyType(lastSymbol->type(), name);
docToWrite += genericBegin;
// if variable, do it quickly...
if(!arglist.contains('('))
{
docToWrite += " * @var " + overview.prettyName(name) + "\n */\n";
}
else
{
docToWrite += " * @fn " + overview.prettyName(name) + "\n";
// Check parameters
// Do it the naive way first before finding better in the API
// TODO, check throw()...
arglist.remove(0, arglist.indexOf("(") + 1);
arglist.remove(arglist.lastIndexOf(")"), arglist.size() - arglist.lastIndexOf(")"));
QStringList args = arglist.trimmed().split(',', QString::SkipEmptyParts);
Q_FOREACH(QString singleArg, args)
{
if(singleArg.contains('>'))
{
singleArg.remove(0, singleArg.lastIndexOf('>') + 1);
}
if(singleArg.contains('='))
{
singleArg.remove(singleArg.size() - singleArg.lastIndexOf('='));
}
singleArg.replace("*","");
singleArg.replace("&","");
docToWrite += " * @arg " + singleArg.section(' ', - 1) + "\n";
}
// And now check the return type
overview.setShowArgumentNames(false);
overview.setShowReturnTypes(true);
overview.setShowFullyQualifiedNamed(false);
overview.setShowFunctionSignatures(false);
arglist = overview.prettyType(lastSymbol->type(), name);
if( (overview.prettyName(name) != scopes.front()) && (overview.prettyName(name).at(0) != '~') )
{
QRegExp rx("void *");
rx.setPatternSyntax(QRegExp::Wildcard);
if(!rx.exactMatch(arglist))
{
arglist.chop(arglist.size() - arglist.lastIndexOf(' '));
docToWrite += " * @return " + arglist + "\n";
}
}
docToWrite += " */\n";
}
}
// Write the documentation in the editor
TextEditor::BaseTextEditor *editorWidget = qobject_cast<TextEditor::BaseTextEditor*>(
editorManager->currentEditor()->widget());
if (editorWidget)
{
editorWidget->moveCursor(QTextCursor::StartOfBlock);
editorWidget->insertPlainText(docToWrite);
}
}
<commit_msg>tiny fix for @enum and template return type workarround<commit_after>/**************************************************************************
**
** This file is part of Doxygen plugin for Qt Creator
**
** Copyright (c) 2009 Kevin Tanguy ([email protected]).
**
** This plugin 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 plugin 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 General Public License
** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>.
**/
#include "doxygen.h"
#include <QObject>
#include <plugins/cppeditor/cppeditorconstants.h>
#include <plugins/cpptools/cpptoolsconstants.h>
#include <plugins/cpptools/cppmodelmanagerinterface.h>
#include <plugins/texteditor/basetexteditor.h>
#include <libs/extensionsystem/pluginmanager.h>
#include <plugins/coreplugin/icore.h>
#include <plugins/coreplugin/uniqueidmanager.h>
#include <plugins/coreplugin/mimedatabase.h>
#include <plugins/coreplugin/actionmanager/actionmanager.h>
#include <plugins/coreplugin/editormanager/ieditor.h>
#include <plugins/coreplugin/editormanager/editormanager.h>
#include <libs/cplusplus/Overview.h>
#include <shared/cplusplus/Scope.h>
#include <shared/cplusplus/Symbols.h>
#include <shared/cplusplus/Names.h>
#include <QString>
#include <QStringList>
#include <QFile>
#include <QFileInfo>
#include <QDebug>
#include <QRegExp>
#include <plugins/projectexplorer/project.h>
#include <plugins/projectexplorer/projectexplorer.h>
#include <plugins/projectexplorer/session.h>
#include <plugins/projectexplorer/projectexplorerconstants.h>
#include <cplusplus/CppDocument.h>
#include <cplusplus/CppBindings.h>
using namespace CPlusPlus;
using namespace CppHelper;
using namespace CppHelper::Internal;
using namespace ProjectExplorer;
Doxygen::Doxygen* Doxygen::m_instance = 0;
Doxygen::Doxygen()
{
}
Doxygen* Doxygen::instance()
{
if (!m_instance)
m_instance = new Doxygen();
return m_instance;
}
QStringList scopesForSymbol(const Symbol* symbol)
{
Scope *scope = symbol->scope();
QStringList scopes;
for (; scope; scope = scope->enclosingScope())
{
Symbol *owner = scope->owner();
if (owner && owner->name() && ! scope->isEnumScope())
{
Name *name = owner->name();
Overview overview;
overview.setShowArgumentNames(false);
overview.setShowReturnTypes(false);
scopes.prepend(overview.prettyName(name));
}
}
return scopes;
}
Symbol* currentSymbol(Core::IEditor *editor)
{
int line = editor->currentLine();
int column = editor->currentColumn();
CppTools::CppModelManagerInterface *modelManager =
ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
if (!modelManager)
return 0;
const Snapshot snapshot = modelManager->snapshot();
Document::Ptr doc = snapshot.value(editor->file()->fileName());
if (!doc)
return 0;
return doc->findSymbolAt(line, column);
}
void Doxygen::createDocumentationDoxygen() const
{
const Core::EditorManager *editorManager = Core::EditorManager::instance();
Core::IEditor *editor = editorManager->currentEditor();
// Catch hold of the plugin-manager
ExtensionSystem::PluginManager* pm
= ExtensionSystem::PluginManager::instance();
// Look for the ProjectExplorerPlugin object
ProjectExplorer::ProjectExplorerPlugin* projectExplorerPlugin
= pm->getObject<ProjectExplorer::ProjectExplorerPlugin>();
// Fetch a list of all open projects
QList<ProjectExplorer::Project*> projects
= projectExplorerPlugin->session()->projects();
// Project root directory
QString projectRoot;
// Attempt to find our project
Q_FOREACH(ProjectExplorer::Project* project, projects)
{
QStringList files = project->files(Project::ExcludeGeneratedFiles); // ProjectExplorer::Project::FilesMode::ExcludeGeneratedFiles
// is it our project ?
if(files.contains(editor->file()->fileName()))
{
// YES! get the .pro and remove the directory part from our filename
// TODO, check if it is smart... (it's not really.)
Q_FOREACH(QString f, files)
{
if(f.contains(QRegExp(".pro$")))
{
projectRoot = f.section('/', 0, -2);
if(projectRoot.size()) projectRoot.append("/");
continue;
}
}
if(projectRoot.size()) continue;
}
}
Symbol *lastSymbol = currentSymbol(editor);
if (!lastSymbol || !lastSymbol->scope())
return;
/// scopes.at(0) = class name
/// scopes.at(1) = method name + (...) <-- analyse this
QStringList scopes = scopesForSymbol(lastSymbol);
Overview overview;
overview.setShowArgumentNames(true);
overview.setShowReturnTypes(true);
overview.setShowFullyQualifiedNamed(true);
overview.setShowFunctionSignatures(true);
Name *name = lastSymbol->name();
scopes.append(overview.prettyName(name));
QString genericBeginNoindent = "/**\n* @brief \n*\n";
QString genericBegin = " /**\n * @brief \n *\n";
QString shortBeginNoindent = "/** ";
QString shortBegin = " /** ";
QString docToWrite;
if(lastSymbol->isClass())
{
QString fileName = editor->file()->fileName().remove(0, editor->file()->fileName().lastIndexOf("/") + 1);
QString fileNameProj = editor->file()->fileName().remove(projectRoot);
docToWrite += genericBeginNoindent;
docToWrite += "* @class " + overview.prettyName(name) + " " + fileName + " \"" + fileNameProj + "\"";
docToWrite += "\n*/\n";
}
else if(lastSymbol->isTypedef())
{
docToWrite += shortBeginNoindent;
docToWrite += "@typedef " + overview.prettyName(name);
docToWrite += " */\n";
}
else if(lastSymbol->isEnum())
{
if(lastSymbol->scope()->isClassScope())
{
docToWrite += genericBegin;
docToWrite += " * @enum " + overview.prettyName(name);
docToWrite += " */\n";
}
else
{
docToWrite += genericBeginNoindent;
docToWrite += "* @enum " + overview.prettyName(name);
docToWrite += "\n*/\n";
}
}
else if(lastSymbol->isArgument())
{
docToWrite += shortBegin;
docToWrite += " ARG*/\n";
}
// Here comes the bitch.
else if(lastSymbol->isDeclaration())
{
overview.setShowArgumentNames(true);
overview.setShowReturnTypes(false);
overview.setShowFullyQualifiedNamed(true);
overview.setShowFunctionSignatures(true);
QString arglist = overview.prettyType(lastSymbol->type(), name);
docToWrite += genericBegin;
// if variable, do it quickly...
if(!arglist.contains('('))
{
docToWrite += " * @var " + overview.prettyName(name) + "\n */\n";
}
else
{
docToWrite += " * @fn " + overview.prettyName(name) + "\n";
// Check parameters
// Do it the naive way first before finding better in the API
// TODO, check throw()...
arglist.remove(0, arglist.indexOf("(") + 1);
arglist.remove(arglist.lastIndexOf(")"), arglist.size() - arglist.lastIndexOf(")"));
QStringList args = arglist.trimmed().split(',', QString::SkipEmptyParts);
Q_FOREACH(QString singleArg, args)
{
if(singleArg.contains('>'))
{
singleArg.remove(0, singleArg.lastIndexOf('>') + 1);
}
if(singleArg.contains('='))
{
singleArg.remove(singleArg.size() - singleArg.lastIndexOf('='));
}
singleArg.replace("*","");
singleArg.replace("&","");
docToWrite += " * @arg " + singleArg.section(' ', - 1) + "\n";
}
// And now check the return type
overview.setShowArgumentNames(false);
overview.setShowReturnTypes(true);
overview.setShowFullyQualifiedNamed(false);
overview.setShowFunctionSignatures(false);
arglist = overview.prettyType(lastSymbol->type(), name);
if( (overview.prettyName(name) != scopes.front()) && (overview.prettyName(name).at(0) != '~') )
{
QRegExp rx("void *");
rx.setPatternSyntax(QRegExp::Wildcard);
if(!rx.exactMatch(arglist))
{
// dirty workarround
int last;
if(arglist.contains('>'))
last = arglist.lastIndexOf('>') + 1;
else
last = arglist.lastIndexOf(' ');
arglist.chop(arglist.size() - last);
docToWrite += " * @return " + arglist + "\n";
}
}
docToWrite += " */\n";
}
}
// Write the documentation in the editor
TextEditor::BaseTextEditor *editorWidget = qobject_cast<TextEditor::BaseTextEditor*>(
editorManager->currentEditor()->widget());
if (editorWidget)
{
editorWidget->moveCursor(QTextCursor::StartOfBlock);
editorWidget->insertPlainText(docToWrite);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: template.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:57:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#ifndef CONFIGMGR_CONFIGTEMPLATE_HXX_
#define CONFIGMGR_CONFIGTEMPLATE_HXX_
#ifndef CONFIGMGR_CONFIGEXCEPT_HXX_
#include "configexcept.hxx"
#endif
#ifndef CONFIGMGR_CONFIGPATH_HXX_
#include "configpath.hxx"
#endif
#ifndef CONFIGMGR_ACCESSOR_HXX
#include "accessor.hxx"
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
struct IConfigTemplateManager;
class RequestOptions;
//-----------------------------------------------------------------------------
namespace data { class SetNodeAccess; }
//-----------------------------------------------------------------------------
namespace configuration
{
//-----------------------------------------------------------------------------
class Name;
class AbsolutePath;
//---------------------------------------------------------------------
typedef com::sun::star::uno::Type UnoType;
typedef com::sun::star::uno::Any UnoAny;
//-----------------------------------------------------------------------------
struct TemplateProvider_Impl;
class TemplateProvider
{
friend class SetElementFactory;
friend class TemplateImplHelper;
rtl::Reference<TemplateProvider_Impl> m_aImpl;
public:
typedef rtl::Reference< IConfigTemplateManager > TemplateManagerRef;
public:
TemplateProvider(); // creates an empty (invalid) template instance provider
TemplateProvider(TemplateManagerRef const & xProvider, RequestOptions const& xOptions);
TemplateProvider(TemplateProvider const& aOther);
TemplateProvider& operator=(TemplateProvider const& aOther);
~TemplateProvider();
bool isValid() const { return !!m_aImpl.is(); }
};
//-----------------------------------------------------------------------------
struct SpecialTemplateProvider_Impl;
class SpecialTemplateProvider
{
friend class TemplateImplHelper;
rtl::Reference<SpecialTemplateProvider_Impl> m_aImpl;
public:
explicit
SpecialTemplateProvider();
SpecialTemplateProvider(SpecialTemplateProvider const& aOther);
SpecialTemplateProvider& operator=(SpecialTemplateProvider const& aOther);
~SpecialTemplateProvider();
bool isValid() const { return !!m_aImpl.is(); }
};
//-----------------------------------------------------------------------------
class Template;
typedef rtl::Reference<Template> TemplateHolder;
/// provides information about the elements of a <type>Node</type> that is a Container ("set").
class Template : public salhelper::SimpleReferenceObject
{
Name m_aName;
Name m_aModule;
UnoType m_aInstanceType;
private:
explicit Template(Name const& aName, Name const& aModule,UnoType const& aType);
public:
/// checks if the type of an instance of this is known
bool isInstanceTypeKnown() const;
/// checks if this is a 'value' template <p> PRE: the instance type is known </p>
bool isInstanceValue() const;
/// get the UNO type for instances (primarily (only ?) for 'value' templates) <p> PRE: the instance type is known </p>
UnoType getInstanceType() const;
/// get the path where the template is located
OUString getPathString() const;
/// get the local name of the template
Name getName() const { return m_aName; }
/// get the package name of the template
Name getModule() const { return m_aModule; }
friend class TemplateImplHelper;
};
/// make a template instance that matches the given (simple) type
TemplateHolder makeSimpleTemplate(UnoType const& aType, SpecialTemplateProvider const& aProvider);
/// make a template instance that matches the given path. Assume that it represents a (complex) tree structure.
TemplateHolder makeTreeTemplate(OUString const& sName, OUString const& sModule, SpecialTemplateProvider const& aProvider);
/// make a template instance that matches the elements of the given set. Ensures that the element type is known
TemplateHolder makeSetElementTemplate(data::SetNodeAccess const& _aSet, TemplateProvider const& _aProvider);
//-----------------------------------------------------------------------------
}
}
#endif // CONFIGMGR_CONFIGTEMPLATE_HXX_
<commit_msg>INTEGRATION: CWS configrefactor01 (1.12.84); FILE MERGED 2007/01/12 17:51:20 mmeeks 1.12.84.2: RIP 'memory::Accessor' 2007/01/11 20:16:01 mmeeks 1.12.84.1: Submitted by: mmeeks More re-factoring, lots of locking rationalized, drastically reduced the mutex count, also removed ~300k interlocked increments with a non-interlocking SimpleReferencedObject base<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: template.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 14:24:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 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
*
************************************************************************/
#ifndef CONFIGMGR_CONFIGTEMPLATE_HXX_
#define CONFIGMGR_CONFIGTEMPLATE_HXX_
#ifndef CONFIGMGR_CONFIGEXCEPT_HXX_
#include "configexcept.hxx"
#endif
#ifndef CONFIGMGR_CONFIGPATH_HXX_
#include "configpath.hxx"
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _CONFIGMGR_UTILITY_HXX_
#include <utility.hxx>
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
struct IConfigTemplateManager;
class RequestOptions;
//-----------------------------------------------------------------------------
namespace data { class SetNodeAccess; }
//-----------------------------------------------------------------------------
namespace configuration
{
//-----------------------------------------------------------------------------
class Name;
class AbsolutePath;
//---------------------------------------------------------------------
typedef com::sun::star::uno::Type UnoType;
typedef com::sun::star::uno::Any UnoAny;
//-----------------------------------------------------------------------------
struct TemplateProvider_Impl;
class TemplateProvider
{
friend class SetElementFactory;
friend class TemplateImplHelper;
rtl::Reference<TemplateProvider_Impl> m_aImpl;
public:
typedef rtl::Reference< IConfigTemplateManager > TemplateManagerRef;
public:
TemplateProvider(); // creates an empty (invalid) template instance provider
TemplateProvider(TemplateManagerRef const & xProvider, RequestOptions const& xOptions);
TemplateProvider(TemplateProvider const& aOther);
TemplateProvider& operator=(TemplateProvider const& aOther);
~TemplateProvider();
bool isValid() const { return !!m_aImpl.is(); }
};
//-----------------------------------------------------------------------------
struct SpecialTemplateProvider_Impl;
class SpecialTemplateProvider
{
friend class TemplateImplHelper;
rtl::Reference<SpecialTemplateProvider_Impl> m_aImpl;
public:
explicit
SpecialTemplateProvider();
SpecialTemplateProvider(SpecialTemplateProvider const& aOther);
SpecialTemplateProvider& operator=(SpecialTemplateProvider const& aOther);
~SpecialTemplateProvider();
bool isValid() const { return !!m_aImpl.is(); }
};
//-----------------------------------------------------------------------------
class Template;
typedef rtl::Reference<Template> TemplateHolder;
/// provides information about the elements of a <type>Node</type> that is a Container ("set").
class Template : public configmgr::SimpleReferenceObject
{
Name m_aName;
Name m_aModule;
UnoType m_aInstanceType;
private:
explicit Template(Name const& aName, Name const& aModule,UnoType const& aType);
public:
/// checks if the type of an instance of this is known
bool isInstanceTypeKnown() const;
/// checks if this is a 'value' template <p> PRE: the instance type is known </p>
bool isInstanceValue() const;
/// get the UNO type for instances (primarily (only ?) for 'value' templates) <p> PRE: the instance type is known </p>
UnoType getInstanceType() const;
/// get the path where the template is located
OUString getPathString() const;
/// get the local name of the template
Name getName() const { return m_aName; }
/// get the package name of the template
Name getModule() const { return m_aModule; }
friend class TemplateImplHelper;
};
/// make a template instance that matches the given (simple) type
TemplateHolder makeSimpleTemplate(UnoType const& aType, SpecialTemplateProvider const& aProvider);
/// make a template instance that matches the given path. Assume that it represents a (complex) tree structure.
TemplateHolder makeTreeTemplate(OUString const& sName, OUString const& sModule, SpecialTemplateProvider const& aProvider);
/// make a template instance that matches the elements of the given set. Ensures that the element type is known
TemplateHolder makeSetElementTemplate(data::SetNodeAccess const& _aSet, TemplateProvider const& _aProvider);
//-----------------------------------------------------------------------------
}
}
#endif // CONFIGMGR_CONFIGTEMPLATE_HXX_
<|endoftext|> |
<commit_before>// 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.
#ifndef __STOUT_OS_RAW_ENVIRONMENT_HPP__
#define __STOUT_OS_RAW_ENVIRONMENT_HPP__
#ifdef __APPLE__
#include <crt_externs.h> // For _NSGetEnviron().
#elif !defined(__WINDOWS__)
// Need to declare 'environ' pointer for platforms that are not OS X or Windows.
extern char** environ;
#endif
// NOTE: the `os::raw` namespace contains a family of simple wrapper functions
// for getting environment data from either Windows or Unix machines. For
// example, `os::raw::environment` returns an "unstructured" `char**` that
// contains the raw environment variables of the executing process. Accessing
// "structured" version of this function, `os::environment`, returns a
// `map<string, string>` instead. This family of functions exists in the
// `os::raw` namespace because of the unstructured nature of their return
// values.
//
// WARNING: these functions are called `environment` and not `environ` because
// on Windows, `environ` is a macro, and not an `extern char**` as it is in the
// POSIX standard. The existance of this macro on Windows makes it impossible
// to use a function called `os::environ`.
namespace os {
namespace raw {
inline char** environment()
{
// Accessing the list of environment variables is platform-specific.
// On OS X, the 'environ' symbol isn't visible to shared libraries,
// so we must use the _NSGetEnviron() function (see 'man environ' on
// OS X). On other platforms, it's fine to access 'environ' from
// shared libraries.
#ifdef __APPLE__
return *_NSGetEnviron();
#else
// NOTE: the correct style for this expression would be `::environ`, but we
// leave it out because `environ` is a macro on Windows, and the `::` will
// break the build.
return environ;
#endif
}
// Returns the address of os::environment().
inline char*** environmentp()
{
// Accessing the list of environment variables is platform-specific.
// On OS X, the 'environ' symbol isn't visible to shared libraries,
// so we must use the _NSGetEnviron() function (see 'man environ' on
// OS X). On other platforms, it's fine to access 'environ' from
// shared libraries.
#ifdef __APPLE__
return _NSGetEnviron();
#else
// NOTE: the correct style for this expression would be `environ`, but we
// leave it out because `environ` is a macro on Windows, and the `::` will
// break the build.
return &environ;
#endif
}
} // namespace raw {
} // namespace os {
#endif // __STOUT_OS_RAW_ENVIRONMENT_HPP__
<commit_msg>Added an abstraction for Envp pointer expected by exec routines.<commit_after>// 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.
#ifndef __STOUT_OS_RAW_ENVIRONMENT_HPP__
#define __STOUT_OS_RAW_ENVIRONMENT_HPP__
#include <string.h>
#include <string>
#include <stout/foreach.hpp>
#include <stout/json.hpp>
#include <stout/stringify.hpp>
#ifdef __APPLE__
#include <crt_externs.h> // For _NSGetEnviron().
#elif !defined(__WINDOWS__)
// Need to declare 'environ' pointer for platforms that are not OS X or Windows.
extern char** environ;
#endif
// NOTE: the `os::raw` namespace contains a family of simple wrapper functions
// for getting environment data from either Windows or Unix machines. For
// example, `os::raw::environment` returns an "unstructured" `char**` that
// contains the raw environment variables of the executing process. Accessing
// "structured" version of this function, `os::environment`, returns a
// `map<string, string>` instead. This family of functions exists in the
// `os::raw` namespace because of the unstructured nature of their return
// values.
//
// WARNING: these functions are called `environment` and not `environ` because
// on Windows, `environ` is a macro, and not an `extern char**` as it is in the
// POSIX standard. The existance of this macro on Windows makes it impossible
// to use a function called `os::environ`.
namespace os {
namespace raw {
inline char** environment()
{
// Accessing the list of environment variables is platform-specific.
// On OS X, the 'environ' symbol isn't visible to shared libraries,
// so we must use the _NSGetEnviron() function (see 'man environ' on
// OS X). On other platforms, it's fine to access 'environ' from
// shared libraries.
#ifdef __APPLE__
return *_NSGetEnviron();
#else
// NOTE: the correct style for this expression would be `::environ`, but we
// leave it out because `environ` is a macro on Windows, and the `::` will
// break the build.
return environ;
#endif
}
// Returns the address of os::environment().
inline char*** environmentp()
{
// Accessing the list of environment variables is platform-specific.
// On OS X, the 'environ' symbol isn't visible to shared libraries,
// so we must use the _NSGetEnviron() function (see 'man environ' on
// OS X). On other platforms, it's fine to access 'environ' from
// shared libraries.
#ifdef __APPLE__
return _NSGetEnviron();
#else
// NOTE: the correct style for this expression would be `environ`, but we
// leave it out because `environ` is a macro on Windows, and the `::` will
// break the build.
return &environ;
#endif
}
// Represents the environment variable list expected by 'exec'
// routines. The environment variable list is an array of pointers
// that point to null-terminated strings. The array of pointers must
// be terminated by a nullptr. To use this abstraction, see the
// following example:
//
// map<string, string> environment = {
// {"key1", "value1"},
// {"key2", "value2"}
// };
// os::raw::Envp envp(environment);
// execle("/bin/sh", "sh", "-c", "echo hello", envp);
class Envp
{
public:
Envp(Envp&& that)
: envp(that.envp),
size(that.size)
{
that.envp = nullptr;
that.size = 0;
}
template <typename Map>
explicit Envp(const Map& map)
{
size = map.size();
// NOTE: We add 1 to the size for a `nullptr` terminator.
envp = new char*[size + 1];
size_t index = 0;
for (auto it = map.begin(); it != map.end(); ++it) {
std::string entry = stringify(it->first) + "=" + stringify(it->second);
envp[index] = new char[entry.size() + 1];
::memcpy(envp[index], entry.c_str(), entry.size() + 1);
++index;
}
envp[index] = nullptr;
}
explicit Envp(const JSON::Object& object)
{
size = object.values.size();
// NOTE: We add 1 to the size for a `nullptr` terminator.
envp = new char*[size + 1];
size_t index = 0;
foreachpair (const std::string& key,
const JSON::Value& value,
object.values) {
std::string entry = key + "=" + value.as<JSON::String>().value;
envp[index] = new char[entry.size() + 1];
::memcpy(envp[index], entry.c_str(), entry.size() + 1);
++index;
}
envp[index] = nullptr;
}
~Envp()
{
if (envp == nullptr) {
return;
}
for (size_t i = 0; i < size; i++) {
delete[] envp[i];
}
delete[] envp;
}
operator char**()
{
return envp;
}
private:
Envp(const Envp&) = delete;
Envp& operator=(const Envp&) = delete;
char **envp;
size_t size;
};
} // namespace raw {
} // namespace os {
#endif // __STOUT_OS_RAW_ENVIRONMENT_HPP__
<|endoftext|> |
<commit_before> /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
* Copyright (c) 2014, RadiantBlue Technologies, Inc.
* Copyright (c) 2014, Centrum Wiskunde Informatica
*
* 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 copyright holder(s) 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.
*
* $Id$
*/
#ifndef POINT_CLOUD_QUALITY_HPP
#define POINT_CLOUD_QUALITY_HPP
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/search/kdtree.h>
#include <pcl/quality/quality_metrics.h>
//using namespace std;
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
using namespace pcl::search;
using namespace pcl::quality;
namespace pcl{
namespace quality{
/**
\brief helper function to convert RGB to YUV
*/
template<typename PointT> void
convertRGBtoYUV(const PointT &in_rgb, float * out_yuv)
{
// color space conversion to YUV on a 0-1 scale
out_yuv[0] = (0.299 * in_rgb.r + 0.587 * in_rgb.g + 0.114 * in_rgb.b)/255.0;
out_yuv[1] = (-0.147 * in_rgb.r - 0.289 * in_rgb.g + 0.436 * in_rgb.b)/255.0;
out_yuv[2] = (0.615 * in_rgb.r - 0.515 * in_rgb.g - 0.100 * in_rgb.b)/255.0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* function to compute quality metric with bit settings
* @param cloud_a original cloud
* @param cloud_b decoded cloud
* @param qual_metric return updated quality metric
* \note PointT typename of point used in point cloud
* \author Rufael Mekuria ([email protected])
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> void
computeQualityMetric (PointCloud<PointT> &cloud_a, PointCloud<PointT> &cloud_b, QualityMetric & qual_metric)
{
print_highlight (stderr, "Computing Quality Metrics for Point Clouds !!\n");
//! we log time past in computing the quality metric
TicToc tt;
tt.tic ();
// compare A to B
pcl::search::KdTree<PointT> tree_b;
tree_b.setInputCloud (cloud_b.makeShared ());
// geometric differences A -> B
float max_dist_a = -std::numeric_limits<float>::max ();
double rms_dist_a = 0;
// color differences A -> B
double psnr_colors_yuv[3] = {0.0,0.0,0.0};
double mse_colors_yuv[3] = {0.0,0.0,0.0};
// maximum color values needed to compute PSNR
double peak_yuv[3] = {0.0,0.0,0.0};
//! compute the maximum and mean square distance between each point in a to the nearest point in b
//! compute the mean square color error for each point in a to the nearest point in b
for (size_t i = 0; i < cloud_a.points.size (); ++i)
{
std::vector<int> indices (1);
std::vector<float> sqr_distances (1);
// search the most nearby point in the cloud_b
tree_b.nearestKSearch (cloud_a.points[i], 1, indices, sqr_distances);
// haussdorf geometric distance (Linf norm)
if (sqr_distances[0] > max_dist_a)
max_dist_a = sqr_distances[0];
// mean square geometric distance (L2 norm)
rms_dist_a+=sqr_distances[0];
////////////////////////////////////////////////////////////////
// compute quality metric for yuv colors
// 1. convert to RGB to YUV
// 2. compute accumulated square error colors a to b
////////////////////////////////////////////////////////////////
float out_yuv[3];
float in_yuv[3];
convertRGBtoYUV<PointT>(cloud_a.points[i],in_yuv);
convertRGBtoYUV<PointT>(cloud_b.points[indices[0]],out_yuv);
// calculate the maximum YUV components
for(int cc=0;cc<3;cc++)
if((in_yuv[cc] * in_yuv[cc]) > (peak_yuv[cc] * peak_yuv[cc]))
peak_yuv[cc] = in_yuv[cc];
mse_colors_yuv[0]+=((in_yuv[0] - out_yuv[0]) * (in_yuv[0] - out_yuv[0]));
mse_colors_yuv[1]+=((in_yuv[1] - out_yuv[1]) * (in_yuv[1] - out_yuv[1]));
mse_colors_yuv[2]+=((in_yuv[2] - out_yuv[2]) * (in_yuv[2] - out_yuv[2]));
}
// compare geometry of B to A (needed for symmetric metric)
pcl::search::KdTree<PointT> tree_a;
tree_a.setInputCloud (cloud_a.makeShared ());
float max_dist_b = -std::numeric_limits<float>::max ();
double rms_dist_b = 0;
for (size_t i = 0; i < cloud_b.points.size (); ++i)
{
std::vector<int> indices (1);
std::vector<float> sqr_distances (1);
tree_a.nearestKSearch (cloud_b.points[i], 1, indices, sqr_distances);
if (sqr_distances[0] > max_dist_b)
max_dist_b = sqr_distances[0];
// mean square distance
rms_dist_b+=sqr_distances[0];
}
////////////////////////////////////////////////////////////////
// calculate geometric error metrics
// 1. compute left and right haussdorf
// 2. compute left and right rms
// 3. compute symmetric haussdorf and rms
// 4. calculate psnr for symmetric rms error
////////////////////////////////////////////////////////////////
max_dist_a = std::sqrt (max_dist_a);
max_dist_b = std::sqrt (max_dist_b);
rms_dist_a = std::sqrt (rms_dist_a/cloud_a.points.size ());
rms_dist_b = std::sqrt (rms_dist_b/cloud_b.points.size ());
float dist_h = std::max (max_dist_a, max_dist_b);
float dist_rms = std::max (rms_dist_a , rms_dist_b);
/////////////////////////////////////////////////////////
//
// calculate peak signal to noise ratio,
// we assume the meshes are normalized per component and the peak energy therefore should approach 3
//
///////////////////////////////////////////////////////////
PointT l_max_signal;
PointT l_min_signal;
// calculate peak geometric signal value
getMinMax3D<PointT>(cloud_a,l_min_signal,l_max_signal);
// calculate max energy of point
float l_max_geom_signal_energy = l_max_signal.x * l_max_signal.x
+ l_max_signal.y * l_max_signal.y + l_max_signal.z * l_max_signal.z ;
float peak_signal_to_noise_ratio = 10 * std::log10( l_max_geom_signal_energy / (dist_rms * dist_rms));
// compute averages for color distortions
mse_colors_yuv[0] /= cloud_a.points.size ();
mse_colors_yuv[1] /= cloud_a.points.size ();
mse_colors_yuv[2] /= cloud_a.points.size ();
// compute PSNR for YUV colors
psnr_colors_yuv[0] = 10 * std::log10( (peak_yuv[0] * peak_yuv[0] )/mse_colors_yuv[0]);
psnr_colors_yuv[1] = 10 * std::log10( (peak_yuv[1] * peak_yuv[1] )/mse_colors_yuv[1]);
psnr_colors_yuv[2] = 10 * std::log10( (peak_yuv[2] * peak_yuv[2] )/mse_colors_yuv[2]);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms \n");
//print_info ("A->B: "); print_value ("%f\n", max_dist_a);
//print_info ("B->A: "); print_value ("%f\n", max_dist_b);
print_info ("Symmetric Geometric Hausdorff Distance: "); print_value ("%f", dist_h);
print_info (" ]\n\n");
//print_info ("A->B : "); print_value ("%f rms\n", rms_dist_a);
//print_info ("B->A: "); print_value ("%f rms\n", rms_dist_b);
print_info ("Symmetric Geometric Root Mean Square Distance: "); print_value ("%f\n", dist_rms);
print_info ("Geometric PSNR: "); print_value ("%f dB", peak_signal_to_noise_ratio);
print_info (" ]\n\n");
print_info ("A->B color psnr Y: "); print_value ("%f dB ", (float) psnr_colors_yuv[0]);
print_info ("A->B color psnr U: "); print_value ("%f dB ", (float) psnr_colors_yuv[1]);
print_info ("A->B color psnr V: "); print_value ("%f dB ", (float) psnr_colors_yuv[2]);
print_info (" ]\n");
qual_metric.in_point_count = cloud_a.points.size ();
qual_metric.out_point_count = cloud_b.points.size ();
//////////////////////////////////////////////////////
//
// store the quality metrics in the return values
//
////////////////////////////////////////////////////
// geometric quality metrics [haussdorf Linf]
qual_metric.left_hausdorff = max_dist_a;
qual_metric.right_hausdorff = max_dist_b;
qual_metric.symm_hausdorff = dist_h;
// geometric quality metrics [rms L2]
qual_metric.left_rms = rms_dist_a;
qual_metric.right_rms = rms_dist_b;
qual_metric.symm_rms = dist_rms;
qual_metric.psnr_db = peak_signal_to_noise_ratio ;
// color quality metric (non-symmetric, L2)
qual_metric.psnr_yuv[0]= psnr_colors_yuv[0];
qual_metric.psnr_yuv[1]= psnr_colors_yuv[1];
qual_metric.psnr_yuv[2]= psnr_colors_yuv[2];
}
//! function to print a header to csv file for logging the quality characteristics
void
QualityMetric::print_csv_line(const std::string &compression_setting_arg, std::ostream &csv_ostream)
{
csv_ostream << compression_setting_arg << std::string(";")
<< in_point_count << std::string(";")
<< out_point_count << std::string(";")
<< compressed_size << std::string(";")
<< compressed_size/ (1.0 * out_point_count) << std::string(";")
<< byte_count_octree_layer/ (1.0 * out_point_count) << std::string(";")
<< byte_count_centroid_layer / (1.0 * out_point_count) << std::string(";")
<< byte_count_color_layer / (1.0 * out_point_count) << std::string(";")
<< symm_rms << std::string(";")
<< symm_hausdorff << std::string(";")
<< psnr_db << std::string(";")
<< psnr_yuv[0] << std::string(";")
<< psnr_yuv[1] << std::string(";")
<< psnr_yuv[2] << std::string(";")
<< encoding_time_ms << std::string(";")
<< decoding_time_ms << std::string(";")
<< std::endl;
}
//! function to print a header to csv file for logging the quality characteristics
void
QualityMetric::print_csv_header(std::ostream &csv_ostream)
{
csv_ostream << "compression setting; "
<< std::string("in point count;")
<< std::string("out point count;")
<< std::string("compressed_byte_size;")
<< std::string("compressed_byte_size_per_output_point;")
<< std::string("octree_byte_size_per_voxel;")
<< std::string("centroid_byte_size_per_voxel;")
<< std::string("color_byte_size_per_voxel;")
<< std::string("symm_rms;")
<< std::string("symm_haussdorff;")
<< std::string("psnr_db;")
<< std::string("psnr_colors_y;")
<< std::string("psnr_colors_u;")
<< std::string("psnr_colors_v;")
<< std::string("encoding_time_ms;")
<< std::string("decoding_time_ms;")
<< std::endl;
}
} //~ namespace quality
}//~ namespace pcl
#endif
<commit_msg>added code to quality metric to handle unusual inputs and account PSNR difference<commit_after> /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
* Copyright (c) 2014, RadiantBlue Technologies, Inc.
* Copyright (c) 2014, Centrum Wiskunde Informatica
*
* 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 copyright holder(s) 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.
*
* $Id$
*/
#ifndef POINT_CLOUD_QUALITY_HPP
#define POINT_CLOUD_QUALITY_HPP
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/search/kdtree.h>
#include <pcl/quality/quality_metrics.h>
//using namespace std;
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
using namespace pcl::search;
using namespace pcl::quality;
namespace pcl{
namespace quality{
/**
\brief helper function to convert RGB to YUV
*/
template<typename PointT> void
convertRGBtoYUV(const PointT &in_rgb, float * out_yuv)
{
// color space conversion to YUV on a 0-1 scale
out_yuv[0] = (0.299 * in_rgb.r + 0.587 * in_rgb.g + 0.114 * in_rgb.b) / 255.0;
out_yuv[1] = (-0.147 * in_rgb.r - 0.289 * in_rgb.g + 0.436 * in_rgb.b) / 255.0;
out_yuv[2] = (0.615 * in_rgb.r - 0.515 * in_rgb.g - 0.100 * in_rgb.b) / 255.0;
// double check for no negative values or values larger than 1
for (int i = 0; i < 3; i++) {
if (out_yuv[i] < 0)
out_yuv[i] = 0;
if (out_yuv[i] > 1)
out_yuv[i] = 1;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* function to compute quality metric with bit settings
* @param cloud_a original cloud
* @param cloud_b decoded cloud
* @param qual_metric return updated quality metric
* \note PointT typename of point used in point cloud
* \author Rufael Mekuria ([email protected])
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT> void
computeQualityMetric (PointCloud<PointT> &cloud_a, PointCloud<PointT> &cloud_b, QualityMetric & qual_metric)
{
print_highlight (stderr, "Computing Quality Metrics for Point Clouds !!\n");
//! we log time past in computing the quality metric
TicToc tt;
tt.tic ();
// compare A to B
pcl::search::KdTree<PointT> tree_b;
tree_b.setInputCloud (cloud_b.makeShared ());
// geometric differences A -> B
float max_dist_a = -std::numeric_limits<float>::max ();
double rms_dist_a = 0;
// color differences A -> B
double psnr_colors_yuv[3] = {0.0,0.0,0.0};
double mse_colors_yuv[3] = {0.0,0.0,0.0};
// maximum color values needed to compute PSNR
double peak_yuv[3] = {0.0,0.0,0.0};
double min_yuv[3] = {0.0,0.0,0.0};
//! compute the maximum and mean square distance between each point in a to the nearest point in b
//! compute the mean square color error for each point in a to the nearest point in b
for (size_t i = 0; i < cloud_a.points.size (); ++i)
{
std::vector<int> indices (1);
std::vector<float> sqr_distances (1);
// search the most nearby point in the cloud_b
tree_b.nearestKSearch (cloud_a.points[i], 1, indices, sqr_distances);
// haussdorf geometric distance (Linf norm)
if (sqr_distances[0] > max_dist_a)
max_dist_a = sqr_distances[0];
// mean square geometric distance (L2 norm)
rms_dist_a+=sqr_distances[0];
////////////////////////////////////////////////////////////////
// compute quality metric for yuv colors
// 1. convert to RGB to YUV
// 2. compute accumulated square error colors a to b
////////////////////////////////////////////////////////////////
float out_yuv[3];
float in_yuv[3];
convertRGBtoYUV<PointT>(cloud_a.points[i],in_yuv);
convertRGBtoYUV<PointT>(cloud_b.points[indices[0]],out_yuv);
// calculate the maximum YUV components
for(int cc=0;cc<3;cc++)
if((in_yuv[cc] * in_yuv[cc]) > (peak_yuv[cc] * peak_yuv[cc]))
peak_yuv[cc] = in_yuv[cc];
// calculate the minimum YUV components
for (int cc = 0; cc<3; cc++)
if ((in_yuv[cc] * in_yuv[cc]) < (min_yuv[cc] * min_yuv[cc]))
min_yuv[cc] = in_yuv[cc];
mse_colors_yuv[0]+=((in_yuv[0] - out_yuv[0]) * (in_yuv[0] - out_yuv[0]));
mse_colors_yuv[1]+=((in_yuv[1] - out_yuv[1]) * (in_yuv[1] - out_yuv[1]));
mse_colors_yuv[2]+=((in_yuv[2] - out_yuv[2]) * (in_yuv[2] - out_yuv[2]));
}
// compare geometry of B to A (needed for symmetric metric)
pcl::search::KdTree<PointT> tree_a;
tree_a.setInputCloud (cloud_a.makeShared ());
float max_dist_b = -std::numeric_limits<float>::max ();
double rms_dist_b = 0;
for (size_t i = 0; i < cloud_b.points.size (); ++i)
{
std::vector<int> indices (1);
std::vector<float> sqr_distances (1);
tree_a.nearestKSearch (cloud_b.points[i], 1, indices, sqr_distances);
if (sqr_distances[0] > max_dist_b)
max_dist_b = sqr_distances[0];
// mean square distance
rms_dist_b+=sqr_distances[0];
}
////////////////////////////////////////////////////////////////
// calculate geometric error metrics
// 1. compute left and right haussdorf
// 2. compute left and right rms
// 3. compute symmetric haussdorf and rms
// 4. calculate psnr for symmetric rms error
////////////////////////////////////////////////////////////////
max_dist_a = std::sqrt (max_dist_a);
max_dist_b = std::sqrt (max_dist_b);
rms_dist_a = std::sqrt (rms_dist_a/cloud_a.points.size ());
rms_dist_b = std::sqrt (rms_dist_b/cloud_b.points.size ());
float dist_h = std::max (max_dist_a, max_dist_b);
float dist_rms = std::max (rms_dist_a , rms_dist_b);
/////////////////////////////////////////////////////////
//
// calculate peak signal to noise ratio,
// we assume the meshes are normalized per component and the peak energy therefore should approach 3
//
///////////////////////////////////////////////////////////
PointT l_max_signal;
PointT l_min_signal;
// calculate peak geometric signal value
getMinMax3D<PointT>(cloud_a,l_min_signal,l_max_signal);
// calculate max energy of point
float l_max_geom_signal_energy = l_max_signal.x * l_max_signal.x
+ l_max_signal.y * l_max_signal.y + l_max_signal.z * l_max_signal.z ;
float peak_signal_to_noise_ratio = 10 * std::log10( l_max_geom_signal_energy / (dist_rms * dist_rms));
// compute averages for color distortions
mse_colors_yuv[0] /= cloud_a.points.size ();
mse_colors_yuv[1] /= cloud_a.points.size ();
mse_colors_yuv[2] /= cloud_a.points.size ();
// compute PSNR for YUV colors
// compute the peak signal also taking into account the
for(int cc=0;cc<3;cc++)
peak_yuv[cc] = peak_yuv[cc] - min_yuv[cc];
psnr_colors_yuv[0] = 10 * std::log10( (peak_yuv[0] * peak_yuv[0] )/mse_colors_yuv[0]);
psnr_colors_yuv[1] = 10 * std::log10( (peak_yuv[1] * peak_yuv[1] )/mse_colors_yuv[1]);
psnr_colors_yuv[2] = 10 * std::log10( (peak_yuv[2] * peak_yuv[2] )/mse_colors_yuv[2]);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms \n");
//print_info ("A->B: "); print_value ("%f\n", max_dist_a);
//print_info ("B->A: "); print_value ("%f\n", max_dist_b);
print_info ("Symmetric Geometric Hausdorff Distance: "); print_value ("%f", dist_h);
print_info (" ]\n\n");
//print_info ("A->B : "); print_value ("%f rms\n", rms_dist_a);
//print_info ("B->A: "); print_value ("%f rms\n", rms_dist_b);
print_info ("Symmetric Geometric Root Mean Square Distance: "); print_value ("%f\n", dist_rms);
print_info ("Geometric PSNR: "); print_value ("%f dB", peak_signal_to_noise_ratio);
print_info (" ]\n\n");
print_info ("A->B color psnr Y: "); print_value ("%f dB ", (float) psnr_colors_yuv[0]);
print_info ("A->B color psnr U: "); print_value ("%f dB ", (float) psnr_colors_yuv[1]);
print_info ("A->B color psnr V: "); print_value ("%f dB ", (float) psnr_colors_yuv[2]);
print_info (" ]\n");
qual_metric.in_point_count = cloud_a.points.size ();
qual_metric.out_point_count = cloud_b.points.size ();
//////////////////////////////////////////////////////
//
// store the quality metrics in the return values
//
////////////////////////////////////////////////////
// geometric quality metrics [haussdorf Linf]
qual_metric.left_hausdorff = max_dist_a;
qual_metric.right_hausdorff = max_dist_b;
qual_metric.symm_hausdorff = dist_h;
// geometric quality metrics [rms L2]
qual_metric.left_rms = rms_dist_a;
qual_metric.right_rms = rms_dist_b;
qual_metric.symm_rms = dist_rms;
qual_metric.psnr_db = peak_signal_to_noise_ratio ;
// color quality metric (non-symmetric, L2)
qual_metric.psnr_yuv[0]= psnr_colors_yuv[0];
qual_metric.psnr_yuv[1]= psnr_colors_yuv[1];
qual_metric.psnr_yuv[2]= psnr_colors_yuv[2];
}
//! function to print a header to csv file for logging the quality characteristics
void
QualityMetric::print_csv_line(const std::string &compression_setting_arg, std::ostream &csv_ostream)
{
csv_ostream << compression_setting_arg << std::string(";")
<< in_point_count << std::string(";")
<< out_point_count << std::string(";")
<< compressed_size << std::string(";")
<< compressed_size/ (1.0 * out_point_count) << std::string(";")
<< byte_count_octree_layer/ (1.0 * out_point_count) << std::string(";")
<< byte_count_centroid_layer / (1.0 * out_point_count) << std::string(";")
<< byte_count_color_layer / (1.0 * out_point_count) << std::string(";")
<< symm_rms << std::string(";")
<< symm_hausdorff << std::string(";")
<< psnr_db << std::string(";")
<< psnr_yuv[0] << std::string(";")
<< psnr_yuv[1] << std::string(";")
<< psnr_yuv[2] << std::string(";")
<< encoding_time_ms << std::string(";")
<< decoding_time_ms << std::string(";")
<< std::endl;
}
//! function to print a header to csv file for logging the quality characteristics
void
QualityMetric::print_csv_header(std::ostream &csv_ostream)
{
csv_ostream << "compression setting; "
<< std::string("in point count;")
<< std::string("out point count;")
<< std::string("compressed_byte_size;")
<< std::string("compressed_byte_size_per_output_point;")
<< std::string("octree_byte_size_per_voxel;")
<< std::string("centroid_byte_size_per_voxel;")
<< std::string("color_byte_size_per_voxel;")
<< std::string("symm_rms;")
<< std::string("symm_haussdorff;")
<< std::string("psnr_db;")
<< std::string("psnr_colors_y;")
<< std::string("psnr_colors_u;")
<< std::string("psnr_colors_v;")
<< std::string("encoding_time_ms;")
<< std::string("decoding_time_ms;")
<< std::endl;
}
} //~ namespace quality
}//~ namespace pcl
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSigmaProjectionImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCommand.h"
#include "itkSimpleFilterWatcher.h"
#include "itkSigmaProjectionImageFilter.h"
int itkSigmaProjectionImageFilterTest(int argc, char * argv[])
{
if( argc < 3 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " InputImage OutputImage " << std::endl;
return EXIT_FAILURE;
}
const int dim = 3;
typedef unsigned char PType;
typedef itk::Image< PType, dim > IType;
typedef itk::ImageFileReader< IType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef itk::SigmaProjectionImageFilter< IType, IType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
itk::SimpleFilterWatcher watcher(filter, "filter");
typedef itk::ImageFileWriter< IType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[2] );
try
{
writer->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>STYLE: code style fix<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSigmaProjectionImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCommand.h"
#include "itkSimpleFilterWatcher.h"
#include "itkSigmaProjectionImageFilter.h"
int itkSigmaProjectionImageFilterTest(int argc, char * argv[])
{
if( argc < 3 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " InputImage OutputImage " << std::endl;
return EXIT_FAILURE;
}
const int dim = 3;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, dim > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef itk::SigmaProjectionImageFilter< ImageType, ImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
itk::SimpleFilterWatcher watcher(filter, "filter");
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[2] );
try
{
writer->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fl_renderer.h"
#include "flutter/shell/platform/embedder/embedder.h"
G_DEFINE_QUARK(fl_renderer_error_quark, fl_renderer_error)
typedef struct {
EGLDisplay egl_display;
EGLSurface egl_surface;
EGLContext egl_context;
EGLSurface resource_surface;
EGLContext resource_context;
} FlRendererPrivate;
G_DEFINE_TYPE_WITH_PRIVATE(FlRenderer, fl_renderer, G_TYPE_OBJECT)
// Gets a string representation of the last EGL error.
static const gchar* get_egl_error() {
EGLint error = eglGetError();
switch (error) {
case EGL_SUCCESS:
return "Success";
case EGL_NOT_INITIALIZED:
return "Not Initialized";
case EGL_BAD_ACCESS:
return "Bad Access";
case EGL_BAD_ALLOC:
return "Bad Allocation";
case EGL_BAD_ATTRIBUTE:
return "Bad Attribute";
case EGL_BAD_CONTEXT:
return "Bad Context";
case EGL_BAD_CONFIG:
return "Bad Configuration";
case EGL_BAD_CURRENT_SURFACE:
return "Bad Current Surface";
case EGL_BAD_DISPLAY:
return "Bad Display";
case EGL_BAD_SURFACE:
return "Bad Surface";
case EGL_BAD_MATCH:
return "Bad Match";
case EGL_BAD_PARAMETER:
return "Bad Parameter";
case EGL_BAD_NATIVE_PIXMAP:
return "Bad Native Pixmap";
case EGL_BAD_NATIVE_WINDOW:
return "Bad Native Window";
case EGL_CONTEXT_LOST:
return "Context Lost";
default:
return "Unknown Error";
}
}
// Creates a resource surface.
static void create_resource_surface(FlRenderer* self, EGLConfig config) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
EGLint context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
const EGLint resource_context_attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1,
EGL_NONE};
priv->resource_surface = eglCreatePbufferSurface(priv->egl_display, config,
resource_context_attribs);
if (priv->resource_surface != nullptr) {
g_warning("Failed to create EGL resource surface: %s", get_egl_error());
return;
}
priv->resource_context = eglCreateContext(
priv->egl_display, config, priv->egl_context, context_attributes);
if (priv->resource_context == nullptr)
g_warning("Failed to create EGL resource context: %s", get_egl_error());
}
// Default implementation for the start virtual method.
// Provided so subclasses can chain up to here.
static gboolean fl_renderer_real_start(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
// Note the use of EGL_DEFAULT_DISPLAY rather than sharing an existing
// display connection (e.g. an X11 connection from GTK). This is because
// this EGL display is going to be accessed by a thread from Flutter. In the
// case of GTK/X11 the display connection is not thread safe and this would
// cause a crash.
priv->egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (!eglInitialize(priv->egl_display, nullptr, nullptr)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to initialze EGL");
return FALSE;
}
EGLint attributes[] = {EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_BLUE_SIZE,
8,
EGL_ALPHA_SIZE,
8,
EGL_NONE};
EGLConfig egl_config;
EGLint n_config;
if (!eglChooseConfig(priv->egl_display, attributes, &egl_config, 1,
&n_config)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to choose EGL config: %s", get_egl_error());
return FALSE;
}
if (n_config == 0) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to find appropriate EGL config: %s", get_egl_error());
return FALSE;
}
if (!eglBindAPI(EGL_OPENGL_ES_API)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to bind EGL OpenGL ES API: %s", get_egl_error());
return FALSE;
}
priv->egl_surface = FL_RENDERER_GET_CLASS(self)->create_surface(
self, priv->egl_display, egl_config);
if (priv->egl_surface == nullptr) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to create EGL surface: %s", get_egl_error());
return FALSE;
}
EGLint context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
priv->egl_context = eglCreateContext(priv->egl_display, egl_config,
EGL_NO_CONTEXT, context_attributes);
if (priv->egl_context == nullptr) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to create EGL context: %s", get_egl_error());
return FALSE;
}
create_resource_surface(self, egl_config);
EGLint value;
eglQueryContext(priv->egl_display, priv->egl_context,
EGL_CONTEXT_CLIENT_VERSION, &value);
return TRUE;
}
static void fl_renderer_class_init(FlRendererClass* klass) {
klass->start = fl_renderer_real_start;
}
static void fl_renderer_init(FlRenderer* self) {}
gboolean fl_renderer_start(FlRenderer* self, GError** error) {
return FL_RENDERER_GET_CLASS(self)->start(self, error);
}
void* fl_renderer_get_proc_address(FlRenderer* self, const char* name) {
return reinterpret_cast<void*>(eglGetProcAddress(name));
}
gboolean fl_renderer_make_current(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (!eglMakeCurrent(priv->egl_display, priv->egl_surface, priv->egl_surface,
priv->egl_context)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to make EGL context current: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
gboolean fl_renderer_make_resource_current(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (priv->resource_surface == nullptr || priv->resource_context == nullptr)
return FALSE;
if (!eglMakeCurrent(priv->egl_display, priv->resource_surface,
priv->resource_surface, priv->resource_context)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to make EGL context current: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
gboolean fl_renderer_clear_current(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (!eglMakeCurrent(priv->egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to clear EGL context: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
guint32 fl_renderer_get_fbo(FlRenderer* self) {
// There is only one frame buffer object - always return that.
return 0;
}
gboolean fl_renderer_present(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (!eglSwapBuffers(priv->egl_display, priv->egl_surface)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to swap EGL buffers: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
<commit_msg>Fix inverted check in creating resource surface (#18989)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fl_renderer.h"
#include "flutter/shell/platform/embedder/embedder.h"
G_DEFINE_QUARK(fl_renderer_error_quark, fl_renderer_error)
typedef struct {
EGLDisplay egl_display;
EGLSurface egl_surface;
EGLContext egl_context;
EGLSurface resource_surface;
EGLContext resource_context;
} FlRendererPrivate;
G_DEFINE_TYPE_WITH_PRIVATE(FlRenderer, fl_renderer, G_TYPE_OBJECT)
// Gets a string representation of the last EGL error.
static const gchar* get_egl_error() {
EGLint error = eglGetError();
switch (error) {
case EGL_SUCCESS:
return "Success";
case EGL_NOT_INITIALIZED:
return "Not Initialized";
case EGL_BAD_ACCESS:
return "Bad Access";
case EGL_BAD_ALLOC:
return "Bad Allocation";
case EGL_BAD_ATTRIBUTE:
return "Bad Attribute";
case EGL_BAD_CONTEXT:
return "Bad Context";
case EGL_BAD_CONFIG:
return "Bad Configuration";
case EGL_BAD_CURRENT_SURFACE:
return "Bad Current Surface";
case EGL_BAD_DISPLAY:
return "Bad Display";
case EGL_BAD_SURFACE:
return "Bad Surface";
case EGL_BAD_MATCH:
return "Bad Match";
case EGL_BAD_PARAMETER:
return "Bad Parameter";
case EGL_BAD_NATIVE_PIXMAP:
return "Bad Native Pixmap";
case EGL_BAD_NATIVE_WINDOW:
return "Bad Native Window";
case EGL_CONTEXT_LOST:
return "Context Lost";
default:
return "Unknown Error";
}
}
// Creates a resource surface.
static void create_resource_surface(FlRenderer* self, EGLConfig config) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
EGLint context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
const EGLint resource_context_attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1,
EGL_NONE};
priv->resource_surface = eglCreatePbufferSurface(priv->egl_display, config,
resource_context_attribs);
if (priv->resource_surface == nullptr) {
g_warning("Failed to create EGL resource surface: %s", get_egl_error());
return;
}
priv->resource_context = eglCreateContext(
priv->egl_display, config, priv->egl_context, context_attributes);
if (priv->resource_context == nullptr)
g_warning("Failed to create EGL resource context: %s", get_egl_error());
}
// Default implementation for the start virtual method.
// Provided so subclasses can chain up to here.
static gboolean fl_renderer_real_start(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
// Note the use of EGL_DEFAULT_DISPLAY rather than sharing an existing
// display connection (e.g. an X11 connection from GTK). This is because
// this EGL display is going to be accessed by a thread from Flutter. In the
// case of GTK/X11 the display connection is not thread safe and this would
// cause a crash.
priv->egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (!eglInitialize(priv->egl_display, nullptr, nullptr)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to initialze EGL");
return FALSE;
}
EGLint attributes[] = {EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_BLUE_SIZE,
8,
EGL_ALPHA_SIZE,
8,
EGL_NONE};
EGLConfig egl_config;
EGLint n_config;
if (!eglChooseConfig(priv->egl_display, attributes, &egl_config, 1,
&n_config)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to choose EGL config: %s", get_egl_error());
return FALSE;
}
if (n_config == 0) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to find appropriate EGL config: %s", get_egl_error());
return FALSE;
}
if (!eglBindAPI(EGL_OPENGL_ES_API)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to bind EGL OpenGL ES API: %s", get_egl_error());
return FALSE;
}
priv->egl_surface = FL_RENDERER_GET_CLASS(self)->create_surface(
self, priv->egl_display, egl_config);
if (priv->egl_surface == nullptr) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to create EGL surface: %s", get_egl_error());
return FALSE;
}
EGLint context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
priv->egl_context = eglCreateContext(priv->egl_display, egl_config,
EGL_NO_CONTEXT, context_attributes);
if (priv->egl_context == nullptr) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to create EGL context: %s", get_egl_error());
return FALSE;
}
create_resource_surface(self, egl_config);
EGLint value;
eglQueryContext(priv->egl_display, priv->egl_context,
EGL_CONTEXT_CLIENT_VERSION, &value);
return TRUE;
}
static void fl_renderer_class_init(FlRendererClass* klass) {
klass->start = fl_renderer_real_start;
}
static void fl_renderer_init(FlRenderer* self) {}
gboolean fl_renderer_start(FlRenderer* self, GError** error) {
return FL_RENDERER_GET_CLASS(self)->start(self, error);
}
void* fl_renderer_get_proc_address(FlRenderer* self, const char* name) {
return reinterpret_cast<void*>(eglGetProcAddress(name));
}
gboolean fl_renderer_make_current(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (!eglMakeCurrent(priv->egl_display, priv->egl_surface, priv->egl_surface,
priv->egl_context)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to make EGL context current: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
gboolean fl_renderer_make_resource_current(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (priv->resource_surface == nullptr || priv->resource_context == nullptr)
return FALSE;
if (!eglMakeCurrent(priv->egl_display, priv->resource_surface,
priv->resource_surface, priv->resource_context)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to make EGL context current: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
gboolean fl_renderer_clear_current(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (!eglMakeCurrent(priv->egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to clear EGL context: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
guint32 fl_renderer_get_fbo(FlRenderer* self) {
// There is only one frame buffer object - always return that.
return 0;
}
gboolean fl_renderer_present(FlRenderer* self, GError** error) {
FlRendererPrivate* priv =
static_cast<FlRendererPrivate*>(fl_renderer_get_instance_private(self));
if (!eglSwapBuffers(priv->egl_display, priv->egl_surface)) {
g_set_error(error, fl_renderer_error_quark(), FL_RENDERER_ERROR_FAILED,
"Failed to swap EGL buffers: %s", get_egl_error());
return FALSE;
}
return TRUE;
}
<|endoftext|> |
<commit_before>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/
#include "booksim.hpp"
#include <iostream>
#include <cassert>
#include "allocator.hpp"
/////////////////////////////////////////////////////////////////////////
//Allocator types
#include "maxsize.hpp"
#include "pim.hpp"
#include "islip.hpp"
#include "loa.hpp"
#include "wavefront.hpp"
#include "fair_wavefront.hpp"
#include "prio_wavefront.hpp"
#include "selalloc.hpp"
#include "separable_input_first.hpp"
#include "separable_output_first.hpp"
//
/////////////////////////////////////////////////////////////////////////
//==================================================
// Allocator base class
//==================================================
Allocator::Allocator( Module *parent, const string& name,
int inputs, int outputs ) :
Module( parent, name ), _inputs( inputs ), _outputs( outputs )
{
_inmatch.resize(_inputs);
_outmatch.resize(_outputs);
}
void Allocator::Clear( )
{
_inmatch.assign(_inputs, -1);
_outmatch.assign(_outputs, -1);
}
int Allocator::OutputAssigned( int in ) const
{
assert( ( in >= 0 ) && ( in < _inputs ) );
return _inmatch[in];
}
int Allocator::InputAssigned( int out ) const
{
assert( ( out >= 0 ) && ( out < _outputs ) );
return _outmatch[out];
}
//==================================================
// DenseAllocator
//==================================================
DenseAllocator::DenseAllocator( Module *parent, const string& name,
int inputs, int outputs ) :
Allocator( parent, name, inputs, outputs )
{
_request.resize(_inputs);
for ( int i = 0; i < _inputs; ++i ) {
_request[i].resize(_outputs);
}
Clear( );
}
void DenseAllocator::Clear( )
{
for ( int i = 0; i < _inputs; ++i ) {
for ( int j = 0; j < _outputs; ++j ) {
_request[i][j].label = -1;
}
}
Allocator::Clear();
}
int DenseAllocator::ReadRequest( int in, int out ) const
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
return _request[in][out].label;
}
bool DenseAllocator::ReadRequest( sRequest &req, int in, int out ) const
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
req = _request[in][out];
return ( req.label != -1 );
}
void DenseAllocator::AddRequest( int in, int out, int label,
int in_pri, int out_pri )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
if((_request[in][out].label == -1) || (_request[in][out].in_pri < in_pri)) {
_request[in][out].label = label;
_request[in][out].in_pri = in_pri;
_request[in][out].out_pri = out_pri;
}
}
void DenseAllocator::RemoveRequest( int in, int out, int label )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
_request[in][out].label = -1;
}
void DenseAllocator::PrintRequests( ostream * os ) const
{
if(!os) os = &cout;
*os << "Requests = [ ";
for ( int i = 0; i < _inputs; ++i ) {
*os << "[ ";
for ( int j = 0; j < _outputs; ++j ) {
*os << ( _request[i][j].label != -1 ) << " ";
}
*os << "] ";
}
*os << "]." << endl;
}
//==================================================
// SparseAllocator
//==================================================
SparseAllocator::SparseAllocator( Module *parent, const string& name,
int inputs, int outputs ) :
Allocator( parent, name, inputs, outputs )
{
_in_req.resize(_inputs);
_out_req.resize(_outputs);
}
void SparseAllocator::Clear( )
{
for ( int i = 0; i < _inputs; ++i ) {
_in_req[i].clear( );
}
for ( int j = 0; j < _outputs; ++j ) {
_out_req[j].clear( );
}
_in_occ.clear( );
_out_occ.clear( );
Allocator::Clear();
}
int SparseAllocator::ReadRequest( int in, int out ) const
{
sRequest r;
if ( ! ReadRequest( r, in, out ) ) {
r.label = -1;
}
return r.label;
}
bool SparseAllocator::ReadRequest( sRequest &req, int in, int out ) const
{
bool found;
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
map<int, sRequest>::const_iterator match = _in_req[in].find(out);
if ( match != _in_req[in].end( ) ) {
req = match->second;
found = true;
} else {
found = false;
}
return found;
}
void SparseAllocator::AddRequest( int in, int out, int label,
int in_pri, int out_pri )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
// insert into occupied inputs set if
// input is currently empty
if ( _in_req[in].empty( ) ) {
_in_occ.insert(in);
}
// similarly for the output
if ( _out_req[out].empty( ) ) {
_out_occ.insert(out);
}
sRequest req;
req.port = out;
req.label = label;
req.in_pri = in_pri;
req.out_pri = out_pri;
// insert input request in order of it's output
map<int, sRequest>::iterator insert_point = _in_req[in].find(out);
if(insert_point == _in_req[in].end()) {
_in_req[in][out] = req;
} else if(insert_point->second.in_pri < in_pri) {
insert_point->second = req;
}
req.port = in;
req.label = label;
insert_point = _out_req[out].find(in);
if(insert_point == _out_req[out].end()) {
_out_req[out][in] = req;
} else if(insert_point->second.in_pri < in_pri) {
insert_point->second = req;
}
}
void SparseAllocator::RemoveRequest( int in, int out, int label )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
// insert input request in order of it's output
map<int, sRequest>::iterator erase_point = _in_req[in].find(out);
assert( erase_point != _in_req[in].end( ) );
_in_req[in].erase( erase_point );
// remove from occupied inputs list if
// input is now empty
if ( _in_req[in].empty( ) ) {
_in_occ.erase(in);
}
// similarly for the output
erase_point = _out_req[out].find(in);
assert( erase_point != _out_req[out].end( ) );
_out_req[out].erase( erase_point );
if ( _out_req[out].empty( ) ) {
_out_occ.erase(out);
}
}
void SparseAllocator::PrintRequests( ostream * os ) const
{
map<int, sRequest>::const_iterator iter;
if(!os) os = &cout;
*os << "Input requests = [ ";
for ( int input = 0; input < _inputs; ++input ) {
*os << input << " -> [ ";
for ( iter = _in_req[input].begin( );
iter != _in_req[input].end( ); iter++ ) {
*os << iter->second.port << " ";
}
*os << "] ";
}
*os << "], output requests = [ ";
for ( int output = 0; output < _outputs; ++output ) {
*os << output << " -> ";
*os << "[ ";
for ( iter = _out_req[output].begin( );
iter != _out_req[output].end( ); iter++ ) {
*os << iter->second.port << " ";
}
*os << "] ";
}
*os << "]." << endl;
}
//==================================================
// Global allocator allocation function
//==================================================
Allocator *Allocator::NewAllocator( Module *parent, const string& name,
const string &alloc_type,
int inputs, int outputs,
int iters, const string &arb_type )
{
Allocator *a = 0;
if ( alloc_type == "max_size" ) {
a = new MaxSizeMatch( parent, name, inputs, outputs );
} else if ( alloc_type == "pim" ) {
a = new PIM( parent, name, inputs, outputs, iters );
} else if ( alloc_type == "islip" ) {
a = new iSLIP_Sparse( parent, name, inputs, outputs, iters );
} else if ( alloc_type == "loa" ) {
a = new LOA( parent, name, inputs, outputs );
} else if ( alloc_type == "wavefront" ) {
a = new Wavefront( parent, name, inputs, outputs );
} else if ( alloc_type == "fair_wavefront" ) {
a = new FairWavefront( parent, name, inputs, outputs );
} else if ( alloc_type == "prio_wavefront" ) {
a = new PrioWavefront( parent, name, inputs, outputs );
} else if ( alloc_type == "select" ) {
a = new SelAlloc( parent, name, inputs, outputs, iters );
} else if (alloc_type == "separable_input_first") {
a = new SeparableInputFirstAllocator( parent, name, inputs, outputs,
arb_type );
} else if (alloc_type == "separable_output_first") {
a = new SeparableOutputFirstAllocator( parent, name, inputs, outputs,
arb_type );
}
//==================================================
// Insert new allocators here, add another else if
//==================================================
return a;
}
<commit_msg>simplify clear-on-construct for allocator base classes<commit_after>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/
#include "booksim.hpp"
#include <iostream>
#include <cassert>
#include "allocator.hpp"
/////////////////////////////////////////////////////////////////////////
//Allocator types
#include "maxsize.hpp"
#include "pim.hpp"
#include "islip.hpp"
#include "loa.hpp"
#include "wavefront.hpp"
#include "fair_wavefront.hpp"
#include "prio_wavefront.hpp"
#include "selalloc.hpp"
#include "separable_input_first.hpp"
#include "separable_output_first.hpp"
//
/////////////////////////////////////////////////////////////////////////
//==================================================
// Allocator base class
//==================================================
Allocator::Allocator( Module *parent, const string& name,
int inputs, int outputs ) :
Module( parent, name ), _inputs( inputs ), _outputs( outputs )
{
_inmatch.resize(_inputs, -1);
_outmatch.resize(_outputs, -1);
}
void Allocator::Clear( )
{
_inmatch.assign(_inputs, -1);
_outmatch.assign(_outputs, -1);
}
int Allocator::OutputAssigned( int in ) const
{
assert( ( in >= 0 ) && ( in < _inputs ) );
return _inmatch[in];
}
int Allocator::InputAssigned( int out ) const
{
assert( ( out >= 0 ) && ( out < _outputs ) );
return _outmatch[out];
}
//==================================================
// DenseAllocator
//==================================================
DenseAllocator::DenseAllocator( Module *parent, const string& name,
int inputs, int outputs ) :
Allocator( parent, name, inputs, outputs )
{
_request.resize(_inputs);
for ( int i = 0; i < _inputs; ++i ) {
_request[i].resize(_outputs, -1);
}
}
void DenseAllocator::Clear( )
{
for ( int i = 0; i < _inputs; ++i ) {
for ( int j = 0; j < _outputs; ++j ) {
_request[i][j].label = -1;
}
}
Allocator::Clear();
}
int DenseAllocator::ReadRequest( int in, int out ) const
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
return _request[in][out].label;
}
bool DenseAllocator::ReadRequest( sRequest &req, int in, int out ) const
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
req = _request[in][out];
return ( req.label != -1 );
}
void DenseAllocator::AddRequest( int in, int out, int label,
int in_pri, int out_pri )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
if((_request[in][out].label == -1) || (_request[in][out].in_pri < in_pri)) {
_request[in][out].label = label;
_request[in][out].in_pri = in_pri;
_request[in][out].out_pri = out_pri;
}
}
void DenseAllocator::RemoveRequest( int in, int out, int label )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
_request[in][out].label = -1;
}
void DenseAllocator::PrintRequests( ostream * os ) const
{
if(!os) os = &cout;
*os << "Requests = [ ";
for ( int i = 0; i < _inputs; ++i ) {
*os << "[ ";
for ( int j = 0; j < _outputs; ++j ) {
*os << ( _request[i][j].label != -1 ) << " ";
}
*os << "] ";
}
*os << "]." << endl;
}
//==================================================
// SparseAllocator
//==================================================
SparseAllocator::SparseAllocator( Module *parent, const string& name,
int inputs, int outputs ) :
Allocator( parent, name, inputs, outputs )
{
_in_req.resize(_inputs);
_out_req.resize(_outputs);
}
void SparseAllocator::Clear( )
{
for ( int i = 0; i < _inputs; ++i ) {
_in_req[i].clear( );
}
for ( int j = 0; j < _outputs; ++j ) {
_out_req[j].clear( );
}
_in_occ.clear( );
_out_occ.clear( );
Allocator::Clear();
}
int SparseAllocator::ReadRequest( int in, int out ) const
{
sRequest r;
if ( ! ReadRequest( r, in, out ) ) {
r.label = -1;
}
return r.label;
}
bool SparseAllocator::ReadRequest( sRequest &req, int in, int out ) const
{
bool found;
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
map<int, sRequest>::const_iterator match = _in_req[in].find(out);
if ( match != _in_req[in].end( ) ) {
req = match->second;
found = true;
} else {
found = false;
}
return found;
}
void SparseAllocator::AddRequest( int in, int out, int label,
int in_pri, int out_pri )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
// insert into occupied inputs set if
// input is currently empty
if ( _in_req[in].empty( ) ) {
_in_occ.insert(in);
}
// similarly for the output
if ( _out_req[out].empty( ) ) {
_out_occ.insert(out);
}
sRequest req;
req.port = out;
req.label = label;
req.in_pri = in_pri;
req.out_pri = out_pri;
// insert input request in order of it's output
map<int, sRequest>::iterator insert_point = _in_req[in].find(out);
if(insert_point == _in_req[in].end()) {
_in_req[in][out] = req;
} else if(insert_point->second.in_pri < in_pri) {
insert_point->second = req;
}
req.port = in;
req.label = label;
insert_point = _out_req[out].find(in);
if(insert_point == _out_req[out].end()) {
_out_req[out][in] = req;
} else if(insert_point->second.in_pri < in_pri) {
insert_point->second = req;
}
}
void SparseAllocator::RemoveRequest( int in, int out, int label )
{
assert( ( in >= 0 ) && ( in < _inputs ) &&
( out >= 0 ) && ( out < _outputs ) );
// insert input request in order of it's output
map<int, sRequest>::iterator erase_point = _in_req[in].find(out);
assert( erase_point != _in_req[in].end( ) );
_in_req[in].erase( erase_point );
// remove from occupied inputs list if
// input is now empty
if ( _in_req[in].empty( ) ) {
_in_occ.erase(in);
}
// similarly for the output
erase_point = _out_req[out].find(in);
assert( erase_point != _out_req[out].end( ) );
_out_req[out].erase( erase_point );
if ( _out_req[out].empty( ) ) {
_out_occ.erase(out);
}
}
void SparseAllocator::PrintRequests( ostream * os ) const
{
map<int, sRequest>::const_iterator iter;
if(!os) os = &cout;
*os << "Input requests = [ ";
for ( int input = 0; input < _inputs; ++input ) {
*os << input << " -> [ ";
for ( iter = _in_req[input].begin( );
iter != _in_req[input].end( ); iter++ ) {
*os << iter->second.port << " ";
}
*os << "] ";
}
*os << "], output requests = [ ";
for ( int output = 0; output < _outputs; ++output ) {
*os << output << " -> ";
*os << "[ ";
for ( iter = _out_req[output].begin( );
iter != _out_req[output].end( ); iter++ ) {
*os << iter->second.port << " ";
}
*os << "] ";
}
*os << "]." << endl;
}
//==================================================
// Global allocator allocation function
//==================================================
Allocator *Allocator::NewAllocator( Module *parent, const string& name,
const string &alloc_type,
int inputs, int outputs,
int iters, const string &arb_type )
{
Allocator *a = 0;
if ( alloc_type == "max_size" ) {
a = new MaxSizeMatch( parent, name, inputs, outputs );
} else if ( alloc_type == "pim" ) {
a = new PIM( parent, name, inputs, outputs, iters );
} else if ( alloc_type == "islip" ) {
a = new iSLIP_Sparse( parent, name, inputs, outputs, iters );
} else if ( alloc_type == "loa" ) {
a = new LOA( parent, name, inputs, outputs );
} else if ( alloc_type == "wavefront" ) {
a = new Wavefront( parent, name, inputs, outputs );
} else if ( alloc_type == "fair_wavefront" ) {
a = new FairWavefront( parent, name, inputs, outputs );
} else if ( alloc_type == "prio_wavefront" ) {
a = new PrioWavefront( parent, name, inputs, outputs );
} else if ( alloc_type == "select" ) {
a = new SelAlloc( parent, name, inputs, outputs, iters );
} else if (alloc_type == "separable_input_first") {
a = new SeparableInputFirstAllocator( parent, name, inputs, outputs,
arb_type );
} else if (alloc_type == "separable_output_first") {
a = new SeparableOutputFirstAllocator( parent, name, inputs, outputs,
arb_type );
}
//==================================================
// Insert new allocators here, add another else if
//==================================================
return a;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/meta_index.hpp"
#include "vast/data.hpp"
#include "vast/expression.hpp"
#include "vast/logger.hpp"
#include "vast/system/atoms.hpp"
#include "vast/table_index.hpp"
#include "vast/table_slice.hpp"
#include "vast/time.hpp"
#include "vast/detail/overload.hpp"
#include "vast/detail/set_operations.hpp"
#include "vast/detail/string.hpp"
namespace vast {
meta_index::meta_index()
: make_synopsis_{make_synopsis},
factory_id_{caf::atom("Sy_Default")} {
// nop
}
void meta_index::add(const uuid& partition, const table_slice& slice) {
auto& part_synopsis = partition_synopses_[partition];
auto& layout = slice.layout();
if (blacklisted_layouts_.count(layout) == 1)
return;
auto i = part_synopsis.find(layout);
table_synopsis* table_syn;
if (i != part_synopsis.end()) {
table_syn = &i->second;
} else {
// Create new synopses for a layout we haven't seen before.
i = part_synopsis.emplace(layout, table_synopsis{}).first;
table_syn = &i->second;
for (auto& field : layout.fields)
if (i->second.emplace_back(make_synopsis_(field.type, synopsis_options_))
!= nullptr)
VAST_DEBUG(this, "created new synopsis structure for type", field.type);
// If we couldn't create a single synopsis for the layout, we will no
// longer attempt to create synopses in the future.
auto is_nullptr = [](auto& x) { return x == nullptr; };
if (std::all_of(table_syn->begin(), table_syn->end(), is_nullptr)) {
VAST_DEBUG(this, "could not create a synopsis for layout:", layout);
blacklisted_layouts_.insert(layout);
}
}
VAST_ASSERT(table_syn->size() == slice.columns());
for (size_t col = 0; col < slice.columns(); ++col)
if (auto& syn = (*table_syn)[col])
for (size_t row = 0; row < slice.rows(); ++row)
syn->add(slice.at(row, col));
}
std::vector<uuid> meta_index::lookup(const expression& expr) const {
VAST_ASSERT(!caf::holds_alternative<caf::none_t>(expr));
// TODO: we could consider a flat_set<uuid> here, which would then have
// overloads for inplace intersection/union and simplify the implementation
// of this function a bit.
using result_type = std::vector<uuid>;
auto all_partitions = [&] {
result_type result;
result.reserve(partition_synopses_.size());
std::transform(partition_synopses_.begin(),
partition_synopses_.end(),
std::back_inserter(result),
[](auto& x) { return x.first; });
std::sort(result.begin(), result.end());
return result;
};
return caf::visit(detail::overload(
[&](const conjunction& x) -> result_type {
VAST_ASSERT(!x.empty());
auto i = x.begin();
auto result = lookup(*i);
if (!result.empty())
for (++i; i != x.end(); ++i) {
auto xs = lookup(*i);
if (xs.empty())
return xs; // short-circuit
detail::inplace_intersect(result, xs);
}
return result;
},
[&](const disjunction& x) -> result_type {
result_type result;
for (auto& op : x) {
auto xs = lookup(op);
if (xs.size() == partition_synopses_.size())
return xs; // short-circuit
detail::inplace_unify(result, xs);
}
return result;
},
[&](const negation&) -> result_type {
// We cannot handle negations, because a synopsis may return false
// positives, and negating such a result may cause false negatives.
return all_partitions();
},
[&](const predicate& x) -> result_type {
// Performs a lookup on all *matching* synopses with operator and data
// from the predicate of the expression. The match function uses a record
// field to determine whether the synopsis should be queried.
auto search = [&](auto match) {
VAST_ASSERT(caf::holds_alternative<data>(x.rhs));
auto& rhs = caf::get<data>(x.rhs);
result_type result;
auto found_matching_synopsis = false;
for (auto& [part_id, part_syn] : partition_synopses_)
for (auto& [layout, table_syn] : part_syn)
for (size_t i = 0; i < table_syn.size(); ++i)
if (table_syn[i] && match(layout.fields[i])) {
found_matching_synopsis = true;
if (table_syn[i]->lookup(x.op, make_view(rhs)))
if (result.empty() || result.back() != part_id)
result.push_back(part_id);
}
std::sort(result.begin(), result.end());
return found_matching_synopsis ? result : all_partitions();
};
return caf::visit(detail::overload(
[&](const attribute_extractor& lhs, const data& d) -> result_type {
if (lhs.attr == system::time_atom::value) {
auto pred = [](auto& field) {
// FIXME: we should really just look at the ×tamp attribute
// and not all fields of type time. [ch3843]
return caf::holds_alternative<timestamp_type>(field.type);
};
return search(pred);
} else if (lhs.attr == system::type_atom::value) {
result_type result;
for (auto& [part_id, part_syn] : partition_synopses_)
for (auto& [layout, _] : part_syn)
if (evaluate(layout.name(), x.op, d))
if (result.empty() || result.back() != part_id)
result.push_back(part_id);
return result;
}
VAST_WARNING(this, "cannot process attribute extractor:", lhs.attr);
return all_partitions();
},
[&](const key_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) {
return detail::ends_with(field.name, lhs.key);
};
return search(pred);
},
[&](const type_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) { return field.type == lhs.type; };
return search(pred);
},
[&](const auto&, const auto&) -> result_type {
VAST_WARNING(this, "cannot process predicate:", x);
return all_partitions();
}
), x.lhs, x.rhs);
},
[&](caf::none_t) -> result_type {
VAST_ERROR(this, "received an empty expression");
VAST_ASSERT(!"invalid expression");
return all_partitions();
}
), expr);
}
void meta_index::factory(caf::atom_value factory_id,
synopsis_factory f) {
factory_id_ = factory_id;
make_synopsis_ = f;
blacklisted_layouts_.clear();
}
std::pair<caf::atom_value, synopsis_factory> meta_index::factory() const {
return {factory_id_, make_synopsis_};
}
synopsis_options& meta_index::factory_options() {
return synopsis_options_;
}
caf::error inspect(caf::serializer& sink, const meta_index& x) {
return sink(x.factory_id_, x.synopsis_options_, x.partition_synopses_);
}
caf::error inspect(caf::deserializer& source, meta_index& x) {
if (auto ex = deserialize_synopsis_factory(source))
x.factory(ex->first, ex->second);
else
return std::move(ex.error());
return source(x.synopsis_options_, x.partition_synopses_);
}
} // namespace vast
<commit_msg>Avoid unused variable warning<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/meta_index.hpp"
#include "vast/data.hpp"
#include "vast/expression.hpp"
#include "vast/logger.hpp"
#include "vast/system/atoms.hpp"
#include "vast/table_index.hpp"
#include "vast/table_slice.hpp"
#include "vast/time.hpp"
#include "vast/detail/overload.hpp"
#include "vast/detail/set_operations.hpp"
#include "vast/detail/string.hpp"
namespace vast {
meta_index::meta_index()
: make_synopsis_{make_synopsis},
factory_id_{caf::atom("Sy_Default")} {
// nop
}
void meta_index::add(const uuid& partition, const table_slice& slice) {
auto& part_synopsis = partition_synopses_[partition];
auto& layout = slice.layout();
if (blacklisted_layouts_.count(layout) == 1)
return;
auto i = part_synopsis.find(layout);
table_synopsis* table_syn;
if (i != part_synopsis.end()) {
table_syn = &i->second;
} else {
// Create new synopses for a layout we haven't seen before.
i = part_synopsis.emplace(layout, table_synopsis{}).first;
table_syn = &i->second;
for (auto& field : layout.fields)
if (i->second.emplace_back(make_synopsis_(field.type, synopsis_options_))
!= nullptr)
VAST_DEBUG(this, "created new synopsis structure for type", field.type);
// If we couldn't create a single synopsis for the layout, we will no
// longer attempt to create synopses in the future.
auto is_nullptr = [](auto& x) { return x == nullptr; };
if (std::all_of(table_syn->begin(), table_syn->end(), is_nullptr)) {
VAST_DEBUG(this, "could not create a synopsis for layout:", layout);
blacklisted_layouts_.insert(layout);
}
}
VAST_ASSERT(table_syn->size() == slice.columns());
for (size_t col = 0; col < slice.columns(); ++col)
if (auto& syn = (*table_syn)[col])
for (size_t row = 0; row < slice.rows(); ++row)
syn->add(slice.at(row, col));
}
std::vector<uuid> meta_index::lookup(const expression& expr) const {
VAST_ASSERT(!caf::holds_alternative<caf::none_t>(expr));
// TODO: we could consider a flat_set<uuid> here, which would then have
// overloads for inplace intersection/union and simplify the implementation
// of this function a bit.
using result_type = std::vector<uuid>;
auto all_partitions = [&] {
result_type result;
result.reserve(partition_synopses_.size());
std::transform(partition_synopses_.begin(),
partition_synopses_.end(),
std::back_inserter(result),
[](auto& x) { return x.first; });
std::sort(result.begin(), result.end());
return result;
};
return caf::visit(detail::overload(
[&](const conjunction& x) -> result_type {
VAST_ASSERT(!x.empty());
auto i = x.begin();
auto result = lookup(*i);
if (!result.empty())
for (++i; i != x.end(); ++i) {
auto xs = lookup(*i);
if (xs.empty())
return xs; // short-circuit
detail::inplace_intersect(result, xs);
}
return result;
},
[&](const disjunction& x) -> result_type {
result_type result;
for (auto& op : x) {
auto xs = lookup(op);
if (xs.size() == partition_synopses_.size())
return xs; // short-circuit
detail::inplace_unify(result, xs);
}
return result;
},
[&](const negation&) -> result_type {
// We cannot handle negations, because a synopsis may return false
// positives, and negating such a result may cause false negatives.
return all_partitions();
},
[&](const predicate& x) -> result_type {
// Performs a lookup on all *matching* synopses with operator and data
// from the predicate of the expression. The match function uses a record
// field to determine whether the synopsis should be queried.
auto search = [&](auto match) {
VAST_ASSERT(caf::holds_alternative<data>(x.rhs));
auto& rhs = caf::get<data>(x.rhs);
result_type result;
auto found_matching_synopsis = false;
for (auto& [part_id, part_syn] : partition_synopses_)
for (auto& [layout, table_syn] : part_syn)
for (size_t i = 0; i < table_syn.size(); ++i)
if (table_syn[i] && match(layout.fields[i])) {
found_matching_synopsis = true;
if (table_syn[i]->lookup(x.op, make_view(rhs)))
if (result.empty() || result.back() != part_id)
result.push_back(part_id);
}
std::sort(result.begin(), result.end());
return found_matching_synopsis ? result : all_partitions();
};
return caf::visit(detail::overload(
[&](const attribute_extractor& lhs, const data& d) -> result_type {
if (lhs.attr == system::time_atom::value) {
auto pred = [](auto& field) {
// FIXME: we should really just look at the ×tamp attribute
// and not all fields of type time. [ch3843]
return caf::holds_alternative<timestamp_type>(field.type);
};
return search(pred);
} else if (lhs.attr == system::type_atom::value) {
result_type result;
for (auto& [part_id, part_syn] : partition_synopses_)
for (auto& pair : part_syn)
if (evaluate(pair.first.name(), x.op, d))
if (result.empty() || result.back() != part_id)
result.push_back(part_id);
return result;
}
VAST_WARNING(this, "cannot process attribute extractor:", lhs.attr);
return all_partitions();
},
[&](const key_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) {
return detail::ends_with(field.name, lhs.key);
};
return search(pred);
},
[&](const type_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) { return field.type == lhs.type; };
return search(pred);
},
[&](const auto&, const auto&) -> result_type {
VAST_WARNING(this, "cannot process predicate:", x);
return all_partitions();
}
), x.lhs, x.rhs);
},
[&](caf::none_t) -> result_type {
VAST_ERROR(this, "received an empty expression");
VAST_ASSERT(!"invalid expression");
return all_partitions();
}
), expr);
}
void meta_index::factory(caf::atom_value factory_id,
synopsis_factory f) {
factory_id_ = factory_id;
make_synopsis_ = f;
blacklisted_layouts_.clear();
}
std::pair<caf::atom_value, synopsis_factory> meta_index::factory() const {
return {factory_id_, make_synopsis_};
}
synopsis_options& meta_index::factory_options() {
return synopsis_options_;
}
caf::error inspect(caf::serializer& sink, const meta_index& x) {
return sink(x.factory_id_, x.synopsis_options_, x.partition_synopses_);
}
caf::error inspect(caf::deserializer& source, meta_index& x) {
if (auto ex = deserialize_synopsis_factory(source))
x.factory(ex->first, ex->second);
else
return std::move(ex.error());
return source(x.synopsis_options_, x.partition_synopses_);
}
} // namespace vast
<|endoftext|> |
<commit_before>#ifndef _MPH_HASH_H_
#define _MPH_HASH_H_
#include <cmath>
#include <vector.hpp>
#include <list.hpp>
namespace hash_functions {
int knuth_div_hash(int k, int n) {
return (k * (k + 3) ) % n;
}
int mod_hash(int k, int n) {
return k % n;
}
int mult_hash(int k, int n) {
float A = 0.5 * (sqrt(5) - 1);
int s = floor(A * pow(2, 32));
int x = k * s;
return x >> (32 - 16);
}
int knuth_mult_hash(int k, int n) {
return (k * 2654435761) >> (32 - (int)floor(log2(n)));
}
int basic_hash(int k, int n) {
return knuth_mult_hash(k, n);
}
};
template <typename T>
class HashTable {
private:
int blocks;
int (*hash_function)(int, int);
Vector<List<T> > * contents;
public:
HashTable();
HashTable(int n);
HashTable(int (*func)(int, int));
HashTable(int (*func)(int, int), int n);
~HashTable();
int size() const;
int block_length(int block) const { return contents->at(block).size(); }
};
template <typename T> using Hash = HashTable<T>;
template <typename T>
HashTable<T>::HashTable() {
hash_function = hash_functions::basic_hash;
blocks = 100;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::HashTable(int s) {
hash_function = hash_functions::basic_hash;
blocks = s;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::HashTable(int (*func)(int, int)) {
hash_function = func;
blocks = 100;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::HashTable(int (*func)(int, int), int n) {
hash_function = func;
blocks = n;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::~HashTable() {
delete contents;
}
template <typename T>
int HashTable<T>::size() const {
int count;
for (int i = 0; i < blocks; i++) {
count += this->block_size(i);
}
return count;
}
#endif
<commit_msg>Hash work<commit_after>#ifndef _MPH_HASH_H_
#define _MPH_HASH_H_
#include <cmath>
#include <vector.hpp>
#include <list.hpp>
namespace hash_functions {
int knuth_div_hash(long k, int n) {
return (k * (k + 3) ) % n;
}
int mod_hash(long k, int n) {
return k % n;
}
int mult_hash(long k, int n) {
float A = 0.5 * (sqrt(5) - 1);
int s = floor(A * pow(2, 32));
int x = k * s;
return x >> (32 - 16);
}
int knuth_mult_hash(long k, int n) {
return (k * 2654435761) >> (32 - (int)floor(log2(n)));
}
int basic_hash(long k, int n) {
return knuth_mult_hash(k, n);
}
};
template <typename T>
class HashTable {
private:
int blocks;
int (*hash_function)(long, int);
Vector<List<T> > * contents;
public:
HashTable();
HashTable(int n);
HashTable(int (*func)(int, int));
HashTable(int (*func)(int, int), int n);
~HashTable();
int size() const { return blocks; }
int block_length(int block) const { return contents->at(block).size(); }
int insert(T data);
List<T> * const get_block(int block);
T find(T data);
};
template <typename T> using Hash = HashTable<T>;
template <typename T>
HashTable<T>::HashTable() {
hash_function = hash_functions::basic_hash;
blocks = 100;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::HashTable(int s) {
hash_function = hash_functions::basic_hash;
blocks = s;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::HashTable(int (*func)(int, int)) {
hash_function = func;
blocks = 100;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::HashTable(int (*func)(int, int), int n) {
hash_function = func;
blocks = n;
contents = new Vector<List<T> >(blocks);
}
template <typename T>
HashTable<T>::~HashTable() {
delete contents;
}
template <typename T>
int HashTable<T>::insert(T data) {
int k = hash_function((long)(data), size);
contents->at(k).append(data);
return k;
}
template <typename T>
List<T> * const HashTable<T>::get_block(int block) {
return contents->at(block);
}
template <typename T>
T HashTable<T>::find(T data) {
int k = hash_function((long)(data), size);
return
}
#endif
<|endoftext|> |
<commit_before>#include <Halide.h>
#include "halide-hexagon-setup.h"
#include <stdio.h>
using namespace Halide;
using namespace Halide::Internal;
IRPrinter irp(std::cerr);
// RUN: rm -f stdout; ./nv12-max.out; llvm-dis -o stdout nv12torgb888.bc ;FileCheck %s < stdout
//CHECK-NOT: vmax
#define COMPILE_OBJ(X) ((X).compile_to_file("nv12torgb888", args, target))
/*
* Conversion from nv12 (4:2:0) to rgb888.
*/
void test_nv12torgb888(Target& target) {
Var x("x"),y("y");
ImageParam inputY(type_of<uint8_t>(), 2);
ImageParam inputUV(type_of<uint8_t>(), 2);
// Y channel
Expr scaleY = inputY(x,y);
scaleY = cast<int32_t>(scaleY);
Expr r = clamp(scaleY, 0, 262143);
Func nv12torgb888("nv12torgb888");
nv12torgb888(x,y) = r;
nv12torgb888.vectorize(x,128);
std::vector<Argument> args(2);
args[0] = inputY;
args[1] = inputUV;
nv12torgb888.compile_to_bitcode("nv12torgb888.bc", args, target);
}
int main(int argc, char **argv) {
Target target;
setupHexagonTarget(target);
commonTestSetup(target);
target.set_feature(Target::HVX_128);
test_nv12torgb888(target);
printf ("Done\n");
return 0;
}
<commit_msg>Unxfail nv12-max test, ie undo the check-not into a check<commit_after>#include <Halide.h>
#include "halide-hexagon-setup.h"
#include <stdio.h>
using namespace Halide;
using namespace Halide::Internal;
IRPrinter irp(std::cerr);
// RUN: rm -f stdout; ./nv12-max.out; llvm-dis -o stdout nv12torgb888.bc ;FileCheck %s < stdout
//CHECK: vmax
#define COMPILE_OBJ(X) ((X).compile_to_file("nv12torgb888", args, target))
/*
* Conversion from nv12 (4:2:0) to rgb888.
*/
void test_nv12torgb888(Target& target) {
Var x("x"),y("y");
ImageParam inputY(type_of<uint8_t>(), 2);
ImageParam inputUV(type_of<uint8_t>(), 2);
// Y channel
Expr scaleY = inputY(x,y);
scaleY = cast<int32_t>(scaleY);
Expr r = clamp(scaleY, 0, 262143);
Func nv12torgb888("nv12torgb888");
nv12torgb888(x,y) = r;
nv12torgb888.vectorize(x,128);
std::vector<Argument> args(2);
args[0] = inputY;
args[1] = inputUV;
nv12torgb888.compile_to_bitcode("nv12torgb888.bc", args, target);
}
int main(int argc, char **argv) {
Target target;
setupHexagonTarget(target);
commonTestSetup(target);
target.set_feature(Target::HVX_128);
test_nv12torgb888(target);
printf ("Done\n");
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <interfaces/chain.h>
#include <node/context.h>
#include <wallet/coinselection.h>
#include <wallet/spend.h>
#include <wallet/wallet.h>
#include <set>
static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<std::unique_ptr<CWalletTx>>& wtxs)
{
static int nextLockTime = 0;
CMutableTransaction tx;
tx.nLockTime = nextLockTime++; // so all transactions get different hashes
tx.vout.resize(1);
tx.vout[0].nValue = nValue;
wtxs.push_back(std::make_unique<CWalletTx>(MakeTransactionRef(std::move(tx))));
}
// Simple benchmark for wallet coin selection. Note that it maybe be necessary
// to build up more complicated scenarios in order to get meaningful
// measurements of performance. From laanwj, "Wallet coin selection is probably
// the hardest, as you need a wider selection of scenarios, just testing the
// same one over and over isn't too useful. Generating random isn't useful
// either for measurements."
// (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484)
static void CoinSelection(benchmark::Bench& bench)
{
NodeContext node;
auto chain = interfaces::MakeChain(node);
CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
wallet.SetupLegacyScriptPubKeyMan();
std::vector<std::unique_ptr<CWalletTx>> wtxs;
LOCK(wallet.cs_wallet);
// Add coins.
for (int i = 0; i < 1000; ++i) {
addCoin(1000 * COIN, wallet, wtxs);
}
addCoin(3 * COIN, wallet, wtxs);
// Create coins
std::vector<COutput> coins;
for (const auto& wtx : wtxs) {
coins.emplace_back(wallet, *wtx, 0 /* iIn */, 6 * 24 /* nDepthIn */, true /* spendable */, true /* solvable */, true /* safe */);
}
const CoinEligibilityFilter filter_standard(1, 6, 0);
const CoinSelectionParams coin_selection_params(/* change_output_size= */ 34,
/* change_spend_size= */ 148, /* effective_feerate= */ CFeeRate(0),
/* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
/* tx_noinputs_size= */ 0, /* avoid_partial= */ false);
bench.run([&] {
std::set<CInputCoin> setCoinsRet;
CAmount nValueRet;
bool success = AttemptSelection(wallet, 1003 * COIN, filter_standard, coins, setCoinsRet, nValueRet, coin_selection_params);
assert(success);
assert(nValueRet == 1003 * COIN);
assert(setCoinsRet.size() == 2);
});
}
typedef std::set<CInputCoin> CoinSet;
static NodeContext testNode;
static auto testChain = interfaces::MakeChain(testNode);
static CWallet testWallet(testChain.get(), "", CreateDummyWalletDatabase());
std::vector<std::unique_ptr<CWalletTx>> wtxn;
// Copied from src/wallet/test/coinselector_tests.cpp
static void add_coin(const CAmount& nValue, int nInput, std::vector<OutputGroup>& set)
{
CMutableTransaction tx;
tx.vout.resize(nInput + 1);
tx.vout[nInput].nValue = nValue;
std::unique_ptr<CWalletTx> wtx = std::make_unique<CWalletTx>(MakeTransactionRef(std::move(tx)));
set.emplace_back();
set.back().Insert(COutput(testWallet, *wtx, nInput, 0, true, true, true).GetInputCoin(), 0, true, 0, 0, false);
wtxn.emplace_back(std::move(wtx));
}
// Copied from src/wallet/test/coinselector_tests.cpp
static CAmount make_hard_case(int utxos, std::vector<OutputGroup>& utxo_pool)
{
utxo_pool.clear();
CAmount target = 0;
for (int i = 0; i < utxos; ++i) {
target += (CAmount)1 << (utxos+i);
add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);
add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);
}
return target;
}
static void BnBExhaustion(benchmark::Bench& bench)
{
// Setup
testWallet.SetupLegacyScriptPubKeyMan();
std::vector<OutputGroup> utxo_pool;
CoinSet selection;
CAmount value_ret = 0;
bench.run([&] {
// Benchmark
CAmount target = make_hard_case(17, utxo_pool);
SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret); // Should exhaust
// Cleanup
utxo_pool.clear();
selection.clear();
});
}
BENCHMARK(CoinSelection);
BENCHMARK(BnBExhaustion);
<commit_msg>bench: remove global testWallet from CoinSelection benchmark<commit_after>// Copyright (c) 2012-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <interfaces/chain.h>
#include <node/context.h>
#include <wallet/coinselection.h>
#include <wallet/spend.h>
#include <wallet/wallet.h>
#include <set>
static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<std::unique_ptr<CWalletTx>>& wtxs)
{
static int nextLockTime = 0;
CMutableTransaction tx;
tx.nLockTime = nextLockTime++; // so all transactions get different hashes
tx.vout.resize(1);
tx.vout[0].nValue = nValue;
wtxs.push_back(std::make_unique<CWalletTx>(MakeTransactionRef(std::move(tx))));
}
// Simple benchmark for wallet coin selection. Note that it maybe be necessary
// to build up more complicated scenarios in order to get meaningful
// measurements of performance. From laanwj, "Wallet coin selection is probably
// the hardest, as you need a wider selection of scenarios, just testing the
// same one over and over isn't too useful. Generating random isn't useful
// either for measurements."
// (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484)
static void CoinSelection(benchmark::Bench& bench)
{
NodeContext node;
auto chain = interfaces::MakeChain(node);
CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
wallet.SetupLegacyScriptPubKeyMan();
std::vector<std::unique_ptr<CWalletTx>> wtxs;
LOCK(wallet.cs_wallet);
// Add coins.
for (int i = 0; i < 1000; ++i) {
addCoin(1000 * COIN, wallet, wtxs);
}
addCoin(3 * COIN, wallet, wtxs);
// Create coins
std::vector<COutput> coins;
for (const auto& wtx : wtxs) {
coins.emplace_back(wallet, *wtx, 0 /* iIn */, 6 * 24 /* nDepthIn */, true /* spendable */, true /* solvable */, true /* safe */);
}
const CoinEligibilityFilter filter_standard(1, 6, 0);
const CoinSelectionParams coin_selection_params(/* change_output_size= */ 34,
/* change_spend_size= */ 148, /* effective_feerate= */ CFeeRate(0),
/* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
/* tx_noinputs_size= */ 0, /* avoid_partial= */ false);
bench.run([&] {
std::set<CInputCoin> setCoinsRet;
CAmount nValueRet;
bool success = AttemptSelection(wallet, 1003 * COIN, filter_standard, coins, setCoinsRet, nValueRet, coin_selection_params);
assert(success);
assert(nValueRet == 1003 * COIN);
assert(setCoinsRet.size() == 2);
});
}
typedef std::set<CInputCoin> CoinSet;
// Copied from src/wallet/test/coinselector_tests.cpp
static void add_coin(const CAmount& nValue, int nInput, std::vector<OutputGroup>& set)
{
CMutableTransaction tx;
tx.vout.resize(nInput + 1);
tx.vout[nInput].nValue = nValue;
CInputCoin coin(MakeTransactionRef(tx), nInput);
set.emplace_back();
set.back().Insert(coin, 0, true, 0, 0, false);
}
// Copied from src/wallet/test/coinselector_tests.cpp
static CAmount make_hard_case(int utxos, std::vector<OutputGroup>& utxo_pool)
{
utxo_pool.clear();
CAmount target = 0;
for (int i = 0; i < utxos; ++i) {
target += (CAmount)1 << (utxos+i);
add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);
add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);
}
return target;
}
static void BnBExhaustion(benchmark::Bench& bench)
{
// Setup
std::vector<OutputGroup> utxo_pool;
CoinSet selection;
CAmount value_ret = 0;
bench.run([&] {
// Benchmark
CAmount target = make_hard_case(17, utxo_pool);
SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret); // Should exhaust
// Cleanup
utxo_pool.clear();
selection.clear();
});
}
BENCHMARK(CoinSelection);
BENCHMARK(BnBExhaustion);
<|endoftext|> |
<commit_before><commit_msg>Update inlineMathFunctions.hpp<commit_after><|endoftext|> |
<commit_before>#pragma once
/*
MIT License
Copyright (c) 2017 Arlen Keshabyan ([email protected])
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 "external/json/include/nlohmann/json.hpp"
#include "ordered_map_set.hpp"
namespace nstd
{
template<class Key, class T, class Ignore, class Ignore2, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator<std::pair<Key, T>>>
using ordered_map = tsl::ordered_map<Key, T, Hash, KeyEqual, Allocator>;
namespace json
{
using namespace nlohmann;
using json_ord = nlohmann::basic_json<ordered_map>;
}
}
inline nstd::json::json_ord operator "" _json_ord(const char* s, std::size_t n)
{
return nstd::json::json_ord::parse(s, s + n);
}
inline nstd::json::json_ord::json_pointer operator "" _json_ord_pointer(const char* s, std::size_t n)
{
return nstd::json::json_ord::json_pointer(std::string(s, n));
}
<commit_msg>ordered_map fix<commit_after>#pragma once
/*
MIT License
Copyright (c) 2017 Arlen Keshabyan ([email protected])
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 "external/json/include/nlohmann/json.hpp"
#include "ordered_map_set.hpp"
namespace nstd
{
template<class Key, class T, class Ignore, class Allocator, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>>
using ordered_map = tsl::ordered_map<Key, T, Hash, KeyEqual, typename std::allocator_traits<Allocator>::template rebind_alloc<std::pair<Key, T>>>;
namespace json
{
using namespace nlohmann;
using json_ord = nlohmann::basic_json<ordered_map>;
}
}
inline nstd::json::json_ord operator "" _json_ord(const char* s, std::size_t n)
{
return nstd::json::json_ord::parse(s, s + n);
}
inline nstd::json::json_ord::json_pointer operator "" _json_ord_pointer(const char* s, std::size_t n)
{
return nstd::json::json_ord::json_pointer(std::string(s, n));
}
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2013 VMware, Inc.
* All Rights Reserved.
*
* 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 <limits.h> // for CHAR_MAX
#include <getopt.h>
#include <string>
#include "cli.hpp"
#include "os_string.hpp"
#include "trace_parser.hpp"
#include "trace_writer.hpp"
static const char *synopsis = "Stream editing of a trace.";
static void
usage(void)
{
std::cout
<< "usage: apitrace sed [OPTIONS] TRACE_FILE...\n"
<< synopsis << "\n"
"\n"
" -h, --help Show detailed help for sed options and exit\n"
" -e s/SEARCH/REPLACE/ Search and replace a symbol. Use @file(<path>)\n"
" to read SEARCH or REPLACE from a file.\n"
" Any character (not just /) can be used as \n"
" separator.\n"
" XXX: Only works for enums and strings.\n"
" -o, --output=TRACE_FILE Output trace file\n"
" --property=NAME=VALUE Set a property\n"
;
}
enum {
PROPERTY_OPT = CHAR_MAX + 1,
};
const static char *
shortOptions = "ho:e:";
const static struct option
longOptions[] = {
{"help", no_argument, 0, 'h'},
{"output", required_argument, 0, 'o'},
{"property", required_argument, 0, PROPERTY_OPT},
{0, 0, 0, 0}
};
using namespace trace;
/**
* A visitor that replaces symbol constants.
*/
class Replacer : public Visitor
{
protected:
std::string searchName;
std::string replaceName;
public:
Replacer(const std::string & _searchName, const std::string & _replaceName) :
searchName(_searchName),
replaceName(_replaceName)
{
}
~Replacer() {
}
void visit(Null *) override {
}
void visit(Bool *node) override {
}
void visit(SInt *node) override {
}
void visit(UInt *node) override {
}
void visit(Float *node) override {
}
void visit(Double *node) override {
}
void visit(String *node) override {
if (!searchName.compare(node->value)) {
size_t len = replaceName.length() + 1;
delete [] node->value;
char *str = new char [len];
memcpy(str, replaceName.c_str(), len);
node->value = str;
}
}
void visit(WString *node) override {
}
void visit(Enum *node) override {
const EnumValue *it = node->lookup();
if (it) {
if (searchName.compare(it->name) == 0) {
const EnumSig *sig = node->sig;
for (unsigned i = 0; i < sig->num_values; ++i) {
if (replaceName.compare(sig->values[i].name) == 0) {
node->value = sig->values[i].value;
break;
}
}
}
}
}
void visit(Bitmask *bitmask) override {
}
void visit(Struct *s) override {
for (auto memberValue : s->members) {
_visit(memberValue);
}
}
void visit(Array *array) override {
for (auto & value : array->values) {
_visit(value);
}
}
void visit(Blob *blob) override {
}
void visit(Pointer *p) override {
}
void visit(Repr *r) override {
_visit(r->humanValue);
}
void visit(Call *call) {
for (auto & arg : call->args) {
if (arg.value) {
_visit(arg.value);
}
}
if (call->ret) {
_visit(call->ret);
}
}
};
typedef std::list<Replacer> Replacements;
static int
sed_trace(Replacements &replacements,
const trace::Properties &extraProperties,
const char *inFileName,
std::string &outFileName)
{
trace::Parser p;
if (!p.open(inFileName)) {
std::cerr << "error: failed to open " << inFileName << "\n";
return 1;
}
/* Prepare outFileName file and writer for outFileName. */
if (outFileName.empty()) {
os::String base(inFileName);
base.trimExtension();
outFileName = std::string(base.str()) + std::string("-sed.trace");
}
trace::Properties properties(p.getProperties());
for (auto & kv : extraProperties) {
properties[kv.first] = kv.second;
}
trace::Writer writer;
if (!writer.open(outFileName.c_str(), p.getVersion(), properties)) {
std::cerr << "error: failed to create " << outFileName << "\n";
return 1;
}
trace::Call *call;
while ((call = p.parse_call())) {
for (auto & replacement : replacements) {
replacement.visit(call);
}
writer.writeCall(call);
delete call;
}
std::cerr << "Edited trace is available as " << outFileName << "\n";
return 0;
}
/**
* Parse a string in the format "s/SEARCH/REPLACE/".
*/
static bool
parseSubstOpt(Replacements &replacements, const char *opt)
{
char separator;
if (*opt++ != 's') {
return false;
}
separator = *opt++;
// Parse the search pattern
const char *search_begin = opt;
while (*opt != separator) {
if (*opt == 0) {
return false;
}
++opt;
}
const char *search_end = opt++;
// Parse the replace pattern
const char *replace_begin = opt;
while (*opt != separator) {
if (*opt == 0) {
return false;
}
++opt;
}
const char *replace_end = opt++;
if (*opt != 0) {
return false;
}
std::string search(search_begin, search_end);
std::string replace(replace_begin, replace_end);
// If search or replace strings are taken from a file, read the file
std::string file_subst = "@file(";
for (int i = 0; i < 2; i++) {
std::string *str = i ? &search : &replace;
if (!str->compare(0, file_subst.length(), file_subst)) {
if ((*str)[str->length()-1] != ')') {
return false;
}
std::string fname = str->substr(file_subst.length());
fname[fname.length()-1] = 0;
FILE *f = fopen(fname.c_str(), "rt");
if (!f) {
std::cerr << "error: cannot open file " << fname << "\n";
return false;
}
char buf[1024];
(*str) = "";
while (!feof(f)) {
if (fgets(buf, 1024, f)) {
str->append(buf);
}
}
fclose(f);
}
}
replacements.push_back(Replacer(search, replace));
return true;
}
static int
command(int argc, char *argv[])
{
Replacements replacements;
trace::Properties extraProperties;
std::string outFileName;
int opt;
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
switch (opt) {
case 'h':
usage();
return 0;
case 'o':
outFileName = optarg;
break;
case 'e':
if (!parseSubstOpt(replacements, optarg)) {
std::cerr << "error: invalid replacement pattern `" << optarg << "`\n";
return 1;
}
break;
case PROPERTY_OPT:
{
const char *sep = strchr(optarg, '=');
if (sep == nullptr) {
std::cerr << "error: bad property `" << optarg << "`\n";
return 1;
}
std::string name(static_cast<const char *>(optarg), sep);
std::string value(sep + 1);
extraProperties[name] = value;
break;
}
default:
std::cerr << "error: unexpected option `" << (char)opt << "`\n";
usage();
return 1;
}
}
if (optind >= argc) {
std::cerr << "error: apitrace sed requires a trace file as an argument.\n";
usage();
return 1;
}
if (argc > optind + 1) {
std::cerr << "error: extraneous arguments:";
for (int i = optind + 1; i < argc; i++) {
std::cerr << " " << argv[i];
}
std::cerr << "\n";
usage();
return 1;
}
return sed_trace(replacements, extraProperties, argv[optind], outFileName);
}
const Command sed_command = {
"sed",
synopsis,
usage,
command
};
<commit_msg>cli: Support pointer substitution in sed<commit_after>/**************************************************************************
*
* Copyright 2013 VMware, Inc.
* All Rights Reserved.
*
* 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 <limits.h> // for CHAR_MAX
#include <getopt.h>
#include <string>
#include "cli.hpp"
#include "os_string.hpp"
#include "trace_parser.hpp"
#include "trace_writer.hpp"
static const char *synopsis = "Stream editing of a trace.";
static void
usage(void)
{
std::cout
<< "usage: apitrace sed [OPTIONS] TRACE_FILE...\n"
<< synopsis << "\n"
"\n"
" -h, --help Show detailed help for sed options and exit\n"
" -e s/SEARCH/REPLACE/ Search and replace a symbol. Use @file(<path>)\n"
" to read SEARCH or REPLACE from a file.\n"
" Any character (not just /) can be used as \n"
" separator.\n"
" XXX: Only works for enums and strings.\n"
" -o, --output=TRACE_FILE Output trace file\n"
" --property=NAME=VALUE Set a property\n"
;
}
enum {
PROPERTY_OPT = CHAR_MAX + 1,
};
const static char *
shortOptions = "ho:e:";
const static struct option
longOptions[] = {
{"help", no_argument, 0, 'h'},
{"output", required_argument, 0, 'o'},
{"property", required_argument, 0, PROPERTY_OPT},
{0, 0, 0, 0}
};
using namespace trace;
/**
* A visitor that replaces symbol constants.
*/
class Replacer : public Visitor
{
protected:
std::string searchString;
std::string replaceString;
bool isPointer = false;
unsigned long long searchPointer = 0;
unsigned long long replacePointer = 0;
public:
Replacer(const std::string & _searchString, const std::string & _replaceString) :
searchString(_searchString),
replaceString(_replaceString)
{
if (searchString.length() > 2 &&
searchString[0] == '0' &&
searchString[1] == 'x') {
isPointer = true;
searchPointer = std::stoull(searchString, 0, 16);
assert(searchPointer);
replacePointer = std::stoull(replaceString, 0, 16);
assert(replacePointer);
}
}
~Replacer() {
}
void visit(Null *) override {
}
void visit(Bool *node) override {
}
void visit(SInt *node) override {
}
void visit(UInt *node) override {
}
void visit(Float *node) override {
}
void visit(Double *node) override {
}
void visit(String *node) override {
if (!searchString.compare(node->value)) {
size_t len = replaceString.length() + 1;
delete [] node->value;
char *str = new char [len];
memcpy(str, replaceString.c_str(), len);
node->value = str;
}
}
void visit(WString *node) override {
}
void visit(Enum *node) override {
const EnumValue *it = node->lookup();
if (it) {
if (searchString.compare(it->name) == 0) {
const EnumSig *sig = node->sig;
for (unsigned i = 0; i < sig->num_values; ++i) {
if (replaceString.compare(sig->values[i].name) == 0) {
node->value = sig->values[i].value;
break;
}
}
}
}
}
void visit(Bitmask *bitmask) override {
}
void visit(Struct *s) override {
for (auto memberValue : s->members) {
_visit(memberValue);
}
}
void visit(Array *array) override {
for (auto & value : array->values) {
_visit(value);
}
}
void visit(Blob *blob) override {
}
void visit(Pointer *p) override {
if (isPointer &&
p->value == searchPointer) {
p->value = replacePointer;
}
}
void visit(Repr *r) override {
_visit(r->humanValue);
}
void visit(Call *call) {
for (auto & arg : call->args) {
if (arg.value) {
_visit(arg.value);
}
}
if (call->ret) {
_visit(call->ret);
}
}
};
typedef std::list<Replacer> Replacements;
static int
sed_trace(Replacements &replacements,
const trace::Properties &extraProperties,
const char *inFileName,
std::string &outFileName)
{
trace::Parser p;
if (!p.open(inFileName)) {
std::cerr << "error: failed to open " << inFileName << "\n";
return 1;
}
/* Prepare outFileName file and writer for outFileName. */
if (outFileName.empty()) {
os::String base(inFileName);
base.trimExtension();
outFileName = std::string(base.str()) + std::string("-sed.trace");
}
trace::Properties properties(p.getProperties());
for (auto & kv : extraProperties) {
properties[kv.first] = kv.second;
}
trace::Writer writer;
if (!writer.open(outFileName.c_str(), p.getVersion(), properties)) {
std::cerr << "error: failed to create " << outFileName << "\n";
return 1;
}
trace::Call *call;
while ((call = p.parse_call())) {
for (auto & replacement : replacements) {
replacement.visit(call);
}
writer.writeCall(call);
delete call;
}
std::cerr << "Edited trace is available as " << outFileName << "\n";
return 0;
}
/**
* Parse a string in the format "s/SEARCH/REPLACE/".
*/
static bool
parseSubstOpt(Replacements &replacements, const char *opt)
{
char separator;
if (*opt++ != 's') {
return false;
}
separator = *opt++;
// Parse the search pattern
const char *search_begin = opt;
while (*opt != separator) {
if (*opt == 0) {
return false;
}
++opt;
}
const char *search_end = opt++;
// Parse the replace pattern
const char *replace_begin = opt;
while (*opt != separator) {
if (*opt == 0) {
return false;
}
++opt;
}
const char *replace_end = opt++;
if (*opt != 0) {
return false;
}
std::string search(search_begin, search_end);
std::string replace(replace_begin, replace_end);
// If search or replace strings are taken from a file, read the file
std::string file_subst = "@file(";
for (int i = 0; i < 2; i++) {
std::string *str = i ? &search : &replace;
if (!str->compare(0, file_subst.length(), file_subst)) {
if ((*str)[str->length()-1] != ')') {
return false;
}
std::string fname = str->substr(file_subst.length());
fname[fname.length()-1] = 0;
FILE *f = fopen(fname.c_str(), "rt");
if (!f) {
std::cerr << "error: cannot open file " << fname << "\n";
return false;
}
char buf[1024];
(*str) = "";
while (!feof(f)) {
if (fgets(buf, 1024, f)) {
str->append(buf);
}
}
fclose(f);
}
}
replacements.push_back(Replacer(search, replace));
return true;
}
static int
command(int argc, char *argv[])
{
Replacements replacements;
trace::Properties extraProperties;
std::string outFileName;
int opt;
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
switch (opt) {
case 'h':
usage();
return 0;
case 'o':
outFileName = optarg;
break;
case 'e':
if (!parseSubstOpt(replacements, optarg)) {
std::cerr << "error: invalid replacement pattern `" << optarg << "`\n";
return 1;
}
break;
case PROPERTY_OPT:
{
const char *sep = strchr(optarg, '=');
if (sep == nullptr) {
std::cerr << "error: bad property `" << optarg << "`\n";
return 1;
}
std::string name(static_cast<const char *>(optarg), sep);
std::string value(sep + 1);
extraProperties[name] = value;
break;
}
default:
std::cerr << "error: unexpected option `" << (char)opt << "`\n";
usage();
return 1;
}
}
if (optind >= argc) {
std::cerr << "error: apitrace sed requires a trace file as an argument.\n";
usage();
return 1;
}
if (argc > optind + 1) {
std::cerr << "error: extraneous arguments:";
for (int i = optind + 1; i < argc; i++) {
std::cerr << " " << argv[i];
}
std::cerr << "\n";
usage();
return 1;
}
return sed_trace(replacements, extraProperties, argv[optind], outFileName);
}
const Command sed_command = {
"sed",
synopsis,
usage,
command
};
<|endoftext|> |
<commit_before>#pragma once
#include <eosiolib/print.hpp>
#include <eosiolib/action.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/std_tuple.hpp>
#include <boost/mp11/tuple.hpp>
#define N(X) ::eosio::string_to_name(#X)
namespace eosio {
template<typename Contract, typename FirstAction>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return false;
}
/**
* This method will dynamically dispatch an incoming set of actions to
*
* ```
* static Contract::on( ActionType )
* ```
*
* For this to work the Actions must be dervied from the
*
*/
template<typename Contract, typename FirstAction, typename SecondAction, typename... Actions>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return eosio::dispatch<Contract,SecondAction,Actions...>( code, act );
}
template<typename T, typename... Args>
bool execute_action( T* obj, void (T::*func)(Args...) ) {
char buffer[action_data_size()];
read_action_data( buffer, sizeof(buffer) );
auto args = unpack<std::tuple<std::decay_t<Args>...>>( buffer, sizeof(buffer) );
auto f2 = [&]( auto... a ){
(obj->*func)( a... );
};
boost::mp11::tuple_apply( f2, args );
return true;
}
#define EOSIO_API_CALL( r, OP, elem ) \
case ::eosio::string_to_name( BOOST_PP_STRINGIZE(elem) ): \
eosio::execute_action( &thiscontract, &OP::elem ); \
return;
#define EOSIO_API( TYPE, MEMBERS ) \
BOOST_PP_SEQ_FOR_EACH( EOSIO_API_CALL, TYPE, MEMBERS )
#define EOSIO_ABI( TYPE, MEMBERS ) \
extern "C" { \
void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \
auto self = receiver; \
if( code == self ) { \
TYPE thiscontract( self ); \
switch( action ) { \
EOSIO_API( TYPE, MEMBERS ) \
} \
eosio_exit(0); \
} \
} \
} \
/*
template<typename T>
struct dispatcher {
dispatcher( account_name code ):_contract(code){}
template<typename FuncPtr>
void dispatch( account_name action, FuncPtr ) {
}
T contract;
};
void dispatch( account_name code, account_name action,
*/
}
<commit_msg>Allow a contract that uses EOSIO_ABI macro to inherit from another contract<commit_after>#pragma once
#include <eosiolib/print.hpp>
#include <eosiolib/action.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/std_tuple.hpp>
#include <boost/mp11/tuple.hpp>
#define N(X) ::eosio::string_to_name(#X)
namespace eosio {
template<typename Contract, typename FirstAction>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return false;
}
/**
* This method will dynamically dispatch an incoming set of actions to
*
* ```
* static Contract::on( ActionType )
* ```
*
* For this to work the Actions must be dervied from the
*
*/
template<typename Contract, typename FirstAction, typename SecondAction, typename... Actions>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return eosio::dispatch<Contract,SecondAction,Actions...>( code, act );
}
template<typename T, typename Q, typename... Args>
bool execute_action( T* obj, void (Q::*func)(Args...) ) {
char buffer[action_data_size()];
read_action_data( buffer, sizeof(buffer) );
auto args = unpack<std::tuple<std::decay_t<Args>...>>( buffer, sizeof(buffer) );
auto f2 = [&]( auto... a ){
(obj->*func)( a... );
};
boost::mp11::tuple_apply( f2, args );
return true;
}
#define EOSIO_API_CALL( r, OP, elem ) \
case ::eosio::string_to_name( BOOST_PP_STRINGIZE(elem) ): \
eosio::execute_action( &thiscontract, &OP::elem ); \
return;
#define EOSIO_API( TYPE, MEMBERS ) \
BOOST_PP_SEQ_FOR_EACH( EOSIO_API_CALL, TYPE, MEMBERS )
#define EOSIO_ABI( TYPE, MEMBERS ) \
extern "C" { \
void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \
auto self = receiver; \
if( code == self ) { \
TYPE thiscontract( self ); \
switch( action ) { \
EOSIO_API( TYPE, MEMBERS ) \
} \
eosio_exit(0); \
} \
} \
} \
/*
template<typename T>
struct dispatcher {
dispatcher( account_name code ):_contract(code){}
template<typename FuncPtr>
void dispatch( account_name action, FuncPtr ) {
}
T contract;
};
void dispatch( account_name code, account_name action,
*/
}
<|endoftext|> |
<commit_before>//===-- TimeProfiler.cpp - Hierarchical Time Profiler ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file Hierarchical time profiler implementation.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/TimeProfiler.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/FileSystem.h"
#include <cassert>
#include <chrono>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std::chrono;
namespace llvm {
TimeTraceProfiler *TimeTraceProfilerInstance = nullptr;
static std::string escapeString(StringRef Src) {
std::string OS;
for (const unsigned char &C : Src) {
switch (C) {
case '"':
case '/':
case '\\':
case '\b':
case '\f':
case '\n':
case '\r':
case '\t':
OS += '\\';
OS += C;
break;
default:
if (isPrint(C)) {
OS += C;
}
}
}
return OS;
}
typedef duration<steady_clock::rep, steady_clock::period> DurationType;
typedef std::pair<std::string, DurationType> NameAndDuration;
struct Entry {
time_point<steady_clock> Start;
DurationType Duration;
std::string Name;
std::string Detail;
};
struct TimeTraceProfiler {
TimeTraceProfiler() {
Stack.reserve(8);
Entries.reserve(128);
StartTime = steady_clock::now();
}
void begin(std::string Name, llvm::function_ref<std::string()> Detail) {
Entry E = {steady_clock::now(), {}, Name, Detail()};
Stack.push_back(std::move(E));
}
void end() {
assert(!Stack.empty() && "Must call begin() first");
auto &E = Stack.back();
E.Duration = steady_clock::now() - E.Start;
// Only include sections longer than 500us.
if (duration_cast<microseconds>(E.Duration).count() > 500)
Entries.emplace_back(E);
// Track total time taken by each "name", but only the topmost levels of
// them; e.g. if there's a template instantiation that instantiates other
// templates from within, we only want to add the topmost one. "topmost"
// happens to be the ones that don't have any currently open entries above
// itself.
if (std::find_if(++Stack.rbegin(), Stack.rend(), [&](const Entry &Val) {
return Val.Name == E.Name;
}) == Stack.rend()) {
TotalPerName[E.Name] += E.Duration;
CountPerName[E.Name]++;
}
Stack.pop_back();
}
void Write(std::unique_ptr<raw_pwrite_stream> &OS) {
assert(Stack.empty() &&
"All profiler sections should be ended when calling Write");
*OS << "{ \"traceEvents\": [\n";
// Emit all events for the main flame graph.
for (const auto &E : Entries) {
auto StartUs = duration_cast<microseconds>(E.Start - StartTime).count();
auto DurUs = duration_cast<microseconds>(E.Duration).count();
*OS << "{ \"pid\":1, \"tid\":0, \"ph\":\"X\", \"ts\":" << StartUs
<< ", \"dur\":" << DurUs << ", \"name\":\"" << escapeString(E.Name)
<< "\", \"args\":{ \"detail\":\"" << escapeString(E.Detail)
<< "\"} },\n";
}
// Emit totals by section name as additional "thread" events, sorted from
// longest one.
int Tid = 1;
std::vector<NameAndDuration> SortedTotals;
SortedTotals.reserve(TotalPerName.size());
for (const auto &E : TotalPerName) {
SortedTotals.push_back(E);
}
std::sort(SortedTotals.begin(), SortedTotals.end(),
[](const NameAndDuration &A, const NameAndDuration &B) {
return A.second > B.second;
});
for (const auto &E : SortedTotals) {
auto DurUs = duration_cast<microseconds>(E.second).count();
*OS << "{ \"pid\":1, \"tid\":" << Tid << ", \"ph\":\"X\", \"ts\":" << 0
<< ", \"dur\":" << DurUs << ", \"name\":\"Total "
<< escapeString(E.first)
<< "\", \"args\":{ \"count\":" << CountPerName[E.first]
<< ", \"avg ms\":" << (DurUs / CountPerName[E.first] / 1000)
<< "} },\n";
++Tid;
}
// Emit metadata event with process name.
*OS << "{ \"cat\":\"\", \"pid\":1, \"tid\":0, \"ts\":0, \"ph\":\"M\", "
"\"name\":\"process_name\", \"args\":{ \"name\":\"clang\" } }\n";
*OS << "] }\n";
}
std::vector<Entry> Stack;
std::vector<Entry> Entries;
std::unordered_map<std::string, DurationType> TotalPerName;
std::unordered_map<std::string, size_t> CountPerName;
time_point<steady_clock> StartTime;
};
void timeTraceProfilerInitialize() {
assert(TimeTraceProfilerInstance == nullptr &&
"Profiler should not be initialized");
TimeTraceProfilerInstance = new TimeTraceProfiler();
}
void timeTraceProfilerCleanup() {
delete TimeTraceProfilerInstance;
TimeTraceProfilerInstance = nullptr;
}
void timeTraceProfilerWrite(std::unique_ptr<raw_pwrite_stream> &OS) {
assert(TimeTraceProfilerInstance != nullptr &&
"Profiler object can't be null");
TimeTraceProfilerInstance->Write(OS);
}
void timeTraceProfilerBegin(StringRef Name, StringRef Detail) {
if (TimeTraceProfilerInstance != nullptr)
TimeTraceProfilerInstance->begin(Name, [&]() { return Detail; });
}
void timeTraceProfilerBegin(StringRef Name,
llvm::function_ref<std::string()> Detail) {
if (TimeTraceProfilerInstance != nullptr)
TimeTraceProfilerInstance->begin(Name, Detail);
}
void timeTraceProfilerEnd() {
if (TimeTraceProfilerInstance != nullptr)
TimeTraceProfilerInstance->end();
}
} // namespace llvm
<commit_msg>Improve hashing for time profiler<commit_after>//===-- TimeProfiler.cpp - Hierarchical Time Profiler ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file Hierarchical time profiler implementation.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/TimeProfiler.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/FileSystem.h"
#include <cassert>
#include <chrono>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std::chrono;
namespace llvm {
TimeTraceProfiler *TimeTraceProfilerInstance = nullptr;
static std::string escapeString(StringRef Src) {
std::string OS;
for (const unsigned char &C : Src) {
switch (C) {
case '"':
case '/':
case '\\':
case '\b':
case '\f':
case '\n':
case '\r':
case '\t':
OS += '\\';
OS += C;
break;
default:
if (isPrint(C)) {
OS += C;
}
}
}
return OS;
}
typedef duration<steady_clock::rep, steady_clock::period> DurationType;
typedef std::pair<size_t, DurationType> CountAndDurationType;
typedef std::pair<std::string, CountAndDurationType>
NameAndCountAndDurationType;
struct Entry {
time_point<steady_clock> Start;
DurationType Duration;
std::string Name;
std::string Detail;
};
struct TimeTraceProfiler {
TimeTraceProfiler() {
Stack.reserve(8);
Entries.reserve(128);
StartTime = steady_clock::now();
}
void begin(std::string Name, llvm::function_ref<std::string()> Detail) {
Entry E = {steady_clock::now(), {}, Name, Detail()};
Stack.push_back(std::move(E));
}
void end() {
assert(!Stack.empty() && "Must call begin() first");
auto &E = Stack.back();
E.Duration = steady_clock::now() - E.Start;
// Only include sections longer than 500us.
if (duration_cast<microseconds>(E.Duration).count() > 500)
Entries.emplace_back(E);
// Track total time taken by each "name", but only the topmost levels of
// them; e.g. if there's a template instantiation that instantiates other
// templates from within, we only want to add the topmost one. "topmost"
// happens to be the ones that don't have any currently open entries above
// itself.
if (std::find_if(++Stack.rbegin(), Stack.rend(), [&](const Entry &Val) {
return Val.Name == E.Name;
}) == Stack.rend()) {
auto &CountAndTotal = CountAndTotalPerName[E.Name];
CountAndTotal.first++;
CountAndTotal.second += E.Duration;
}
Stack.pop_back();
}
void Write(std::unique_ptr<raw_pwrite_stream> &OS) {
assert(Stack.empty() &&
"All profiler sections should be ended when calling Write");
*OS << "{ \"traceEvents\": [\n";
// Emit all events for the main flame graph.
for (const auto &E : Entries) {
auto StartUs = duration_cast<microseconds>(E.Start - StartTime).count();
auto DurUs = duration_cast<microseconds>(E.Duration).count();
*OS << "{ \"pid\":1, \"tid\":0, \"ph\":\"X\", \"ts\":" << StartUs
<< ", \"dur\":" << DurUs << ", \"name\":\"" << escapeString(E.Name)
<< "\", \"args\":{ \"detail\":\"" << escapeString(E.Detail)
<< "\"} },\n";
}
// Emit totals by section name as additional "thread" events, sorted from
// longest one.
int Tid = 1;
std::vector<NameAndCountAndDurationType> SortedTotals;
SortedTotals.reserve(CountAndTotalPerName.size());
for (const auto &E : CountAndTotalPerName) {
SortedTotals.emplace_back(E.getKey(), E.getValue());
}
std::sort(SortedTotals.begin(), SortedTotals.end(),
[](const NameAndCountAndDurationType &A,
const NameAndCountAndDurationType &B) {
return A.second.second > B.second.second;
});
for (const auto &E : SortedTotals) {
auto DurUs = duration_cast<microseconds>(E.second.second).count();
auto Count = CountAndTotalPerName[E.first].first;
*OS << "{ \"pid\":1, \"tid\":" << Tid << ", \"ph\":\"X\", \"ts\":" << 0
<< ", \"dur\":" << DurUs << ", \"name\":\"Total "
<< escapeString(E.first) << "\", \"args\":{ \"count\":" << Count
<< ", \"avg ms\":" << (DurUs / Count / 1000) << "} },\n";
++Tid;
}
// Emit metadata event with process name.
*OS << "{ \"cat\":\"\", \"pid\":1, \"tid\":0, \"ts\":0, \"ph\":\"M\", "
"\"name\":\"process_name\", \"args\":{ \"name\":\"clang\" } }\n";
*OS << "] }\n";
}
std::vector<Entry> Stack;
std::vector<Entry> Entries;
StringMap<CountAndDurationType> CountAndTotalPerName;
time_point<steady_clock> StartTime;
};
void timeTraceProfilerInitialize() {
assert(TimeTraceProfilerInstance == nullptr &&
"Profiler should not be initialized");
TimeTraceProfilerInstance = new TimeTraceProfiler();
}
void timeTraceProfilerCleanup() {
delete TimeTraceProfilerInstance;
TimeTraceProfilerInstance = nullptr;
}
void timeTraceProfilerWrite(std::unique_ptr<raw_pwrite_stream> &OS) {
assert(TimeTraceProfilerInstance != nullptr &&
"Profiler object can't be null");
TimeTraceProfilerInstance->Write(OS);
}
void timeTraceProfilerBegin(StringRef Name, StringRef Detail) {
if (TimeTraceProfilerInstance != nullptr)
TimeTraceProfilerInstance->begin(Name, [&]() { return Detail; });
}
void timeTraceProfilerBegin(StringRef Name,
llvm::function_ref<std::string()> Detail) {
if (TimeTraceProfilerInstance != nullptr)
TimeTraceProfilerInstance->begin(Name, Detail);
}
void timeTraceProfilerEnd() {
if (TimeTraceProfilerInstance != nullptr)
TimeTraceProfilerInstance->end();
}
} // namespace llvm
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* 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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// Base class for the calibration components using
// as input TPCseeds and ESDs
// Event loop outside of the component
//
//
// Base functionality to be implemeneted by component
/*
//In some cases only one of this function to be implemented
virtual void Process(AliESDEvent *event)
virtual void Process(AliTPCseed *track)
//
virtual Long64_t Merge(TCollection *li);
virtual void Analyze()
void Terminate();
*/
// Functionality provided by base class for Algorith debuging:
// TTreeSRedirector * cstream = GetDebugStreamer() - get debug streamer which can be use for numerical debugging
//
// [email protected]
//
#include "AliTPCcalibBase.h"
#include "TSystem.h"
#include "TFile.h"
#include "TTreeStream.h"
#include "TTimeStamp.h"
#include "TGraph.h"
#include "TGraphErrors.h"
#include "TF1.h"
#include "TH1D.h"
#include "TH2D.h"
#include "THnSparse.h"
#include "AliLog.h"
#include "AliESDEvent.h"
ClassImp(AliTPCcalibBase)
AliTPCcalibBase::AliTPCcalibBase():
TNamed(),
fDebugStreamer(0),
fStreamLevel(0),
fRun(0), //! current Run number
fEvent(0), //! current Event number
fTime(0), //! current Time
fTrigger(0), //! current trigger type
fMagF(0), //! current magnetic field
fTriggerMaskReject(-1), //trigger mask - reject trigger
fTriggerMaskAccept(-1), //trigger mask - accept trigger
fHasLaser(kFALSE), //flag the laser is overlayed with given event
fRejectLaser(kTRUE), //flag- reject laser
fTriggerClass(),
fDebugLevel(0)
{
//
// Constructor
//
}
AliTPCcalibBase::AliTPCcalibBase(const char * name, const char * title):
TNamed(name,title),
fDebugStreamer(0),
fStreamLevel(0),
fRun(0), //! current Run number
fEvent(0), //! current Event number
fTime(0), //! current Time
fTrigger(0), //! current trigger type
fMagF(0), //! current magnetic field
fTriggerMaskReject(-1), //trigger mask - reject trigger
fTriggerMaskAccept(-1), //trigger mask - accept trigger
fHasLaser(kFALSE), //flag the laser is overlayed with given event
fRejectLaser(kTRUE), //flag- reject laser
fTriggerClass(),
fDebugLevel(0)
{
//
// Constructor
//
}
AliTPCcalibBase::AliTPCcalibBase(const AliTPCcalibBase&calib):
TNamed(calib),
fDebugStreamer(0),
fStreamLevel(calib.fStreamLevel),
fRun(0), //! current Run number
fEvent(0), //! current Event number
fTime(0), //! current Time
fTrigger(0), //! current trigger type
fMagF(0), //! current magnetic field
fTriggerMaskReject(calib.fTriggerMaskReject), //trigger mask - reject trigger
fTriggerMaskAccept(calib.fTriggerMaskAccept), //trigger mask - accept trigger
fHasLaser(calib.fHasLaser), //flag the laser is overlayed with given event
fRejectLaser(calib.fRejectLaser), //flag- reject laser
fTriggerClass(calib.fTriggerClass),
fDebugLevel(calib.fDebugLevel)
{
//
// copy constructor
//
}
AliTPCcalibBase &AliTPCcalibBase::operator=(const AliTPCcalibBase&calib){
//
//
//
((TNamed *)this)->operator=(calib);
fDebugStreamer=0;
fStreamLevel=calib.fStreamLevel;
fDebugLevel=calib.fDebugLevel;
return *this;
}
AliTPCcalibBase::~AliTPCcalibBase() {
//
// destructor
//
if (fDebugLevel>0) printf("AliTPCcalibBase::~AliTPCcalibBase\n");
if (fDebugStreamer) delete fDebugStreamer;
fDebugStreamer=0;
}
void AliTPCcalibBase::Terminate(){
//
//
//
if (fDebugLevel>0) printf("AliTPCcalibBase::Terminate\n");
if (fDebugStreamer) delete fDebugStreamer;
fDebugStreamer = 0;
return;
}
TTreeSRedirector *AliTPCcalibBase::GetDebugStreamer(){
//
// Get Debug streamer
// In case debug streamer not yet initialized and StreamLevel>0 create new one
//
if (fStreamLevel==0) return 0;
if (fDebugStreamer) return fDebugStreamer;
TString dsName;
dsName=GetName();
dsName+="Debug.root";
dsName.ReplaceAll(" ","");
fDebugStreamer = new TTreeSRedirector(dsName.Data());
return fDebugStreamer;
}
void AliTPCcalibBase::UpdateEventInfo(AliESDEvent * event){
//
//
//
fRun = event->GetRunNumber();
fEvent = event->GetEventNumberInFile();
fTime = event->GetTimeStamp();
fTrigger = event->GetTriggerMask();
fMagF = event->GetMagneticField();
fTriggerClass = event->GetFiredTriggerClasses().Data();
fHasLaser = HasLaser(event);
}
Bool_t AliTPCcalibBase::HasLaser(AliESDEvent *event){
//
//
//
// Thresholds more than 8 tracks with small dip angle
const Int_t kMinLaserTracks = 8;
const Float_t kThrLaser = 0.3;
const Float_t kLaserTgl = 0.01;
Int_t ntracks = event->GetNumberOfTracks();
if (ntracks<kMinLaserTracks) return kFALSE;
Float_t nlaser=0;
Float_t nall=0;
for (Int_t i=0;i<ntracks;++i) {
AliESDtrack *track=event->GetTrack(i);
if (!track) continue;
if (track->GetTPCNcls()<=0) continue;
nall++;
if (TMath::Abs(track->GetTgl())<kLaserTgl) nlaser++;
}
if (nlaser>kMinLaserTracks) return kTRUE;
if (nall>0 && nlaser/nall>kThrLaser) return kTRUE;
return kFALSE;
}
Bool_t AliTPCcalibBase::AcceptTrigger(){
//
// Apply trigger mask - Don't do calibration for non proper triggers
//
if (fTriggerMaskReject==(Int_t)fTrigger) return kFALSE;
if (fTriggerMaskAccept>0 && fTriggerMaskAccept!=(Int_t)fTrigger) return kFALSE;
if (fHasLaser && fRejectLaser) return kFALSE;
return kTRUE;
}
void AliTPCcalibBase::RegisterDebugOutput(const char *path){
//
// store - copy debug output to the destination position
// currently ONLY for local copy
if (fDebugLevel>0) printf("AliTPCcalibBase::RegisterDebugOutput(%s)\n",path);
if (fStreamLevel==0) return;
TString dsName;
dsName=GetName();
dsName+="Debug.root";
dsName.ReplaceAll(" ","");
TString dsName2=path;
gSystem->MakeDirectory(dsName2.Data());
dsName2+=gSystem->HostName();
gSystem->MakeDirectory(dsName2.Data());
dsName2+="/";
TTimeStamp s;
dsName2+=Int_t(s.GetNanoSec());
dsName2+="/";
gSystem->MakeDirectory(dsName2.Data());
dsName2+=dsName;
AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
TFile::Cp(dsName.Data(),dsName2.Data());
}
TGraphErrors * AliTPCcalibBase::FitSlices(THnSparse *h, Int_t axisDim1, Int_t axisDim2, Int_t minEntries, Int_t nmaxBin, Float_t fracLow, Float_t fracUp){
//
// Fitting slices of the projection(axisDim1,axisDim2) of a sparse histogram
//
TH2D * hist = h->Projection(axisDim1, axisDim2);
Double_t *xvec = new Double_t[hist->GetNbinsX()];
Double_t *yvec = new Double_t[hist->GetNbinsX()];
Double_t *xerr = new Double_t[hist->GetNbinsX()];
Double_t *yerr = new Double_t[hist->GetNbinsX()];
Int_t counter = 0;
TH1D * projectionHist =0;
//
for(Int_t i=1; i < hist->GetNbinsX(); i++) {
Int_t nsum=0;
Int_t imin = i;
Int_t imax = i;
for (Int_t idelta=0; idelta<nmaxBin; idelta++){
//
imin = TMath::Max(i-idelta,1);
imax = TMath::Min(i+idelta,hist->GetNbinsX());
nsum = TMath::Nint(hist->Integral(imin,imax,0,hist->GetNbinsY()));
if (nsum==0) break;
if (nsum>minEntries) break;
}
if (nsum<minEntries) continue;
//
hist->GetXaxis()->SetRange(imin,imax);
projectionHist = hist->ProjectionY("gain",imin,imax);
// Determine Median:
Float_t xMin = projectionHist->GetXaxis()->GetXmin();
Float_t xMax = projectionHist->GetXaxis()->GetXmax();
Float_t xMedian = (xMin+xMax)*0.5;
Float_t integral = 0;
for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {
integral+=projectionHist->GetBinContent(jbin);
}
printf("Integral %f\t%f\n",integral, projectionHist->GetSum());
//
//
Float_t currentSum=0;
for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {
currentSum += projectionHist->GetBinContent(jbin);
if (currentSum<fracLow*integral) xMin = projectionHist->GetBinCenter(jbin);
if (currentSum<fracUp*integral) xMax = projectionHist->GetBinCenter(jbin+1);
if (currentSum<0.5*integral && projectionHist->GetBinContent(jbin)>0){
xMedian = (projectionHist->GetBinCenter(jbin)*projectionHist->GetBinContent(jbin)+
projectionHist->GetBinCenter(jbin+1)*projectionHist->GetBinContent(jbin+1))/
(projectionHist->GetBinContent(jbin)+projectionHist->GetBinContent(jbin+1));
}
}
//
Float_t rms = projectionHist->GetRMS();
// i += interval;
//
Double_t xcenter = hist->GetMean();
Double_t xrms = hist->GetRMS()+hist->GetXaxis()->GetBinWidth(1)/TMath::Sqrt(12.);
Double_t binWidth = projectionHist->GetXaxis()->GetBinWidth(1);
if (rms>0){
TF1 funcGaus("funcGaus","gaus");
// cut on +- 4 RMS
projectionHist->Fit(&funcGaus,"QN","",xMin, xMax);
//
xvec[counter] = xcenter;
yvec[counter] = funcGaus.GetParameter(1);
xerr[counter] = xrms;
yerr[counter] = funcGaus.GetParError(1);
counter++;
}else{
xvec[counter] = xcenter;
yvec[counter] = xMedian;
xerr[counter] = xrms;
yerr[counter] = binWidth/TMath::Sqrt(12.);
counter++;
}
delete projectionHist;
}
TGraphErrors * graphErrors = new TGraphErrors(counter, xvec, yvec, xerr, yerr);
delete [] xvec;
delete [] yvec;
delete [] xerr;
delete [] yerr;
delete hist;
return graphErrors;
}
<commit_msg>Removed printf (Marian)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* 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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// Base class for the calibration components using
// as input TPCseeds and ESDs
// Event loop outside of the component
//
//
// Base functionality to be implemeneted by component
/*
//In some cases only one of this function to be implemented
virtual void Process(AliESDEvent *event)
virtual void Process(AliTPCseed *track)
//
virtual Long64_t Merge(TCollection *li);
virtual void Analyze()
void Terminate();
*/
// Functionality provided by base class for Algorith debuging:
// TTreeSRedirector * cstream = GetDebugStreamer() - get debug streamer which can be use for numerical debugging
//
// [email protected]
//
#include "AliTPCcalibBase.h"
#include "TSystem.h"
#include "TFile.h"
#include "TTreeStream.h"
#include "TTimeStamp.h"
#include "TGraph.h"
#include "TGraphErrors.h"
#include "TF1.h"
#include "TH1D.h"
#include "TH2D.h"
#include "THnSparse.h"
#include "AliLog.h"
#include "AliESDEvent.h"
ClassImp(AliTPCcalibBase)
AliTPCcalibBase::AliTPCcalibBase():
TNamed(),
fDebugStreamer(0),
fStreamLevel(0),
fRun(0), //! current Run number
fEvent(0), //! current Event number
fTime(0), //! current Time
fTrigger(0), //! current trigger type
fMagF(0), //! current magnetic field
fTriggerMaskReject(-1), //trigger mask - reject trigger
fTriggerMaskAccept(-1), //trigger mask - accept trigger
fHasLaser(kFALSE), //flag the laser is overlayed with given event
fRejectLaser(kTRUE), //flag- reject laser
fTriggerClass(),
fDebugLevel(0)
{
//
// Constructor
//
}
AliTPCcalibBase::AliTPCcalibBase(const char * name, const char * title):
TNamed(name,title),
fDebugStreamer(0),
fStreamLevel(0),
fRun(0), //! current Run number
fEvent(0), //! current Event number
fTime(0), //! current Time
fTrigger(0), //! current trigger type
fMagF(0), //! current magnetic field
fTriggerMaskReject(-1), //trigger mask - reject trigger
fTriggerMaskAccept(-1), //trigger mask - accept trigger
fHasLaser(kFALSE), //flag the laser is overlayed with given event
fRejectLaser(kTRUE), //flag- reject laser
fTriggerClass(),
fDebugLevel(0)
{
//
// Constructor
//
}
AliTPCcalibBase::AliTPCcalibBase(const AliTPCcalibBase&calib):
TNamed(calib),
fDebugStreamer(0),
fStreamLevel(calib.fStreamLevel),
fRun(0), //! current Run number
fEvent(0), //! current Event number
fTime(0), //! current Time
fTrigger(0), //! current trigger type
fMagF(0), //! current magnetic field
fTriggerMaskReject(calib.fTriggerMaskReject), //trigger mask - reject trigger
fTriggerMaskAccept(calib.fTriggerMaskAccept), //trigger mask - accept trigger
fHasLaser(calib.fHasLaser), //flag the laser is overlayed with given event
fRejectLaser(calib.fRejectLaser), //flag- reject laser
fTriggerClass(calib.fTriggerClass),
fDebugLevel(calib.fDebugLevel)
{
//
// copy constructor
//
}
AliTPCcalibBase &AliTPCcalibBase::operator=(const AliTPCcalibBase&calib){
//
//
//
((TNamed *)this)->operator=(calib);
fDebugStreamer=0;
fStreamLevel=calib.fStreamLevel;
fDebugLevel=calib.fDebugLevel;
return *this;
}
AliTPCcalibBase::~AliTPCcalibBase() {
//
// destructor
//
if (fDebugLevel>0) printf("AliTPCcalibBase::~AliTPCcalibBase\n");
if (fDebugStreamer) delete fDebugStreamer;
fDebugStreamer=0;
}
void AliTPCcalibBase::Terminate(){
//
//
//
if (fDebugLevel>0) printf("AliTPCcalibBase::Terminate\n");
if (fDebugStreamer) delete fDebugStreamer;
fDebugStreamer = 0;
return;
}
TTreeSRedirector *AliTPCcalibBase::GetDebugStreamer(){
//
// Get Debug streamer
// In case debug streamer not yet initialized and StreamLevel>0 create new one
//
if (fStreamLevel==0) return 0;
if (fDebugStreamer) return fDebugStreamer;
TString dsName;
dsName=GetName();
dsName+="Debug.root";
dsName.ReplaceAll(" ","");
fDebugStreamer = new TTreeSRedirector(dsName.Data());
return fDebugStreamer;
}
void AliTPCcalibBase::UpdateEventInfo(AliESDEvent * event){
//
//
//
fRun = event->GetRunNumber();
fEvent = event->GetEventNumberInFile();
fTime = event->GetTimeStamp();
fTrigger = event->GetTriggerMask();
fMagF = event->GetMagneticField();
fTriggerClass = event->GetFiredTriggerClasses().Data();
fHasLaser = HasLaser(event);
}
Bool_t AliTPCcalibBase::HasLaser(AliESDEvent *event){
//
//
//
// Thresholds more than 8 tracks with small dip angle
const Int_t kMinLaserTracks = 8;
const Float_t kThrLaser = 0.3;
const Float_t kLaserTgl = 0.01;
Int_t ntracks = event->GetNumberOfTracks();
if (ntracks<kMinLaserTracks) return kFALSE;
Float_t nlaser=0;
Float_t nall=0;
for (Int_t i=0;i<ntracks;++i) {
AliESDtrack *track=event->GetTrack(i);
if (!track) continue;
if (track->GetTPCNcls()<=0) continue;
nall++;
if (TMath::Abs(track->GetTgl())<kLaserTgl) nlaser++;
}
if (nlaser>kMinLaserTracks) return kTRUE;
if (nall>0 && nlaser/nall>kThrLaser) return kTRUE;
return kFALSE;
}
Bool_t AliTPCcalibBase::AcceptTrigger(){
//
// Apply trigger mask - Don't do calibration for non proper triggers
//
if (fTriggerMaskReject==(Int_t)fTrigger) return kFALSE;
if (fTriggerMaskAccept>0 && fTriggerMaskAccept!=(Int_t)fTrigger) return kFALSE;
if (fHasLaser && fRejectLaser) return kFALSE;
return kTRUE;
}
void AliTPCcalibBase::RegisterDebugOutput(const char *path){
//
// store - copy debug output to the destination position
// currently ONLY for local copy
if (fDebugLevel>0) printf("AliTPCcalibBase::RegisterDebugOutput(%s)\n",path);
if (fStreamLevel==0) return;
TString dsName;
dsName=GetName();
dsName+="Debug.root";
dsName.ReplaceAll(" ","");
TString dsName2=path;
gSystem->MakeDirectory(dsName2.Data());
dsName2+=gSystem->HostName();
gSystem->MakeDirectory(dsName2.Data());
dsName2+="/";
TTimeStamp s;
dsName2+=Int_t(s.GetNanoSec());
dsName2+="/";
gSystem->MakeDirectory(dsName2.Data());
dsName2+=dsName;
AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
TFile::Cp(dsName.Data(),dsName2.Data());
}
TGraphErrors * AliTPCcalibBase::FitSlices(THnSparse *h, Int_t axisDim1, Int_t axisDim2, Int_t minEntries, Int_t nmaxBin, Float_t fracLow, Float_t fracUp){
//
// Fitting slices of the projection(axisDim1,axisDim2) of a sparse histogram
//
TH2D * hist = h->Projection(axisDim1, axisDim2);
Double_t *xvec = new Double_t[hist->GetNbinsX()];
Double_t *yvec = new Double_t[hist->GetNbinsX()];
Double_t *xerr = new Double_t[hist->GetNbinsX()];
Double_t *yerr = new Double_t[hist->GetNbinsX()];
Int_t counter = 0;
TH1D * projectionHist =0;
//
for(Int_t i=1; i < hist->GetNbinsX(); i++) {
Int_t nsum=0;
Int_t imin = i;
Int_t imax = i;
for (Int_t idelta=0; idelta<nmaxBin; idelta++){
//
imin = TMath::Max(i-idelta,1);
imax = TMath::Min(i+idelta,hist->GetNbinsX());
nsum = TMath::Nint(hist->Integral(imin,imax,0,hist->GetNbinsY()));
if (nsum==0) break;
if (nsum>minEntries) break;
}
if (nsum<minEntries) continue;
//
hist->GetXaxis()->SetRange(imin,imax);
projectionHist = hist->ProjectionY("gain",imin,imax);
// Determine Median:
Float_t xMin = projectionHist->GetXaxis()->GetXmin();
Float_t xMax = projectionHist->GetXaxis()->GetXmax();
Float_t xMedian = (xMin+xMax)*0.5;
Float_t integral = 0;
for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {
integral+=projectionHist->GetBinContent(jbin);
}
//printf("Integral %f\t%f\n",integral, projectionHist->GetSum());
//
//
Float_t currentSum=0;
for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {
currentSum += projectionHist->GetBinContent(jbin);
if (currentSum<fracLow*integral) xMin = projectionHist->GetBinCenter(jbin);
if (currentSum<fracUp*integral) xMax = projectionHist->GetBinCenter(jbin+1);
if (currentSum<0.5*integral && projectionHist->GetBinContent(jbin)>0){
xMedian = (projectionHist->GetBinCenter(jbin)*projectionHist->GetBinContent(jbin)+
projectionHist->GetBinCenter(jbin+1)*projectionHist->GetBinContent(jbin+1))/
(projectionHist->GetBinContent(jbin)+projectionHist->GetBinContent(jbin+1));
}
}
//
Float_t rms = projectionHist->GetRMS();
// i += interval;
//
Double_t xcenter = hist->GetMean();
Double_t xrms = hist->GetRMS()+hist->GetXaxis()->GetBinWidth(1)/TMath::Sqrt(12.);
Double_t binWidth = projectionHist->GetXaxis()->GetBinWidth(1);
if (rms>0){
TF1 funcGaus("funcGaus","gaus");
// cut on +- 4 RMS
projectionHist->Fit(&funcGaus,"QN","",xMin, xMax);
//
xvec[counter] = xcenter;
yvec[counter] = funcGaus.GetParameter(1);
xerr[counter] = xrms;
yerr[counter] = funcGaus.GetParError(1);
counter++;
}else{
xvec[counter] = xcenter;
yvec[counter] = xMedian;
xerr[counter] = xrms;
yerr[counter] = binWidth/TMath::Sqrt(12.);
counter++;
}
delete projectionHist;
}
TGraphErrors * graphErrors = new TGraphErrors(counter, xvec, yvec, xerr, yerr);
delete [] xvec;
delete [] yvec;
delete [] xerr;
delete [] yerr;
delete hist;
return graphErrors;
}
<|endoftext|> |
<commit_before>// Used for testing, do not use it as an example
#include <iostream>
#include "qpp.h"
int main() {
/////////// testing ///////////
using namespace qpp;
QCircuit qc{4, 4};
qc.QFT();
qc.measureZ(0, 0);
qc.measureZ(1, 1);
std::cout << qc << std::endl << std::endl;
QEngine q_engine{qc};
std::cout << q_engine << std::endl;
std::cout << qc.get_gate_depth("CTRL-R2") << std::endl;
std::cout << qc.get_gate_depth() << std::endl;
std::cout << qc.get_gate_count("H") << std::endl;
}
<commit_msg>Update _test.cpp<commit_after>// Used for testing, do not use it as an example
#include <iostream>
#include "qpp.h"
int main() {
/////////// testing ///////////
using namespace qpp;
QCircuit qc{4, 4};
qc.measureV(gt.H, 3, 3);
qc.QFT();
qc.measureZ(0, 0);
qc.measureZ(1, 1);
std::cout << qc << std::endl << std::endl;
QEngine q_engine{qc};
std::cout << q_engine << std::endl;
std::cout << qc.get_gate_depth("CTRL-R2") << std::endl;
std::cout << qc.get_gate_depth() << std::endl;
std::cout << qc.get_gate_count("H") << std::endl;
std::cout << qc.get_gate_depth("H") << std::endl;
}
<|endoftext|> |
<commit_before>#include <uv.h>
#include "sds.h"
#include "sds_responder.hpp"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
extern char* current_time;
void create_plaintext_response_sds(write_batch* batch) {
sds response_buffer = sdsnew("HTTP/1.1 200 OK\r\n");
response_buffer = sdscat(response_buffer, "Server: octane\r\n");
response_buffer = sdscat(response_buffer, "Content-Type: text/plain\r\n");
response_buffer = sdscat(response_buffer, "Content-Length: 14\r\n");
response_buffer = sdscatprintf(response_buffer, "Date: %s\r\n", current_time);
response_buffer = sdscat(response_buffer, "Hello, World!\n");
batch->buffers[batch->number_of_used_buffers].base = response_buffer;
batch->buffers[batch->number_of_used_buffers].len = sdslen(response_buffer);
batch->number_of_used_buffers++;
}
void create_json_response_sds(write_batch* batch) {
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.Key("message");
writer.String("Hello, World!");
writer.EndObject();
sds response_buffer = sdsnew("HTTP/1.1 200 OK\r\n");
response_buffer = sdscat(response_buffer, "Server: octane\r\n");
response_buffer = sdscat(response_buffer, "Content-Type: application/json\r\n");
response_buffer = sdscat(response_buffer, "Content-Length: 28\r\n");
response_buffer = sdscatprintf(response_buffer, "Date: %s\r\n", current_time);
response_buffer = sdscat(response_buffer, s.GetString());
response_buffer = sdscat(response_buffer, "\n");
batch->buffers[batch->number_of_used_buffers].base = response_buffer;
batch->buffers[batch->number_of_used_buffers].len = sdslen(response_buffer);
batch->number_of_used_buffers++;
}<commit_msg>Fixed content length.<commit_after>#include <uv.h>
#include "sds.h"
#include "sds_responder.hpp"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
extern char* current_time;
void create_plaintext_response_sds(write_batch* batch) {
sds response_buffer = sdsnew("HTTP/1.1 200 OK\r\n");
response_buffer = sdscat(response_buffer, "Server: octane\r\n");
response_buffer = sdscat(response_buffer, "Content-Type: text/plain\r\n");
response_buffer = sdscat(response_buffer, "Content-Length: 13\r\n");
response_buffer = sdscatprintf(response_buffer, "Date: %s\r\n", current_time);
response_buffer = sdscat(response_buffer, "Hello, World!");
batch->buffers[batch->number_of_used_buffers].base = response_buffer;
batch->buffers[batch->number_of_used_buffers].len = sdslen(response_buffer);
batch->number_of_used_buffers++;
}
void create_json_response_sds(write_batch* batch) {
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.Key("message");
writer.String("Hello, World!");
writer.EndObject();
sds response_buffer = sdsnew("HTTP/1.1 200 OK\r\n");
response_buffer = sdscat(response_buffer, "Server: octane\r\n");
response_buffer = sdscat(response_buffer, "Content-Type: application/json\r\n");
response_buffer = sdscat(response_buffer, "Content-Length: 27\r\n");
response_buffer = sdscatprintf(response_buffer, "Date: %s\r\n", current_time);
response_buffer = sdscat(response_buffer, s.GetString());
batch->buffers[batch->number_of_used_buffers].base = response_buffer;
batch->buffers[batch->number_of_used_buffers].len = sdslen(response_buffer);
batch->number_of_used_buffers++;
}
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik 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 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 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.
*/
//$Id: pool.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef POOL_HPP
#define POOL_HPP
#include <iostream>
#include <map>
#include <deque>
#include <ctime>
#include "utils.hpp"
#include <boost/shared_ptr.hpp>
namespace mapnik
{
template <typename T, typename PoolT>
class PoolGuard
{
private:
const T& obj_;
PoolT& pool_;
public:
explicit PoolGuard(const T& ptr,PoolT& pool)
: obj_(ptr),
pool_(pool) {}
~PoolGuard()
{
pool_->returnObject(obj_);
}
private:
PoolGuard();
PoolGuard(const PoolGuard&);
PoolGuard& operator=(const PoolGuard&);
};
template <typename T,template <typename> class Creator>
class Pool
{
typedef boost::shared_ptr<T> HolderType;
typedef std::deque<HolderType> ContType;
Creator<T> creator_;
const int initialSize_;
const int maxSize_;
ContType usedPool_;
ContType unusedPool_;
Mutex mutex_;
public:
Pool(const Creator<T>& creator,int initialSize=5,int maxSize=20)
:creator_(creator),
initialSize_(initialSize),
maxSize_(maxSize)
{
for (int i=0;i<initialSize_;++i)
{
unusedPool_.push_back(HolderType(creator_()));
}
}
const HolderType& borrowObject()
{
Lock lock(&mutex_);
typename ContType::iterator itr=unusedPool_.begin();
if (itr!=unusedPool_.end())
{
std::cout<<"borrow "<<(*itr).get()<<"\n";
usedPool_.push_back(*itr);
itr=unusedPool_.erase(itr);
mutex_.unlock();
return usedPool_[usedPool_.size()-1];
}
static const HolderType defaultObj;
return defaultObj;
}
void returnObject(const HolderType& obj)
{
Lock lock(&mutex_);
typename ContType::iterator itr=usedPool_.begin();
while (itr != usedPool_.end())
{
if (obj.get()==(*itr).get())
{
std::cout<<"return "<<(*itr).get()<<"\n";
unusedPool_.push_back(*itr);
usedPool_.erase(itr);
return;
}
++itr;
}
}
private:
Pool(const Pool&);
Pool& operator=(const Pool&);
};
}
#endif //POOL_HPP
<commit_msg>1. use boost::noncopyable 2. use boost::thread::mutex<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik 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 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 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.
*/
//$Id: pool.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef POOL_HPP
#define POOL_HPP
#include <iostream>
#include <map>
#include <deque>
#include <ctime>
#include "utils.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/utility.hpp>
namespace mapnik
{
template <typename T, typename PoolT>
class PoolGuard
{
private:
const T& obj_;
PoolT& pool_;
public:
explicit PoolGuard(const T& ptr,PoolT& pool)
: obj_(ptr),
pool_(pool) {}
~PoolGuard()
{
pool_->returnObject(obj_);
}
private:
PoolGuard();
PoolGuard(const PoolGuard&);
PoolGuard& operator=(const PoolGuard&);
};
template <typename T,template <typename> class Creator>
class Pool : private boost::noncopyable
{
typedef boost::shared_ptr<T> HolderType;
typedef std::deque<HolderType> ContType;
Creator<T> creator_;
const int initialSize_;
const int maxSize_;
ContType usedPool_;
ContType unusedPool_;
boost::mutex mutex_;
public:
Pool(const Creator<T>& creator,int initialSize=5,int maxSize=20)
:creator_(creator),
initialSize_(initialSize),
maxSize_(maxSize)
{
for (int i=0;i<initialSize_;++i)
{
unusedPool_.push_back(HolderType(creator_()));
}
}
const HolderType& borrowObject()
{
mutex::scoped_lock lock(mutex_);
typename ContType::iterator itr=unusedPool_.begin();
if (itr!=unusedPool_.end())
{
std::cout<<"borrow "<<(*itr).get()<<"\n";
usedPool_.push_back(*itr);
itr=unusedPool_.erase(itr);
return usedPool_[usedPool_.size()-1];
}
static const HolderType defaultObj;
return defaultObj;
}
void returnObject(const HolderType& obj)
{
mutex::scoped_lock lock(mutex_);
typename ContType::iterator itr=usedPool_.begin();
while (itr != usedPool_.end())
{
if (obj.get()==(*itr).get())
{
std::cout<<"return "<<(*itr).get()<<"\n";
unusedPool_.push_back(*itr);
usedPool_.erase(itr);
return;
}
++itr;
}
}
};
}
#endif //POOL_HPP
<|endoftext|> |
<commit_before>/*
* despot1_main.cpp
*
* Created by Tobias Wood on 27/01/2015.
* Copyright (c) 2015 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 <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include <Eigen/Dense>
#include "Nifti/Nifti.h"
#include "QUIT/QUIT.h"
#include "DESPOT.h"
#include "DESPOT_Functors.h"
#include "unsupported/Eigen/NonLinearOptimization"
#include "unsupported/Eigen/NumericalDiff"
using namespace std;
using namespace Eigen;
using namespace QUIT;
class T2starFunctor : public Functor<double> {
protected:
const ArrayXd &m_echotimes;
const ArrayXd &m_data;
public:
const long inputs() const override { return 2; }
const long values() const override { return m_data.rows(); }
T2starFunctor(const ArrayXd &echos, const ArrayXd &data) : m_echotimes(echos), m_data(data) {};
int operator()(const Ref<VectorXd> ¶ms, Ref<ArrayXd> diffs) const override {
double T2star = params[0];
double PD = params[1];
diffs = m_data - PD * (-m_echotimes / T2star).exp();
return 0;
};
};
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: t2star [options] input_file \n\
\
Options:\n\
--help, -h : Print this message\n\
--verbose, -v : Print more information\n\
--no-prompt, -n : Suppress input prompts\n\
--out, -o path : Add a prefix to the output filenames\n\
--mask, -m file : Mask input with specified file\n\
--thresh, -t n : Threshold maps at PD < n\n\
--clamp, -c n : Clamp T2* between 0 and n\n\
--resids, -r : Write out per flip-angle residuals\n\
--threads, -T N : Use N threads (default=hardware limit)\n"
};
static bool verbose = false, prompt = true, all_residuals = false;
static string outPrefix;
static double thresh = -numeric_limits<double>::infinity();
static double clamp_lo = -numeric_limits<double>::infinity(), clamp_hi = numeric_limits<double>::infinity();
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"no-prompt", no_argument, 0, 'n'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"thresh", required_argument, 0, 't'},
{"clamp", required_argument, 0, 'c'},
{"threads", required_argument, 0, 'T'},
{"resids", no_argument, 0, 'r'},
{0, 0, 0, 0}
};
static const char *short_opts = "hvnm:o:b:t:c:T:r";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
try { // To fix uncaught exceptions on Mac
cout << version << endl << credit_shared << endl;
Eigen::initParallel();
Nifti::File inputFile, maskFile;
MultiArray<int8_t, 3> maskVol;
ThreadPool threads;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_opts, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'n': prompt = false; break;
case 'm':
cout << "Reading mask file " << optarg << endl;
maskFile.open(optarg, Nifti::Mode::Read);
maskVol.resize(maskFile.matrix());
maskFile.readVolumes(maskVol.begin(), maskVol.end(), 0, 1);
break;
case 'o':
outPrefix = optarg;
cout << "Output prefix will be: " << outPrefix << endl;
break;
case 't': thresh = atof(optarg); break;
case 'c':
clamp_lo = 0;
clamp_hi = atof(optarg);
break;
case 'T':
threads.resize(atoi(optarg));
break;
case 'r': all_residuals = true; break;
case 'h':
case '?': // getopt will print an error message
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
// Gather input data
cout << "Opening input file: " << argv[optind] << endl;
inputFile.open(argv[optind], Nifti::Mode::Read);
checkHeaders(inputFile.header(), {maskFile});
Agilent::ProcPar pp; ReadPP(inputFile, pp);
double TE1, ESP;
if (pp) {
TE1 = pp.realValue("te");
ESP = pp.realValue("te2");
} else {
if (prompt) cout << "Enter first echo-time: " << flush;
QUIT::Read<double>::FromLine(cin, TE1);
if (prompt) cout << "Enter echo spacing: " << flush;
QUIT::Read<double>::FromLine(cin, ESP);
}
// Set up echo times array
MatrixXd X(inputFile.dim(4), 2);
X(0, 0) = TE1;
for (int i = 1; i < X.rows(); i++) {
X(i, 0) = X(i-1, 0) + ESP;
}
X.col(1).setOnes();
if (verbose) {
cout << "Ouput prefix will be: " << outPrefix << endl;
cout << "Echo times are: " << X.col(0).transpose() << endl;
cout << "Clamp: " << clamp_lo << " " << clamp_hi << endl;
cout << "Thresh: " << thresh << endl;
}
cout << "Reading input data..." << flush;
MultiArray<complex<float>, 4> inputVols(inputFile.dims().head(4));
inputFile.readVolumes(inputVols.begin(), inputVols.end());
cout << "done." << endl;
//**************************************************************************
// Do the fitting
//**************************************************************************
const auto dims = inputFile.matrix();
MultiArray<float, 3> T2starVol(dims), PDVol(dims), ResVol(dims);
MultiArray<float, 4> ResidsVols;
if (all_residuals) {
ResidsVols = MultiArray<float, 4>(dims, inputFile.dim(4));
}
for (size_t k = 0; k < dims[2]; k++) {
clock_t loopStart;
if (verbose) cout << "Starting slice " << k << "..." << flush;
loopStart = clock();
atomic<int> voxCount{0};
function<void (const size_t, const size_t)> process = [&] (const size_t i, const size_t j) {
const MultiArray<float, 3>::Index idx{i,j,k};
if (!maskFile || (maskVol[idx])) {
voxCount++;
double T2star, PD;
ArrayXd signal = inputVols.slice<1>({i,j,k,0},{0,0,0,-1}).asArray().abs().cast<double>();
VectorXd Y = signal.log();
VectorXd b = (X.transpose() * X).partialPivLu().solve(X.transpose() * Y);
T2star = -1 / b[0];
PD = exp(b[1]);
/*T2starFunctor f(X.col(0).array(), signal);
NumericalDiff<T2starFunctor> nDiff(f);
LevenbergMarquardt<NumericalDiff<T2starFunctor>> lm(nDiff);
lm.parameters.maxfev = 20;
VectorXd p(2);
p << T2star, PD;
lm.lmder1(p);
T2star = p(0); PD = p(1);
if (PD < thresh) {
PD = 0.;
T2star = 0.;
}*/
T2star = clamp(T2star, clamp_lo, clamp_hi);
ArrayXd theory = PD * (-X.col(0).array() / T2star).exp();
ArrayXd resids = (signal - theory);
if (all_residuals) {
ResidsVols.slice<1>({i,j,k,0},{0,0,0,-1}).asArray() = resids.cast<float>();
}
T2starVol[idx] = static_cast<float>(T2star);
PDVol[idx] = static_cast<float>(PD);
ResVol[idx] = static_cast<float>(sqrt(resids.square().sum() / resids.rows()) / PD);
}
};
threads.for_loop2(process, dims[0], dims[1]);
if (verbose) {
clock_t loopEnd = clock();
if (voxCount > 0)
cout << voxCount << " unmasked voxels, CPU time per voxel was "
<< ((loopEnd - loopStart) / ((float)voxCount * CLOCKS_PER_SEC)) << " s, ";
cout << "finished." << endl;
}
}
if (verbose)
cout << "Writing results." << endl;
outPrefix = outPrefix + "ME_";
Nifti::Header outHdr = inputFile.header();
outHdr.description = version;
outHdr.setDim(4, 1);
outHdr.setDatatype(Nifti::DataType::FLOAT32);
outHdr.intent = Nifti::Intent::Estimate;
outHdr.intent_name = "T2* (seconds)";
Nifti::File outFile(outHdr, outPrefix + "T2star" + OutExt());
outFile.writeVolumes(T2starVol.begin(), T2starVol.end());
outFile.close();
outHdr.intent_name = "PD (au)";
outFile.setHeader(outHdr);
outFile.open(outPrefix + "PD" + OutExt(), Nifti::Mode::Write);
outFile.writeVolumes(PDVol.begin(), PDVol.end());
outFile.close();
outHdr.intent_name = "Fractional Residual";
outFile.setHeader(outHdr);
outFile.open(outPrefix + "residual" + OutExt(), Nifti::Mode::Write);
outFile.writeVolumes(ResVol.begin(), ResVol.end());
outFile.close();
if (all_residuals) {
outHdr.intent_name = "Residuals";
outHdr.setDim(4, inputFile.dim(4));
outFile.setHeader(outHdr);
outFile.open(outPrefix + "residuals" + OutExt(), Nifti::Mode::Write);
outFile.writeVolumes(ResidsVols.begin(), ResidsVols.end(), 0, inputFile.dim(4));
outFile.close();
}
cout << "All done." << endl;
} catch (exception &e) {
cerr << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Fixed missing threshold code.<commit_after>/*
* despot1_main.cpp
*
* Created by Tobias Wood on 27/01/2015.
* Copyright (c) 2015 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 <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include <Eigen/Dense>
#include "Nifti/Nifti.h"
#include "QUIT/QUIT.h"
#include "DESPOT.h"
#include "DESPOT_Functors.h"
#include "unsupported/Eigen/NonLinearOptimization"
#include "unsupported/Eigen/NumericalDiff"
using namespace std;
using namespace Eigen;
using namespace QUIT;
class T2starFunctor : public Functor<double> {
protected:
const ArrayXd &m_echotimes;
const ArrayXd &m_data;
public:
const long inputs() const override { return 2; }
const long values() const override { return m_data.rows(); }
T2starFunctor(const ArrayXd &echos, const ArrayXd &data) : m_echotimes(echos), m_data(data) {};
int operator()(const Ref<VectorXd> ¶ms, Ref<ArrayXd> diffs) const override {
double T2star = params[0];
double PD = params[1];
diffs = m_data - PD * (-m_echotimes / T2star).exp();
return 0;
};
};
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: t2star [options] input_file \n\
\
Options:\n\
--help, -h : Print this message\n\
--verbose, -v : Print more information\n\
--no-prompt, -n : Suppress input prompts\n\
--out, -o path : Add a prefix to the output filenames\n\
--mask, -m file : Mask input with specified file\n\
--thresh, -t n : Threshold maps at PD < n\n\
--clamp, -c n : Clamp T2* between 0 and n\n\
--resids, -r : Write out per flip-angle residuals\n\
--threads, -T N : Use N threads (default=hardware limit)\n"
};
static bool verbose = false, prompt = true, all_residuals = false;
static string outPrefix;
static double thresh = -numeric_limits<double>::infinity();
static double clamp_lo = -numeric_limits<double>::infinity(), clamp_hi = numeric_limits<double>::infinity();
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"no-prompt", no_argument, 0, 'n'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"thresh", required_argument, 0, 't'},
{"clamp", required_argument, 0, 'c'},
{"threads", required_argument, 0, 'T'},
{"resids", no_argument, 0, 'r'},
{0, 0, 0, 0}
};
static const char *short_opts = "hvnm:o:b:t:c:T:r";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
try { // To fix uncaught exceptions on Mac
cout << version << endl << credit_shared << endl;
Eigen::initParallel();
Nifti::File inputFile, maskFile;
MultiArray<int8_t, 3> maskVol;
ThreadPool threads;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_opts, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'n': prompt = false; break;
case 'm':
cout << "Reading mask file " << optarg << endl;
maskFile.open(optarg, Nifti::Mode::Read);
maskVol.resize(maskFile.matrix());
maskFile.readVolumes(maskVol.begin(), maskVol.end(), 0, 1);
break;
case 'o':
outPrefix = optarg;
cout << "Output prefix will be: " << outPrefix << endl;
break;
case 't': thresh = atof(optarg); break;
case 'c':
clamp_lo = 0;
clamp_hi = atof(optarg);
break;
case 'T':
threads.resize(atoi(optarg));
break;
case 'r': all_residuals = true; break;
case 'h':
case '?': // getopt will print an error message
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
// Gather input data
cout << "Opening input file: " << argv[optind] << endl;
inputFile.open(argv[optind], Nifti::Mode::Read);
checkHeaders(inputFile.header(), {maskFile});
Agilent::ProcPar pp; ReadPP(inputFile, pp);
double TE1, ESP;
if (pp) {
TE1 = pp.realValue("te");
ESP = pp.realValue("te2");
} else {
if (prompt) cout << "Enter first echo-time: " << flush;
QUIT::Read<double>::FromLine(cin, TE1);
if (prompt) cout << "Enter echo spacing: " << flush;
QUIT::Read<double>::FromLine(cin, ESP);
}
// Set up echo times array
MatrixXd X(inputFile.dim(4), 2);
X(0, 0) = TE1;
for (int i = 1; i < X.rows(); i++) {
X(i, 0) = X(i-1, 0) + ESP;
}
X.col(1).setOnes();
if (verbose) {
cout << "Ouput prefix will be: " << outPrefix << endl;
cout << "Echo times are: " << X.col(0).transpose() << endl;
cout << "Clamp: " << clamp_lo << " " << clamp_hi << endl;
cout << "Thresh: " << thresh << endl;
}
cout << "Reading input data..." << flush;
MultiArray<complex<float>, 4> inputVols(inputFile.dims().head(4));
inputFile.readVolumes(inputVols.begin(), inputVols.end());
cout << "done." << endl;
//**************************************************************************
// Do the fitting
//**************************************************************************
const auto dims = inputFile.matrix();
MultiArray<float, 3> T2starVol(dims), PDVol(dims), ResVol(dims);
MultiArray<float, 4> ResidsVols;
if (all_residuals) {
ResidsVols = MultiArray<float, 4>(dims, inputFile.dim(4));
}
for (size_t k = 0; k < dims[2]; k++) {
clock_t loopStart;
if (verbose) cout << "Starting slice " << k << "..." << flush;
loopStart = clock();
atomic<int> voxCount{0};
function<void (const size_t, const size_t)> process = [&] (const size_t i, const size_t j) {
const MultiArray<float, 3>::Index idx{i,j,k};
if (!maskFile || (maskVol[idx])) {
voxCount++;
double T2star, PD;
ArrayXd signal = inputVols.slice<1>({i,j,k,0},{0,0,0,-1}).asArray().abs().cast<double>();
VectorXd Y = signal.log();
VectorXd b = (X.transpose() * X).partialPivLu().solve(X.transpose() * Y);
T2star = -1 / b[0];
PD = exp(b[1]);
/*T2starFunctor f(X.col(0).array(), signal);
NumericalDiff<T2starFunctor> nDiff(f);
LevenbergMarquardt<NumericalDiff<T2starFunctor>> lm(nDiff);
lm.parameters.maxfev = 20;
VectorXd p(2);
p << T2star, PD;
lm.lmder1(p);
T2star = p(0); PD = p(1);
if (PD < thresh) {
PD = 0.;
T2star = 0.;
}*/
if (PD < thresh) {
PD = 0.;
T2star = 0.;
}
T2star = clamp(T2star, clamp_lo, clamp_hi);
ArrayXd theory = PD * (-X.col(0).array() / T2star).exp();
ArrayXd resids = (signal - theory);
if (all_residuals) {
ResidsVols.slice<1>({i,j,k,0},{0,0,0,-1}).asArray() = resids.cast<float>();
}
T2starVol[idx] = static_cast<float>(T2star);
PDVol[idx] = static_cast<float>(PD);
ResVol[idx] = static_cast<float>(sqrt(resids.square().sum() / resids.rows()) / PD);
}
};
threads.for_loop2(process, dims[0], dims[1]);
if (verbose) {
clock_t loopEnd = clock();
if (voxCount > 0)
cout << voxCount << " unmasked voxels, CPU time per voxel was "
<< ((loopEnd - loopStart) / ((float)voxCount * CLOCKS_PER_SEC)) << " s, ";
cout << "finished." << endl;
}
}
if (verbose)
cout << "Writing results." << endl;
outPrefix = outPrefix + "ME_";
Nifti::Header outHdr = inputFile.header();
outHdr.description = version;
outHdr.setDim(4, 1);
outHdr.setDatatype(Nifti::DataType::FLOAT32);
outHdr.intent = Nifti::Intent::Estimate;
outHdr.intent_name = "T2* (seconds)";
Nifti::File outFile(outHdr, outPrefix + "T2star" + OutExt());
outFile.writeVolumes(T2starVol.begin(), T2starVol.end());
outFile.close();
outHdr.intent_name = "PD (au)";
outFile.setHeader(outHdr);
outFile.open(outPrefix + "PD" + OutExt(), Nifti::Mode::Write);
outFile.writeVolumes(PDVol.begin(), PDVol.end());
outFile.close();
outHdr.intent_name = "Fractional Residual";
outFile.setHeader(outHdr);
outFile.open(outPrefix + "residual" + OutExt(), Nifti::Mode::Write);
outFile.writeVolumes(ResVol.begin(), ResVol.end());
outFile.close();
if (all_residuals) {
outHdr.intent_name = "Residuals";
outHdr.setDim(4, inputFile.dim(4));
outFile.setHeader(outHdr);
outFile.open(outPrefix + "residuals" + OutExt(), Nifti::Mode::Write);
outFile.writeVolumes(ResidsVols.begin(), ResidsVols.end(), 0, inputFile.dim(4));
outFile.close();
}
cout << "All done." << endl;
} catch (exception &e) {
cerr << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2009-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : [email protected]
//
// Author: André RIBES - EDF R&D
//
#include "Launcher_Job_SALOME.hxx"
#include "Basics_DirUtils.hxx"
#ifdef WITH_LIBBATCH
#include <libbatch/Constants.hxx>
#endif
#ifdef WNT
#include <io.h>
#define _chmod chmod
#endif
Launcher::Job_SALOME::Job_SALOME() {}
Launcher::Job_SALOME::~Job_SALOME() {}
void
Launcher::Job_SALOME::setResourceDefinition(const ParserResourcesType & resource_definition)
{
// Check resource_definition
if (resource_definition.AppliPath == "")
{
std::string mess = "Resource definition must define an application path !, resource name is: " + resource_definition.Name;
throw LauncherException(mess);
}
Launcher::Job::setResourceDefinition(resource_definition);
}
void
Launcher::Job_SALOME::update_job()
{
#ifdef WITH_LIBBATCH
Batch::Parametre params = common_job_params();
params[Batch::EXECUTABLE] = buildSalomeScript(params);
params[Batch::EXCLUSIVE] = true;
_batch_job->setParametre(params);
#endif
}
#ifdef WITH_LIBBATCH
std::string
Launcher::Job_SALOME::buildSalomeScript(Batch::Parametre params)
{
// parameters
std::string work_directory = params[Batch::WORKDIR].str();
std::string launch_script = Kernel_Utils::GetTmpDir() + "runSalome_" + _job_file_name + "_" + _launch_date + ".sh";
std::ofstream launch_script_stream;
launch_script_stream.open(launch_script.c_str(),
std::ofstream::out
#ifdef WIN32
| std::ofstream::binary //rnv: to avoid CL+RF end of line on windows
#endif
);
// Begin of script
launch_script_stream << "#!/bin/sh -f" << std::endl;
launch_script_stream << "cd " << work_directory << std::endl;
launch_script_stream << "export PYTHONPATH=" << work_directory << ":$PYTHONPATH" << std::endl;
launch_script_stream << "export PATH=" << work_directory << ":$PATH" << std::endl;
if (_env_file != "")
{
std::string::size_type last = _env_file.find_last_of("/");
launch_script_stream << ". " << _env_file.substr(last+1) << std::endl;
}
launch_script_stream << "export SALOME_TMP_DIR=" << work_directory << "/logs" << std::endl;
// -- Generates Catalog Resources
std::string resource_protocol = _resource_definition.getClusterInternalProtocolStr();
launch_script_stream << "if [ \"x$LIBBATCH_NODEFILE\" != \"x\" ]; then " << std::endl;
launch_script_stream << "CATALOG_FILE=" << "CatalogResources_" << _launch_date << ".xml" << std::endl;
launch_script_stream << "export USER_CATALOG_RESOURCES_FILE=" << "$CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<!DOCTYPE ResourcesCatalog>' > $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "cat $LIBBATCH_NODEFILE | sort | uniq -c | while read nbproc host" << std::endl;
launch_script_stream << "do" << std::endl;
// Full name doesn't work. eg: sagittaire-7 instead of sagittaire-7.lyon.grid5000.fr
launch_script_stream << "host_basename=$(echo $host | cut -f1 -d.)" << std::endl;
launch_script_stream << "echo '<machine hostname='\\\"$host_basename\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' protocol=\"" << resource_protocol << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' userName=\"" << _resource_definition.UserName << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' appliPath=\"" << _resource_definition.AppliPath << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' mpi=\"" << _resource_definition.getMpiImplTypeStr() << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfNodes='\\\"$nbproc\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfProcPerNode=\"1\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' can_run_containers=\"true\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '/>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "done" << std::endl;
launch_script_stream << "echo '</resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "fi" << std::endl;
// Create file for ns-port-log
launch_script_stream << "NS_PORT_FILE_PATH=`mktemp " << _resource_definition.AppliPath << "/USERS/nsport_XXXXXX` &&\n";
launch_script_stream << "NS_PORT_FILE_NAME=`basename $NS_PORT_FILE_PATH` &&\n";
// Launch SALOME with an appli
launch_script_stream << _resource_definition.AppliPath << "/runAppli --terminal --ns-port-log=$NS_PORT_FILE_NAME --server-launch-mode=fork ";
launch_script_stream << "> logs/salome_" << _launch_date << ".log 2>&1 &&" << std::endl;
launch_script_stream << "current=0 &&\n"
<< "stop=20 &&\n"
<< "while ! test -s $NS_PORT_FILE_PATH\n"
<< "do\n"
<< " sleep 2\n"
<< " current=$((current+1))\n"
<< " if [ \"$current\" -eq \"$stop\" ] ; then\n"
<< " echo Error Naming Service failed ! >&2\n"
<< " exit\n"
<< " fi\n"
<< "done &&\n"
<< "appli_port=`cat $NS_PORT_FILE_PATH` &&\n"
<< "rm $NS_PORT_FILE_PATH &&\n";
// Call real job type
addJobTypeSpecificScript(launch_script_stream);
// End
launch_script_stream << _resource_definition.AppliPath << "/runSession -p $appli_port shutdownSalome.py" << std::endl;
launch_script_stream << "sleep 10" << std::endl;
// Return
launch_script_stream.flush();
launch_script_stream.close();
chmod(launch_script.c_str(), 0x1ED);
return launch_script;
}
#endif
<commit_msg>Fix regression in Launcher with ForEach-like batch jobs<commit_after>// Copyright (C) 2009-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : [email protected]
//
// Author: André RIBES - EDF R&D
//
#include "Launcher_Job_SALOME.hxx"
#include "Basics_DirUtils.hxx"
#ifdef WITH_LIBBATCH
#include <libbatch/Constants.hxx>
#endif
#ifdef WNT
#include <io.h>
#define _chmod chmod
#endif
Launcher::Job_SALOME::Job_SALOME() {}
Launcher::Job_SALOME::~Job_SALOME() {}
void
Launcher::Job_SALOME::setResourceDefinition(const ParserResourcesType & resource_definition)
{
// Check resource_definition
if (resource_definition.AppliPath == "")
{
std::string mess = "Resource definition must define an application path !, resource name is: " + resource_definition.Name;
throw LauncherException(mess);
}
Launcher::Job::setResourceDefinition(resource_definition);
}
void
Launcher::Job_SALOME::update_job()
{
#ifdef WITH_LIBBATCH
Batch::Parametre params = common_job_params();
params[Batch::EXECUTABLE] = buildSalomeScript(params);
params[Batch::EXCLUSIVE] = true;
_batch_job->setParametre(params);
#endif
}
#ifdef WITH_LIBBATCH
std::string
Launcher::Job_SALOME::buildSalomeScript(Batch::Parametre params)
{
// parameters
std::string work_directory = params[Batch::WORKDIR].str();
std::string launch_script = Kernel_Utils::GetTmpDir() + "runSalome_" + _job_file_name + "_" + _launch_date + ".sh";
std::ofstream launch_script_stream;
launch_script_stream.open(launch_script.c_str(),
std::ofstream::out
#ifdef WIN32
| std::ofstream::binary //rnv: to avoid CL+RF end of line on windows
#endif
);
// Begin of script
launch_script_stream << "#!/bin/sh -f" << std::endl;
launch_script_stream << "cd " << work_directory << std::endl;
launch_script_stream << "export PYTHONPATH=" << work_directory << ":$PYTHONPATH" << std::endl;
launch_script_stream << "export PATH=" << work_directory << ":$PATH" << std::endl;
if (_env_file != "")
{
std::string::size_type last = _env_file.find_last_of("/");
launch_script_stream << ". " << _env_file.substr(last+1) << std::endl;
}
launch_script_stream << "export SALOME_TMP_DIR=" << work_directory << "/logs" << std::endl;
// -- Generates Catalog Resources
std::string resource_protocol = _resource_definition.getClusterInternalProtocolStr();
launch_script_stream << "if [ \"x$LIBBATCH_NODEFILE\" != \"x\" ]; then " << std::endl;
launch_script_stream << "CATALOG_FILE=" << "CatalogResources_" << _launch_date << ".xml" << std::endl;
launch_script_stream << "export USER_CATALOG_RESOURCES_FILE=" << "$CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<!DOCTYPE ResourcesCatalog>' > $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '<resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "cat $LIBBATCH_NODEFILE | sort | uniq -c | while read nbproc host" << std::endl;
launch_script_stream << "do" << std::endl;
// Full name doesn't work. eg: sagittaire-7 instead of sagittaire-7.lyon.grid5000.fr
launch_script_stream << "host_basename=$(echo $host | cut -f1 -d.)" << std::endl;
launch_script_stream << "echo '<machine hostname='\\\"$host_basename\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' protocol=\"" << resource_protocol << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' userName=\"" << _resource_definition.UserName << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' appliPath=\"" << _resource_definition.AppliPath << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' mpi=\"" << _resource_definition.getMpiImplTypeStr() << "\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfNodes='\\\"$nbproc\\\" >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' nbOfProcPerNode=\"1\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo ' canRunContainers=\"true\"' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "echo '/>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "done" << std::endl;
launch_script_stream << "echo '</resources>' >> $CATALOG_FILE" << std::endl;
launch_script_stream << "fi" << std::endl;
// Create file for ns-port-log
launch_script_stream << "NS_PORT_FILE_PATH=`mktemp " << _resource_definition.AppliPath << "/USERS/nsport_XXXXXX` &&\n";
launch_script_stream << "NS_PORT_FILE_NAME=`basename $NS_PORT_FILE_PATH` &&\n";
// Launch SALOME with an appli
launch_script_stream << _resource_definition.AppliPath << "/runAppli --terminal --ns-port-log=$NS_PORT_FILE_NAME --server-launch-mode=fork ";
launch_script_stream << "> logs/salome_" << _launch_date << ".log 2>&1 &&" << std::endl;
launch_script_stream << "current=0 &&\n"
<< "stop=20 &&\n"
<< "while ! test -s $NS_PORT_FILE_PATH\n"
<< "do\n"
<< " sleep 2\n"
<< " current=$((current+1))\n"
<< " if [ \"$current\" -eq \"$stop\" ] ; then\n"
<< " echo Error Naming Service failed ! >&2\n"
<< " exit\n"
<< " fi\n"
<< "done &&\n"
<< "appli_port=`cat $NS_PORT_FILE_PATH` &&\n"
<< "rm $NS_PORT_FILE_PATH &&\n";
// Call real job type
addJobTypeSpecificScript(launch_script_stream);
// End
launch_script_stream << _resource_definition.AppliPath << "/runSession -p $appli_port shutdownSalome.py" << std::endl;
launch_script_stream << "sleep 10" << std::endl;
// Return
launch_script_stream.flush();
launch_script_stream.close();
chmod(launch_script.c_str(), 0x1ED);
return launch_script;
}
#endif
<|endoftext|> |
<commit_before>/**
* Steps to do for pwm
* 1. "echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots"
* 2. "echo bone_pwm_P8_13 > /sys/devices/bone_capemgr.9/slots"
* 3. "cd /sys/devices/ocp.3/pwm_test_P8_13.16/"
* 4. "echo 0 > duty" for max value or "echo 500000 > duty" for min value
*/
#include "gpio.hpp"
#include <cassert>
#include <glob.h>
#include <sstream>
using namespace std;
GPIO::GPIO() :
PWM_PERIOD(50000) // nanoseconds = 2000 Hz
{
// Enable the pwm pins
echo("/sys/devices/bone_capemgr.9/slots", "am33xx_pwm");
// Do not change the order of pins here. The PIN enum is used to access
// these paths, so their order is important.
cout << "Finding PWM pin paths:\n";
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P8_13");
string path = matchPath("/sys/devices/ocp.*/pwm_test_P8_13.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P8_19");
path = matchPath("/sys/devices/ocp.*/pwm_test_P8_19.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P9_14");
path = matchPath("/sys/devices/ocp.*/pwm_test_P9_14.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P9_16");
path = matchPath("/sys/devices/ocp.*/pwm_test_P9_16.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
// Set PWM period for both outputs
int result = echo(append(_pwmPinPaths[P8_13], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
result = echo(append(_pwmPinPaths[P8_19], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
result = echo(append(_pwmPinPaths[P9_14], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
result = echo(append(_pwmPinPaths[P9_16], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
}
GPIO::~GPIO()
{
}
void GPIO::setPin(const Pin pin, const bool value)
{
assert(value == 0 || value == 1);
// already exported?
if (!containsPin(pin)) {
exportPin(pin);
}
stringstream ss;
ss << "/sys/class/gpio/gpio" << pin << "/value";
string pinPath = ss.str();
echo(pinPath, value);
}
/* Duty cycle in percent */
void GPIO::setPwm(const PwmPin pin, const float dutyPerc)
{
/*
https://groups.google.com/forum/#!topic/beagleboard/qma8bMph0yM
This will connect PWM to pin P9_14 and generate on the pin ~2MHz
waveform with 50% duty.
modprobe pwm_test
echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots
echo bone_pwm_P9_14 > /sys/devices/bone_capemgr.9/slots
echo 500 > /sys/devices/ocp.2/pwm_test_P9_14.16/period
echo 250 > /sys/devices/ocp.2/pwm_test_P9_14.16/duty
*/
assert(dutyPerc >= 0.0);
assert(dutyPerc <= 1.0);
// The beaglebone interprets duty == period as 0 V output and duty == 0 results in
// 3.3 V output, so we invert the value here to make 0 % duty correspond to 0 V output.
const int duty = (1.0 - dutyPerc) * 500000;
int result = 0;
result = echo(append(_pwmPinPaths[pin], "duty"), duty);
if(result != 0) {
cout << "At least one echo failed\n";
}
}
bool GPIO::containsPin(const Pin pin)
{
for (vector<int>::iterator it = _exportedPins.begin();
it != _exportedPins.end(); it++) {
if (*it == pin) {
return true;
}
}
return false;
}
void GPIO::exportPin(const Pin pin)
{
// Construct the base path to the pin
stringstream ss;
ss << "/sys/class/gpio/gpio" << pin << "/";
string basePath = ss.str();
echo("/sys/class/gpio/export", pin);
echo(append(basePath, "direction"), "out");
// WTF?
/*strcpy(setValue, GPIOString);
if(fwrite(&setValue, sizeof(char), 2, outputHandle) == -1)
cerr << "kaputt\n";
fclose(outputHandle);*/
_exportedPins.push_back(pin);
}
int GPIO::echo(const string target, const int value)
{
ofstream file(target.c_str());
if(!file) {
cerr << "Could not open " << target << endl;
return -1;
}
file << value;
file.close();
return 0;
}
int GPIO::echo(const string target, const char *value)
{
ofstream file(target.c_str());
if(!file) {
cerr << "Could not open " << target << endl;
return -1;
}
file << value;
file.close();
return 0;
}
string GPIO::matchPath(const std::string pattern)
{
// Find the pwm pin paths (they change on every reboot...)
// int glob(const char *pattern, int flags,
// int (*errfunc) (const char *epath, int eerrno),
// glob_t *pglob);
glob_t foundPaths;
int result = glob(pattern.c_str(), GLOB_ERR | GLOB_MARK, NULL, &foundPaths);
switch(result) {
case 0:
if(foundPaths.gl_pathc != 1) {
cout << "Warning: PWM pin path pattern (tm) matched more than one path. Taking the first one.\n";
}
return string(foundPaths.gl_pathv[0]);
case GLOB_NOSPACE:
cerr << "Call to glob ran out of memory!\n";
break;
case GLOB_ABORTED:
cerr << "Glob encountered a read error (are we root?)\n";
break;
case GLOB_NOMATCH:
cerr << "Glob couldn't match a path\n";
break;
default:
cerr << "Unexpected glob error!\n";
}
return string();
}
<commit_msg>Initialize GPIOs to low<commit_after>/**
* Steps to do for pwm
* 1. "echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots"
* 2. "echo bone_pwm_P8_13 > /sys/devices/bone_capemgr.9/slots"
* 3. "cd /sys/devices/ocp.3/pwm_test_P8_13.16/"
* 4. "echo 0 > duty" for max value or "echo 500000 > duty" for min value
*/
#include "gpio.hpp"
#include <cassert>
#include <glob.h>
#include <sstream>
using namespace std;
GPIO::GPIO() :
PWM_PERIOD(50000) // nanoseconds = 2000 Hz
{
// Enable the pwm pins
echo("/sys/devices/bone_capemgr.9/slots", "am33xx_pwm");
// Do not change the order of pins here. The PIN enum is used to access
// these paths, so their order is important.
cout << "Finding PWM pin paths:\n";
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P8_13");
string path = matchPath("/sys/devices/ocp.*/pwm_test_P8_13.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
setPwm(P8_13, 0.0);
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P8_19");
path = matchPath("/sys/devices/ocp.*/pwm_test_P8_19.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
setPwm(P8_19, 0.0);
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P9_14");
path = matchPath("/sys/devices/ocp.*/pwm_test_P9_14.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
setPwm(P9_14, 0.0);
echo("/sys/devices/bone_capemgr.9/slots", "bone_pwm_P9_16");
path = matchPath("/sys/devices/ocp.*/pwm_test_P9_16.*/");
cout << path << endl;
_pwmPinPaths.push_back(path);
setPwm(P9_16, 0.0);
// Set PWM period for both outputs
int result = echo(append(_pwmPinPaths[P8_13], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
result = echo(append(_pwmPinPaths[P8_19], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
result = echo(append(_pwmPinPaths[P9_14], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
result = echo(append(_pwmPinPaths[P9_16], "period"), PWM_PERIOD);
if(result != 0) {
cout << "At least one echo failed\n";
}
}
GPIO::~GPIO()
{
}
void GPIO::setPin(const Pin pin, const bool value)
{
assert(value == 0 || value == 1);
// already exported?
if (!containsPin(pin)) {
exportPin(pin);
}
stringstream ss;
ss << "/sys/class/gpio/gpio" << pin << "/value";
string pinPath = ss.str();
echo(pinPath, value);
}
/* Duty cycle in percent */
void GPIO::setPwm(const PwmPin pin, const float dutyPerc)
{
/*
https://groups.google.com/forum/#!topic/beagleboard/qma8bMph0yM
This will connect PWM to pin P9_14 and generate on the pin ~2MHz
waveform with 50% duty.
modprobe pwm_test
echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots
echo bone_pwm_P9_14 > /sys/devices/bone_capemgr.9/slots
echo 500 > /sys/devices/ocp.2/pwm_test_P9_14.16/period
echo 250 > /sys/devices/ocp.2/pwm_test_P9_14.16/duty
*/
assert(dutyPerc >= 0.0);
assert(dutyPerc <= 1.0);
// The beaglebone interprets duty == period as 0 V output and duty == 0 results in
// 3.3 V output, so we invert the value here to make 0 % duty correspond to 0 V output.
const int duty = (1.0 - dutyPerc) * 500000;
int result = 0;
result = echo(append(_pwmPinPaths[pin], "duty"), duty);
if(result != 0) {
cout << "At least one echo failed\n";
}
}
bool GPIO::containsPin(const Pin pin)
{
for (vector<int>::iterator it = _exportedPins.begin();
it != _exportedPins.end(); it++) {
if (*it == pin) {
return true;
}
}
return false;
}
void GPIO::exportPin(const Pin pin)
{
// Construct the base path to the pin
stringstream ss;
ss << "/sys/class/gpio/gpio" << pin << "/";
string basePath = ss.str();
echo("/sys/class/gpio/export", pin);
echo(append(basePath, "direction"), "out");
// WTF?
/*strcpy(setValue, GPIOString);
if(fwrite(&setValue, sizeof(char), 2, outputHandle) == -1)
cerr << "kaputt\n";
fclose(outputHandle);*/
_exportedPins.push_back(pin);
}
int GPIO::echo(const string target, const int value)
{
ofstream file(target.c_str());
if(!file) {
cerr << "Could not open " << target << endl;
return -1;
}
file << value;
file.close();
return 0;
}
int GPIO::echo(const string target, const char *value)
{
ofstream file(target.c_str());
if(!file) {
cerr << "Could not open " << target << endl;
return -1;
}
file << value;
file.close();
return 0;
}
string GPIO::matchPath(const std::string pattern)
{
// Find the pwm pin paths (they change on every reboot...)
// int glob(const char *pattern, int flags,
// int (*errfunc) (const char *epath, int eerrno),
// glob_t *pglob);
glob_t foundPaths;
int result = glob(pattern.c_str(), GLOB_ERR | GLOB_MARK, NULL, &foundPaths);
switch(result) {
case 0:
if(foundPaths.gl_pathc != 1) {
cout << "Warning: PWM pin path pattern (tm) matched more than one path. Taking the first one.\n";
}
return string(foundPaths.gl_pathv[0]);
case GLOB_NOSPACE:
cerr << "Call to glob ran out of memory!\n";
break;
case GLOB_ABORTED:
cerr << "Glob encountered a read error (are we root?)\n";
break;
case GLOB_NOMATCH:
cerr << "Glob couldn't match a path\n";
break;
default:
cerr << "Unexpected glob error!\n";
}
return string();
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/base_layer_derivations/base_tivlayer.h"
using namespace elm;
base_TIVLayer::base_TIVLayer()
{
}
<commit_msg>add missing destructor implementation<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/base_layer_derivations/base_tivlayer.h"
using namespace elm;
base_TIVLayer::base_TIVLayer()
{
}
base_TIVLayer::~base_TIVLayer()
{
}
<|endoftext|> |
<commit_before>#include "condor_common.h"
#include "condor_classad.h"
BEGIN_NAMESPACE( classad )
ClassAd* getOldClassAd( Sock& sock )
{
ClassAd *ad = new ClassAd( );
if( !ad ) {
return (ClassAd*) 0;
}
if( !getOldClassAd( sock, *ad ) ) {
delete ad;
return NULL;
}
return ad;
}
bool getOldClassAd( Sock& sock, ClassAd& ad )
{
Source src;
int numExprs;
char *eq;
ExprTree *expr;
static char *buffer = new char[ 10240 ];
sock.decode( );
if( !sock.code( numExprs ) ) {
return false;
}
for( int i = 0 ; i < numExprs ; i++ ) {
// get the expression and find the '=' in the expr
if( !sock.code( buffer ) || !( eq = strchr( buffer, '=' ) ) ) {
return false;
}
// split the expression at the '='
*eq = '\0';
// set the source to the part after the '='
src.SetSource( eq+1 );
// parse the expression and insert it into the classad
if( !src.ParseExpression( expr ) || !ad.Insert( buffer, expr ) ) {
return false;
}
}
// Get my type and target type
if (!sock.code(buffer) || !ad.Insert("MyType",buffer)) return false;
if (!sock.code(buffer) || !ad.Insert("TargetType",buffer)) return false;
return true;
}
bool putOldClassAd ( Sock& sock, ClassAd& ad )
{
char* attr;
ExprTree* expr;
char buffer[10240];
char tmp[10240];
char* tmpPtr=tmp;
int numExprs=0;
ClassAdIterator itor(ad);
while (itor.NextAttribute(attr, expr)) {
if (strcmp(attr,"MyType")==0 || strcmp(attr,"TargetType")==0) continue;
numExprs++;
}
sock.encode( );
//printf("Sending: %d\n",numExprs);
if( !sock.code( numExprs ) ) {
return false;
}
itor.ToBeforeFirst();
while (itor.NextAttribute(attr, expr)) {
if (strcmp(attr,"MyType")==0 || strcmp(attr,"TargetType")==0) continue;
memset(buffer,0,sizeof(buffer));
Sink s;
s.SetSink(buffer,sizeof(buffer));
expr->ToSink(s);
sprintf(tmp,"%s = %s",attr,buffer);
//printf("Sending: %s\n",tmpPtr);
if (!sock.code(tmpPtr)) {
return false;
}
}
// Send the type
char* type=NULL;
if (!ad.EvaluateAttrString("MyType",type)) type="(unknown type)";
//printf("Sending: %s\n",type);
if (!sock.code(type)) {
return false;
}
char* target_type=NULL;
if (!ad.EvaluateAttrString("TargetType",target_type)) target_type="(unknown type)";
//printf("Sending: %s\n",target_type);
if (!sock.code(target_type)) {
return false;
}
return true;
}
void printClassAdExpr( ExprTree *tree )
{
static Sink sink;
static FormatOptions fo;
sink.SetSink( stdout );
fo.SetClassAdIndentation( );
fo.SetListIndentation( );
sink.SetFormatOptions( &fo );
tree->ToSink( sink );
sink.FlushSink( );
}
void printClassAdValue( Value &val )
{
static Sink sink;
static FormatOptions fo;
sink.SetSink( stdout );
fo.SetClassAdIndentation( );
fo.SetListIndentation( );
sink.SetFormatOptions( &fo );
val.ToSink( sink );
sink.FlushSink( );
}
END_NAMESPACE // classad
<commit_msg>Fixed possible unitialized variable use<commit_after>#include "condor_common.h"
#include "condor_classad.h"
BEGIN_NAMESPACE( classad )
ClassAd* getOldClassAd( Sock& sock )
{
ClassAd *ad = new ClassAd( );
if( !ad ) {
return (ClassAd*) 0;
}
if( !getOldClassAd( sock, *ad ) ) {
delete ad;
return NULL;
}
return ad;
}
bool getOldClassAd( Sock& sock, ClassAd& ad )
{
Source src;
int numExprs;
char *eq=NULL;
ExprTree *expr;
static char *buffer = new char[ 10240 ];
sock.decode( );
if( !sock.code( numExprs ) ) {
return false;
}
for( int i = 0 ; i < numExprs ; i++ ) {
// get the expression and find the '=' in the expr
if( !sock.code( buffer ) || !( eq = strchr( buffer, '=' ) ) ) {
return false;
}
// split the expression at the '='
*eq = '\0';
// set the source to the part after the '='
src.SetSource( eq+1 );
// parse the expression and insert it into the classad
if( !src.ParseExpression( expr ) || !ad.Insert( buffer, expr ) ) {
return false;
}
}
// Get my type and target type
if (!sock.code(buffer) || !ad.Insert("MyType",buffer)) return false;
if (!sock.code(buffer) || !ad.Insert("TargetType",buffer)) return false;
return true;
}
bool putOldClassAd ( Sock& sock, ClassAd& ad )
{
char* attr;
ExprTree* expr;
char buffer[10240];
char tmp[10240];
char* tmpPtr=tmp;
int numExprs=0;
ClassAdIterator itor(ad);
while (itor.NextAttribute(attr, expr)) {
if (strcmp(attr,"MyType")==0 || strcmp(attr,"TargetType")==0) continue;
numExprs++;
}
sock.encode( );
//printf("Sending: %d\n",numExprs);
if( !sock.code( numExprs ) ) {
return false;
}
itor.ToBeforeFirst();
while (itor.NextAttribute(attr, expr)) {
if (strcmp(attr,"MyType")==0 || strcmp(attr,"TargetType")==0) continue;
memset(buffer,0,sizeof(buffer));
Sink s;
s.SetSink(buffer,sizeof(buffer));
expr->ToSink(s);
sprintf(tmp,"%s = %s",attr,buffer);
//printf("Sending: %s\n",tmpPtr);
if (!sock.code(tmpPtr)) {
return false;
}
}
// Send the type
char* type=NULL;
if (!ad.EvaluateAttrString("MyType",type)) type="(unknown type)";
//printf("Sending: %s\n",type);
if (!sock.code(type)) {
return false;
}
char* target_type=NULL;
if (!ad.EvaluateAttrString("TargetType",target_type)) target_type="(unknown type)";
//printf("Sending: %s\n",target_type);
if (!sock.code(target_type)) {
return false;
}
return true;
}
void printClassAdExpr( ExprTree *tree )
{
static Sink sink;
static FormatOptions fo;
sink.SetSink( stdout );
fo.SetClassAdIndentation( );
fo.SetListIndentation( );
sink.SetFormatOptions( &fo );
tree->ToSink( sink );
sink.Terminate( );
sink.FlushSink( );
}
void printClassAdValue( Value &val )
{
static Sink sink;
static FormatOptions fo;
sink.SetSink( stdout );
fo.SetClassAdIndentation( );
fo.SetListIndentation( );
sink.SetFormatOptions( &fo );
val.ToSink( sink );
sink.Terminate( );
sink.FlushSink( );
}
END_NAMESPACE // classad
<|endoftext|> |
<commit_before><commit_msg>[HOTFIX] Release Python GIL & reset threat state<commit_after><|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <map>
// PRIVATE API
extern "C" {
#include "disir_private.h"
#include "value.h"
}
#include "test_helper.h"
// Global recurring sample string
const char sample[] = "Snickers and Mars bars";
class DisirValueGenericTest: public testing::DisirTestWrapper
{
protected:
void SetUp()
{
DisirLogCurrentTestEnter ();
memset (&value, 0, sizeof (struct disir_value));
value.dv_type = type;
}
void TearDown()
{
DisirLogCurrentTestExit ();
}
public:
enum disir_status status;
enum disir_value_type type;
struct disir_value value;
};
class DisirValueStringTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_STRING;
DisirValueGenericTest::SetUp();
}
};
class DisirValueIntegerTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_INTEGER;
DisirValueGenericTest::SetUp();
}
};
class DisirValueFloatTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_FLOAT;
DisirValueGenericTest::SetUp();
}
};
class DisirValueEnumTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_ENUM;
DisirValueGenericTest::SetUp();
}
};
class DisirValueBooleanTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_BOOLEAN;
DisirValueGenericTest::SetUp();
}
};
//
// DISIR VALUE GENERIC
//
TEST_F (DisirValueGenericTest, sanify_invalid)
{
ASSERT_EQ (dx_value_type_sanify ((enum disir_value_type) 0), DISIR_VALUE_TYPE_UNKNOWN);
ASSERT_EQ (dx_value_type_sanify ((enum disir_value_type) -1), DISIR_VALUE_TYPE_UNKNOWN);
ASSERT_EQ (dx_value_type_sanify ((enum disir_value_type) 659843), DISIR_VALUE_TYPE_UNKNOWN);
}
//
// DISIR VALUE STRING
//
TEST_F (DisirValueStringTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_STRING);
}
TEST_F (DisirValueStringTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "STRING");
}
TEST_F (DisirValueStringTest, set_string_invalid_argument_shall_fail)
{
status = dx_value_set_string (NULL, NULL, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
status = dx_value_set_string (NULL, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
}
TEST_F (DisirValueStringTest, set_string_invalid_value_type_shall_fail)
{
value.dv_type = DISIR_VALUE_TYPE_UNKNOWN;
status = dx_value_set_string (&value, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
}
TEST_F (DisirValueStringTest, set_string_valid_argument_shall_succeed)
{
status = dx_value_set_string (&value, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_STREQ (sample, value.dv_string);
}
TEST_F (DisirValueStringTest, get_string_invalid_argument_shall_fail)
{
const char *output;
status = dx_value_get_string (NULL, NULL, NULL);
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
status = dx_value_get_string (&value, NULL, NULL);
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
status = dx_value_get_string (NULL, &output, NULL);
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
}
TEST_F (DisirValueStringTest, get_string_populated_shall_succeed)
{
const char *output;
int32_t output_size;
// Setup
status = dx_value_set_string (&value, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_STREQ (sample, value.dv_string);
status = dx_value_get_string (&value, &output, NULL);
EXPECT_STATUS (DISIR_STATUS_OK, status);
status = dx_value_get_string (&value, &output, &output_size);
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_STREQ (sample, output);
EXPECT_EQ (strlen (sample), output_size);
}
TEST_F (DisirValueStringTest, get_string_empty_shall_succeed)
{
const char *output;
int32_t output_size;
status = dx_value_get_string (&value, &output, NULL);
EXPECT_STATUS (DISIR_STATUS_OK, status);
status = dx_value_get_string (&value, &output, &output_size);
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_EQ (NULL, output);
EXPECT_EQ (0, output_size);
}
//
// DISIR VALUE INTEGER
//
TEST_F (DisirValueIntegerTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_INTEGER);
}
TEST_F (DisirValueIntegerTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "INTEGER");
}
//
// DISIR VALUE FLOAT
//
TEST_F (DisirValueFloatTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_FLOAT);
}
TEST_F (DisirValueFloatTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "FLOAT");
}
//
// DISIR VALUE ENUM
//
TEST_F (DisirValueEnumTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_ENUM);
}
TEST_F (DisirValueEnumTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "ENUM");
}
//
// DISIR VALUE BOOLEAN
//
TEST_F (DisirValueBooleanTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_BOOLEAN);
}
TEST_F (DisirValueBooleanTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "BOOLEAN");
}
<commit_msg>test: cleanup allocated string in disir_value<commit_after>#include <gtest/gtest.h>
#include <map>
// PRIVATE API
extern "C" {
#include "disir_private.h"
#include "value.h"
}
#include "test_helper.h"
// Global recurring sample string
const char sample[] = "Snickers and Mars bars";
class DisirValueGenericTest: public testing::DisirTestWrapper
{
protected:
void SetUp()
{
DisirLogCurrentTestEnter ();
memset (&value, 0, sizeof (struct disir_value));
value.dv_type = type;
}
void TearDown()
{
if (value.dv_type == DISIR_VALUE_TYPE_STRING)
{
if (value.dv_string)
{
free (value.dv_string);
}
}
DisirLogCurrentTestExit ();
}
public:
enum disir_status status;
enum disir_value_type type;
struct disir_value value;
};
class DisirValueStringTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_STRING;
DisirValueGenericTest::SetUp();
}
};
class DisirValueIntegerTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_INTEGER;
DisirValueGenericTest::SetUp();
}
};
class DisirValueFloatTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_FLOAT;
DisirValueGenericTest::SetUp();
}
};
class DisirValueEnumTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_ENUM;
DisirValueGenericTest::SetUp();
}
};
class DisirValueBooleanTest : public DisirValueGenericTest
{
void SetUp()
{
type = DISIR_VALUE_TYPE_BOOLEAN;
DisirValueGenericTest::SetUp();
}
};
//
// DISIR VALUE GENERIC
//
TEST_F (DisirValueGenericTest, sanify_invalid)
{
ASSERT_EQ (dx_value_type_sanify ((enum disir_value_type) 0), DISIR_VALUE_TYPE_UNKNOWN);
ASSERT_EQ (dx_value_type_sanify ((enum disir_value_type) -1), DISIR_VALUE_TYPE_UNKNOWN);
ASSERT_EQ (dx_value_type_sanify ((enum disir_value_type) 659843), DISIR_VALUE_TYPE_UNKNOWN);
}
//
// DISIR VALUE STRING
//
TEST_F (DisirValueStringTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_STRING);
}
TEST_F (DisirValueStringTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "STRING");
}
TEST_F (DisirValueStringTest, set_string_invalid_argument_shall_fail)
{
status = dx_value_set_string (NULL, NULL, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
status = dx_value_set_string (NULL, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
}
TEST_F (DisirValueStringTest, set_string_invalid_value_type_shall_fail)
{
value.dv_type = DISIR_VALUE_TYPE_UNKNOWN;
status = dx_value_set_string (&value, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
}
TEST_F (DisirValueStringTest, set_string_valid_argument_shall_succeed)
{
status = dx_value_set_string (&value, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_STREQ (sample, value.dv_string);
}
TEST_F (DisirValueStringTest, get_string_invalid_argument_shall_fail)
{
const char *output;
status = dx_value_get_string (NULL, NULL, NULL);
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
status = dx_value_get_string (&value, NULL, NULL);
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
status = dx_value_get_string (NULL, &output, NULL);
EXPECT_STATUS (DISIR_STATUS_INVALID_ARGUMENT, status);
}
TEST_F (DisirValueStringTest, get_string_populated_shall_succeed)
{
const char *output;
int32_t output_size;
// Setup
status = dx_value_set_string (&value, sample, strlen (sample));
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_STREQ (sample, value.dv_string);
status = dx_value_get_string (&value, &output, NULL);
EXPECT_STATUS (DISIR_STATUS_OK, status);
status = dx_value_get_string (&value, &output, &output_size);
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_STREQ (sample, output);
EXPECT_EQ (strlen (sample), output_size);
}
TEST_F (DisirValueStringTest, get_string_empty_shall_succeed)
{
const char *output;
int32_t output_size;
status = dx_value_get_string (&value, &output, NULL);
EXPECT_STATUS (DISIR_STATUS_OK, status);
status = dx_value_get_string (&value, &output, &output_size);
EXPECT_STATUS (DISIR_STATUS_OK, status);
EXPECT_EQ (NULL, output);
EXPECT_EQ (0, output_size);
}
//
// DISIR VALUE INTEGER
//
TEST_F (DisirValueIntegerTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_INTEGER);
}
TEST_F (DisirValueIntegerTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "INTEGER");
}
//
// DISIR VALUE FLOAT
//
TEST_F (DisirValueFloatTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_FLOAT);
}
TEST_F (DisirValueFloatTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "FLOAT");
}
//
// DISIR VALUE ENUM
//
TEST_F (DisirValueEnumTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_ENUM);
}
TEST_F (DisirValueEnumTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "ENUM");
}
//
// DISIR VALUE BOOLEAN
//
TEST_F (DisirValueBooleanTest, sanify)
{
ASSERT_EQ (dx_value_type_sanify (type), DISIR_VALUE_TYPE_BOOLEAN);
}
TEST_F (DisirValueBooleanTest, string)
{
ASSERT_STREQ (dx_value_type_string (type), "BOOLEAN");
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef VIEW_HPP
#define VIEW_HPP
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif
#include <functional>
#include <GL/gl3w.h>
#include <GLFW/glfw3.h>
//template<typename T> struct std::function;
namespace View {
void printErrors(const char *prefix);
/// A view structure (state and implementation)
struct view {
typedef enum {
prog_id=0, va_id,
vbuf_id, ibuf_id,
model_id, view_id,
proj_id,
_max
} id_index;
GLuint ids[id_index::_max];
bool valid = false;
float near = 1, far = 10, fov = 25;
int nTriangles;
GLFWwindow *win;
void setUniforms(void);
/*! Calculates and displays the next frame, potentially incorporating
* the frame index (discrete time) and FPS
* @param frame The discrete time (frames since startup)
* @param fps The most-recently calculated frames per second
*/
void redraw(int frame = 0, int fps = 0);
void run(std::function<bool()>, std::function<void()>);
view(const char *vert, const char *frag);
virtual ~view(void);
};
}
#endif
<commit_msg>Added documentation<commit_after>#pragma once
#ifndef VIEW_HPP
#define VIEW_HPP
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif
#include <functional>
#include <GL/gl3w.h>
#include <GLFW/glfw3.h>
#include "view/input.hpp"
#include "view/shade.hpp"
//template<typename T> struct std::function;
namespace View {
void printErrors(const char *prefix);
/// A view structure (state and implementation)
struct view {
typedef enum {
prog_id=0, va_id,
vbuf_id, ibuf_id,
model_id, view_id,
proj_id,
_max
} id_index;
GLuint ids[id_index::_max];
bool valid = false;
float near = 1, far = 10, fov = 25;
int nTriangles;
GLFWwindow *win;
/// Sets stable shader values (uniforms)
void setUniforms(void);
/*! Calculates and displays the next frame, potentially incorporating
* the frame index (discrete time) and FPS
* @param frame The discrete time (frames since startup)
* @param fps The most-recently calculated frames per second
*/
void redraw(int frame = 0, int fps = 0);
/** Begins the game loop with the specified callbacks
* @param update Updates the model; false signals shutdown
* @param quit Destroys the model and managed resources
*/
void run(std::function<bool()> update,
std::function<void()> quit);
/** Constructor for a view object
* @param vert Path to a GLSL vertex shader
* @param frag Path to a GLSL fragment shader
*/
view(const char *vert, const char *frag);
/// Destructor for a view object
virtual ~view(void);
};
}
#endif
<|endoftext|> |
<commit_before>//===-- SymbolTable.cpp - Implement the SymbolTable class -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the SymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/SymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "Support/StringExtras.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_SYMBOL_TABLE 0
#define DEBUG_ABSTYPE 0
SymbolTable::~SymbolTable() {
// Drop all abstract type references in the type plane...
iterator TyPlane = find(Type::TypeTy);
if (TyPlane != end()) {
VarMap &TyP = TyPlane->second;
for (VarMap::iterator I = TyP.begin(), E = TyP.end(); I != E; ++I) {
const Type *Ty = cast<Type>(I->second);
if (Ty->isAbstract()) // If abstract, drop the reference...
cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
}
}
// TODO: FIXME: BIG ONE: This doesn't unreference abstract types for the planes
// that could still have entries!
#ifndef NDEBUG // Only do this in -g mode...
bool LeftoverValues = true;
for (iterator i = begin(); i != end(); ++i) {
for (type_iterator I = i->second.begin(); I != i->second.end(); ++I)
if (!isa<Constant>(I->second) && !isa<Type>(I->second)) {
std::cerr << "Value still in symbol table! Type = '"
<< i->first->getDescription() << "' Name = '"
<< I->first << "'\n";
LeftoverValues = false;
}
}
assert(LeftoverValues && "Values remain in symbol table!");
#endif
}
// getUniqueName - Given a base name, return a string that is either equal to
// it (or derived from it) that does not already occur in the symbol table for
// the specified type.
//
std::string SymbolTable::getUniqueName(const Type *Ty,
const std::string &BaseName) {
iterator I = find(Ty);
if (I == end()) return BaseName;
std::string TryName = BaseName;
type_iterator End = I->second.end();
while (I->second.find(TryName) != End) // Loop until we find a free
TryName = BaseName + utostr(++LastUnique); // name in the symbol table
return TryName;
}
// lookup - Returns null on failure...
Value *SymbolTable::lookup(const Type *Ty, const std::string &Name) const {
const_iterator I = find(Ty);
if (I != end()) { // We have symbols in that plane...
type_const_iterator J = I->second.find(Name);
if (J != I->second.end()) // and the name is in our hash table...
return J->second;
}
return 0;
}
void SymbolTable::remove(Value *N) {
assert(N->hasName() && "Value doesn't have name!");
if (InternallyInconsistent) return;
iterator I = find(N->getType());
assert(I != end() &&
"Trying to remove a type that doesn't have a plane yet!");
removeEntry(I, I->second.find(N->getName()));
}
// removeEntry - Remove a value from the symbol table...
//
Value *SymbolTable::removeEntry(iterator Plane, type_iterator Entry) {
if (InternallyInconsistent) return 0;
assert(Plane != super::end() &&
Entry != Plane->second.end() && "Invalid entry to remove!");
Value *Result = Entry->second;
const Type *Ty = Result->getType();
#if DEBUG_SYMBOL_TABLE
dump();
std::cerr << " Removing Value: " << Result->getName() << "\n";
#endif
// Remove the value from the plane...
Plane->second.erase(Entry);
// If the plane is empty, remove it now!
if (Plane->second.empty()) {
// If the plane represented an abstract type that we were interested in,
// unlink ourselves from this plane.
//
if (Plane->first->isAbstract()) {
#if DEBUG_ABSTYPE
std::cerr << "Plane Empty: Removing type: "
<< Plane->first->getDescription() << "\n";
#endif
cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this);
}
erase(Plane);
}
// If we are removing an abstract type, remove the symbol table from it's use
// list...
if (Ty == Type::TypeTy) {
const Type *T = cast<Type>(Result);
if (T->isAbstract()) {
#if DEBUG_ABSTYPE
std::cerr << "Removing abs type from symtab" << T->getDescription()<<"\n";
#endif
cast<DerivedType>(T)->removeAbstractTypeUser(this);
}
}
return Result;
}
// insertEntry - Insert a value into the symbol table with the specified
// name...
//
void SymbolTable::insertEntry(const std::string &Name, const Type *VTy,
Value *V) {
// Check to see if there is a naming conflict. If so, rename this value!
if (lookup(VTy, Name)) {
std::string UniqueName = getUniqueName(VTy, Name);
assert(InternallyInconsistent == false && "Infinite loop inserting entry!");
InternallyInconsistent = true;
V->setName(UniqueName, this);
InternallyInconsistent = false;
return;
}
#if DEBUG_SYMBOL_TABLE
dump();
std::cerr << " Inserting definition: " << Name << ": "
<< VTy->getDescription() << "\n";
#endif
iterator I = find(VTy);
if (I == end()) { // Not in collection yet... insert dummy entry
// Insert a new empty element. I points to the new elements.
I = super::insert(make_pair(VTy, VarMap())).first;
assert(I != end() && "How did insert fail?");
// Check to see if the type is abstract. If so, it might be refined in the
// future, which would cause the plane of the old type to get merged into
// a new type plane.
//
if (VTy->isAbstract()) {
cast<DerivedType>(VTy)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
std::cerr << "Added abstract type value: " << VTy->getDescription()
<< "\n";
#endif
}
}
I->second.insert(make_pair(Name, V));
// If we are adding an abstract type, add the symbol table to it's use list.
if (VTy == Type::TypeTy) {
const Type *T = cast<Type>(V);
if (T->isAbstract()) {
cast<DerivedType>(T)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
std::cerr << "Added abstract type to ST: " << T->getDescription() << "\n";
#endif
}
}
}
// This function is called when one of the types in the type plane are refined
void SymbolTable::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
// Search to see if we have any values of the type oldtype. If so, we need to
// move them into the newtype plane...
iterator TPI = find(OldType);
if (TPI != end()) {
// Get a handle to the new type plane...
iterator NewTypeIt = find(NewType);
if (NewTypeIt == super::end()) { // If no plane exists, add one
NewTypeIt = super::insert(make_pair(NewType, VarMap())).first;
if (NewType->isAbstract()) {
cast<DerivedType>(NewType)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
std::cerr << "[Added] refined to abstype: " << NewType->getDescription()
<< "\n";
#endif
}
}
VarMap &NewPlane = NewTypeIt->second;
VarMap &OldPlane = TPI->second;
while (!OldPlane.empty()) {
std::pair<const std::string, Value*> V = *OldPlane.begin();
// Check to see if there is already a value in the symbol table that this
// would collide with.
type_iterator TI = NewPlane.find(V.first);
if (TI != NewPlane.end() && TI->second == V.second) {
// No action
} else if (TI != NewPlane.end()) {
// The only thing we are allowing for now is two external global values
// folded into one.
//
GlobalValue *ExistGV = dyn_cast<GlobalValue>(TI->second);
GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second);
if (ExistGV && NewGV) {
assert((ExistGV->isExternal() || NewGV->isExternal()) &&
"Two planes folded together with overlapping value names!");
// Make sure that ExistGV is the one we want to keep!
if (!NewGV->isExternal())
std::swap(NewGV, ExistGV);
// Ok we have two external global values. Make all uses of the new
// one use the old one...
NewGV->uncheckedReplaceAllUsesWith(ExistGV);
// Now we just convert it to an unnamed method... which won't get
// added to our symbol table. The problem is that if we call
// setName on the method that it will try to remove itself from
// the symbol table and die... because it's not in the symtab
// right now. To fix this, we have an internally consistent flag
// that turns remove into a noop. Thus the name will get null'd
// out, but the symbol table won't get upset.
//
assert(InternallyInconsistent == false &&
"Symbol table already inconsistent!");
InternallyInconsistent = true;
// Remove newM from the symtab
NewGV->setName("");
InternallyInconsistent = false;
// Now we can remove this global from the module entirely...
Module *M = NewGV->getParent();
if (Function *F = dyn_cast<Function>(NewGV))
M->getFunctionList().remove(F);
else
M->getGlobalList().remove(cast<GlobalVariable>(NewGV));
delete NewGV;
} else {
// If they are not global values, they must be just random values who
// happen to conflict now that types have been resolved. If this is
// the case, reinsert the value into the new plane, allowing it to get
// renamed.
assert(V.second->getType() == NewType &&"Type resolution is broken!");
insert(V.second);
}
} else {
insertEntry(V.first, NewType, V.second);
}
// Remove the item from the old type plane
OldPlane.erase(OldPlane.begin());
}
// Ok, now we are not referencing the type anymore... take me off your user
// list please!
#if DEBUG_ABSTYPE
std::cerr << "Removing type " << OldType->getDescription() << "\n";
#endif
OldType->removeAbstractTypeUser(this);
// Remove the plane that is no longer used
erase(TPI);
}
TPI = find(Type::TypeTy);
if (TPI != end()) {
// Loop over all of the types in the symbol table, replacing any references
// to OldType with references to NewType. Note that there may be multiple
// occurrences, and although we only need to remove one at a time, it's
// faster to remove them all in one pass.
//
VarMap &TyPlane = TPI->second;
for (VarMap::iterator I = TyPlane.begin(), E = TyPlane.end(); I != E; ++I)
if (I->second == (Value*)OldType) { // FIXME when Types aren't const.
#if DEBUG_ABSTYPE
std::cerr << "Removing type " << OldType->getDescription() << "\n";
#endif
OldType->removeAbstractTypeUser(this);
I->second = (Value*)NewType; // TODO FIXME when types aren't const
if (NewType->isAbstract()) {
#if DEBUG_ABSTYPE
std::cerr << "Added type " << NewType->getDescription() << "\n";
#endif
cast<DerivedType>(NewType)->addAbstractTypeUser(this);
}
}
}
}
void SymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
iterator TPI = find(AbsTy);
// If there are any values in the symbol table of this type, then the type
// plan is a use of the abstract type which must be dropped.
if (TPI != end())
AbsTy->removeAbstractTypeUser(this);
TPI = find(Type::TypeTy);
if (TPI != end()) {
// Loop over all of the types in the symbol table, dropping any abstract
// type user entries for AbsTy which occur because there are names for the
// type.
//
VarMap &TyPlane = TPI->second;
for (VarMap::iterator I = TyPlane.begin(), E = TyPlane.end(); I != E; ++I)
if (I->second == (Value*)AbsTy) // FIXME when Types aren't const.
AbsTy->removeAbstractTypeUser(this);
}
}
static void DumpVal(const std::pair<const std::string, Value *> &V) {
std::cout << " '" << V.first << "' = ";
V.second->dump();
std::cout << "\n";
}
static void DumpPlane(const std::pair<const Type *,
std::map<const std::string, Value *> >&P){
std::cout << " Plane: ";
P.first->dump();
std::cout << "\n";
for_each(P.second.begin(), P.second.end(), DumpVal);
}
void SymbolTable::dump() const {
std::cout << "Symbol table dump:\n";
for_each(begin(), end(), DumpPlane);
}
<commit_msg>Completely rewrote the class. SymbolTable now separates Type* from Value* in preparation\ for making Type not derive from Value. There are now separate interfaces \ for looking up, finding, and inserting Types and Values. There are also \ three separate iterator interfaces, one for type planes, one for the types \ (type type plane), and one for values within a type plane. See the \ documentation in the Header file.<commit_after>//===-- SymbolTable.cpp - Implement the SymbolTable class -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and revised by Reid
// Spencer. It is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the SymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/SymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "Support/StringExtras.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_SYMBOL_TABLE 0
#define DEBUG_ABSTYPE 0
SymbolTable::~SymbolTable() {
// Drop all abstract type references in the type plane...
for (type_iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
if (TI->second->isAbstract()) // If abstract, drop the reference...
cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
}
// TODO: FIXME: BIG ONE: This doesn't unreference abstract types for the
// planes that could still have entries!
#ifndef NDEBUG // Only do this in -g mode...
bool LeftoverValues = true;
for (plane_iterator PI = pmap.begin(); PI != pmap.end(); ++PI) {
for (value_iterator VI = PI->second.begin(); VI != PI->second.end(); ++VI)
if (!isa<Constant>(VI->second) ) {
std::cerr << "Value still in symbol table! Type = '"
<< PI->first->getDescription() << "' Name = '"
<< VI->first << "'\n";
LeftoverValues = false;
}
}
assert(LeftoverValues && "Values remain in symbol table!");
#endif
}
// getUniqueName - Given a base name, return a string that is either equal to
// it (or derived from it) that does not already occur in the symbol table for
// the specified type.
//
std::string SymbolTable::getUniqueName(const Type *Ty,
const std::string &BaseName) const {
// Find the plane
plane_const_iterator PI = pmap.find(Ty);
if (PI == pmap.end()) return BaseName;
std::string TryName = BaseName;
const ValueMap& vmap = PI->second;
value_const_iterator End = vmap.end();
// See if the name exists
while (vmap.find(TryName) != End) // Loop until we find a free
TryName = BaseName + utostr(++LastUnique); // name in the symbol table
return TryName;
}
// lookup a value - Returns null on failure...
Value *SymbolTable::lookup(const Type *Ty, const std::string &Name) const {
plane_const_iterator PI = pmap.find(Ty);
if (PI != pmap.end()) { // We have symbols in that plane...
value_const_iterator VI = PI->second.find(Name);
if (VI != PI->second.end()) // and the name is in our hash table...
return VI->second;
}
return 0;
}
// lookup a type by name - returns null on failure
Type* SymbolTable::lookupType( const std::string& Name ) const {
type_const_iterator TI = tmap.find( Name );
if ( TI != tmap.end() )
return TI->second;
return 0;
}
// Remove a value
void SymbolTable::remove(Value *N) {
assert(N->hasName() && "Value doesn't have name!");
if (InternallyInconsistent) return;
plane_iterator PI = pmap.find(N->getType());
assert(PI != pmap.end() &&
"Trying to remove a value that doesn't have a type plane yet!");
removeEntry(PI, PI->second.find(N->getName()));
}
// removeEntry - Remove a value from the symbol table...
Value *SymbolTable::removeEntry(plane_iterator Plane, value_iterator Entry) {
if (InternallyInconsistent) return 0;
assert(Plane != pmap.end() &&
Entry != Plane->second.end() && "Invalid entry to remove!");
Value *Result = Entry->second;
const Type *Ty = Result->getType();
#if DEBUG_SYMBOL_TABLE
dump();
std::cerr << " Removing Value: " << Result->getName() << "\n";
#endif
// Remove the value from the plane...
Plane->second.erase(Entry);
// If the plane is empty, remove it now!
if (Plane->second.empty()) {
// If the plane represented an abstract type that we were interested in,
// unlink ourselves from this plane.
//
if (Plane->first->isAbstract()) {
#if DEBUG_ABSTYPE
std::cerr << "Plane Empty: Removing type: "
<< Plane->first->getDescription() << "\n";
#endif
cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this);
}
pmap.erase(Plane);
}
return Result;
}
// remove - Remove a type
void SymbolTable::remove(Type* Ty ) {
type_iterator TI = this->type_begin();
type_iterator TE = this->type_end();
// Search for the entry
while ( TI != TE && TI->second != Ty )
++TI;
if ( TI != TE )
this->removeEntry( TI );
}
// removeEntry - Remove a type from the symbol table...
Type* SymbolTable::removeEntry(type_iterator Entry) {
if (InternallyInconsistent) return 0;
assert( Entry != tmap.end() && "Invalid entry to remove!");
Type* Result = Entry->second;
#if DEBUG_SYMBOL_TABLE
dump();
std::cerr << " Removing Value: " << Result->getName() << "\n";
#endif
tmap.erase(Entry);
// If we are removing an abstract type, remove the symbol table from it's use
// list...
if (Result->isAbstract()) {
#if DEBUG_ABSTYPE
std::cerr << "Removing abstract type from symtab" << Result->getDescription()<<"\n";
#endif
cast<DerivedType>(Result)->removeAbstractTypeUser(this);
}
return Result;
}
// insertEntry - Insert a value into the symbol table with the specified name.
void SymbolTable::insertEntry(const std::string &Name, const Type *VTy,
Value *V) {
// Check to see if there is a naming conflict. If so, rename this value!
if (lookup(VTy, Name)) {
std::string UniqueName = getUniqueName(VTy, Name);
assert(InternallyInconsistent == false && "Infinite loop inserting value!");
InternallyInconsistent = true;
V->setName(UniqueName, this);
InternallyInconsistent = false;
return;
}
#if DEBUG_SYMBOL_TABLE
dump();
std::cerr << " Inserting definition: " << Name << ": "
<< VTy->getDescription() << "\n";
#endif
plane_iterator PI = pmap.find(VTy);
if (PI == pmap.end()) { // Not in collection yet... insert dummy entry
// Insert a new empty element. I points to the new elements.
PI = pmap.insert(make_pair(VTy, ValueMap())).first;
assert(PI != pmap.end() && "How did insert fail?");
// Check to see if the type is abstract. If so, it might be refined in the
// future, which would cause the plane of the old type to get merged into
// a new type plane.
//
if (VTy->isAbstract()) {
cast<DerivedType>(VTy)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
std::cerr << "Added abstract type value: " << VTy->getDescription()
<< "\n";
#endif
}
}
PI->second.insert(make_pair(Name, V));
}
// insertEntry - Insert a value into the symbol table with the specified
// name...
//
void SymbolTable::insertEntry(const std::string& Name, Type* T) {
// Check to see if there is a naming conflict. If so, rename this type!
std::string UniqueName = Name;
if (lookupType(Name))
UniqueName = getUniqueName(T, Name);
#if DEBUG_SYMBOL_TABLE
dump();
std::cerr << " Inserting type: " << UniqueName << ": "
<< T->getDescription() << "\n";
#endif
// Insert the tmap entry
tmap.insert(make_pair(UniqueName, T));
// If we are adding an abstract type, add the symbol table to it's use list.
if (T->isAbstract()) {
cast<DerivedType>(T)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
std::cerr << "Added abstract type to ST: " << T->getDescription() << "\n";
#endif
}
}
// Determine how many entries for a given type.
unsigned SymbolTable::type_size(const Type *Ty) const {
plane_const_iterator PI = pmap.find(Ty);
if ( PI == pmap.end() ) return 0;
return PI->second.size();
}
// Get the name of a value
std::string SymbolTable::get_name( const Value* V ) const {
value_const_iterator VI = this->value_begin( V->getType() );
value_const_iterator VE = this->value_end( V->getType() );
// Search for the entry
while ( VI != VE && VI->second != V )
++VI;
if ( VI != VE )
return VI->first;
return "";
}
// Get the name of a type
std::string SymbolTable::get_name( const Type* T ) const {
if (tmap.empty()) return ""; // No types at all.
type_const_iterator TI = tmap.begin();
type_const_iterator TE = tmap.end();
// Search for the entry
while (TI != TE && TI->second != T )
++TI;
if (TI != TE) // Must have found an entry!
return TI->first;
return ""; // Must not have found anything...
}
// Strip the symbol table of its names.
bool SymbolTable::strip( void ) {
bool RemovedSymbol = false;
for (plane_iterator I = pmap.begin(); I != pmap.end();) {
// Removing items from the plane can cause the plane itself to get deleted.
// If this happens, make sure we incremented our plane iterator already!
ValueMap &Plane = (I++)->second;
value_iterator B = Plane.begin(), Bend = Plane.end();
while (B != Bend) { // Found nonempty type plane!
Value *V = B->second;
if (isa<Constant>(V)) {
remove(V);
RemovedSymbol = true;
} else {
if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()){
// Set name to "", removing from symbol table!
V->setName("", this);
RemovedSymbol = true;
}
}
++B;
}
}
for (type_iterator TI = tmap.begin(); TI != tmap.end(); ) {
Type* T = (TI++)->second;
remove(T);
RemovedSymbol = true;
}
return RemovedSymbol;
}
// This function is called when one of the types in the type plane are refined
void SymbolTable::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
// Search to see if we have any values of the type Oldtype. If so, we need to
// move them into the newtype plane...
plane_iterator PI = pmap.find(OldType);
if (PI != pmap.end()) {
// Get a handle to the new type plane...
plane_iterator NewTypeIt = pmap.find(NewType);
if (NewTypeIt == pmap.end()) { // If no plane exists, add one
NewTypeIt = pmap.insert(make_pair(NewType, ValueMap())).first;
if (NewType->isAbstract()) {
cast<DerivedType>(NewType)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
std::cerr << "[Added] refined to abstype: " << NewType->getDescription()
<< "\n";
#endif
}
}
ValueMap &NewPlane = NewTypeIt->second;
ValueMap &OldPlane = PI->second;
while (!OldPlane.empty()) {
std::pair<const std::string, Value*> V = *OldPlane.begin();
// Check to see if there is already a value in the symbol table that this
// would collide with.
value_iterator VI = NewPlane.find(V.first);
if (VI != NewPlane.end() && VI->second == V.second) {
// No action
} else if (VI != NewPlane.end()) {
// The only thing we are allowing for now is two external global values
// folded into one.
//
GlobalValue *ExistGV = dyn_cast<GlobalValue>(VI->second);
GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second);
if (ExistGV && NewGV) {
assert((ExistGV->isExternal() || NewGV->isExternal()) &&
"Two planes folded together with overlapping value names!");
// Make sure that ExistGV is the one we want to keep!
if (!NewGV->isExternal())
std::swap(NewGV, ExistGV);
// Ok we have two external global values. Make all uses of the new
// one use the old one...
NewGV->uncheckedReplaceAllUsesWith(ExistGV);
// Now we just convert it to an unnamed method... which won't get
// added to our symbol table. The problem is that if we call
// setName on the method that it will try to remove itself from
// the symbol table and die... because it's not in the symtab
// right now. To fix this, we have an internally consistent flag
// that turns remove into a noop. Thus the name will get null'd
// out, but the symbol table won't get upset.
//
assert(InternallyInconsistent == false &&
"Symbol table already inconsistent!");
InternallyInconsistent = true;
// Remove newM from the symtab
NewGV->setName("");
InternallyInconsistent = false;
// Now we can remove this global from the module entirely...
Module *M = NewGV->getParent();
if (Function *F = dyn_cast<Function>(NewGV))
M->getFunctionList().remove(F);
else
M->getGlobalList().remove(cast<GlobalVariable>(NewGV));
delete NewGV;
} else {
// If they are not global values, they must be just random values who
// happen to conflict now that types have been resolved. If this is
// the case, reinsert the value into the new plane, allowing it to get
// renamed.
assert(V.second->getType() == NewType &&"Type resolution is broken!");
insert(V.second);
}
} else {
insertEntry(V.first, NewType, V.second);
}
// Remove the item from the old type plane
OldPlane.erase(OldPlane.begin());
}
// Ok, now we are not referencing the type anymore... take me off your user
// list please!
#if DEBUG_ABSTYPE
std::cerr << "Removing type " << OldType->getDescription() << "\n";
#endif
OldType->removeAbstractTypeUser(this);
// Remove the plane that is no longer used
pmap.erase(PI);
}
// Loop over all of the types in the symbol table, replacing any references
// to OldType with references to NewType. Note that there may be multiple
// occurrences, and although we only need to remove one at a time, it's
// faster to remove them all in one pass.
//
for (type_iterator I = type_begin(), E = type_end(); I != E; ++I) {
if (I->second == (Type*)OldType) { // FIXME when Types aren't const.
#if DEBUG_ABSTYPE
std::cerr << "Removing type " << OldType->getDescription() << "\n";
#endif
OldType->removeAbstractTypeUser(this);
I->second = (Type*)NewType; // TODO FIXME when types aren't const
if (NewType->isAbstract()) {
#if DEBUG_ABSTYPE
std::cerr << "Added type " << NewType->getDescription() << "\n";
#endif
cast<DerivedType>(NewType)->addAbstractTypeUser(this);
}
}
}
}
// Handle situation where type becomes Concreate from Abstract
void SymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
plane_iterator PI = pmap.find(AbsTy);
// If there are any values in the symbol table of this type, then the type
// plane is a use of the abstract type which must be dropped.
if (PI != pmap.end())
AbsTy->removeAbstractTypeUser(this);
// Loop over all of the types in the symbol table, dropping any abstract
// type user entries for AbsTy which occur because there are names for the
// type.
for (type_iterator TI = type_begin(), TE = type_end(); TI != TE; ++TI)
if (TI->second == (Type*)AbsTy) // FIXME when Types aren't const.
AbsTy->removeAbstractTypeUser(this);
}
static void DumpVal(const std::pair<const std::string, Value *> &V) {
std::cerr << " '" << V.first << "' = ";
V.second->dump();
std::cerr << "\n";
}
static void DumpPlane(const std::pair<const Type *,
std::map<const std::string, Value *> >&P){
P.first->dump();
std::cerr << "\n";
for_each(P.second.begin(), P.second.end(), DumpVal);
}
static void DumpTypes(const std::pair<const std::string, Type*>& T ) {
std::cerr << " '" << T.first << "' = ";
T.second->dump();
std::cerr << "\n";
}
void SymbolTable::dump() const {
std::cerr << "Symbol table dump:\n Plane:";
for_each(pmap.begin(), pmap.end(), DumpPlane);
std::cerr << " Types: ";
for_each(tmap.begin(), tmap.end(), DumpTypes);
}
// vim: sw=2 ai
<|endoftext|> |
<commit_before>/*
*
* interval.cpp
*/
#include <iostream>
#include <utility>
// Include the prototype of the Interval Tree class
#include "interval.h"
using namespace std;
#define INF 1000000000
// Definition of the functions of Interval Class
// Constructor
Interval::Interval()
{
root = NULL;
}
// Insert an interval
void Interval::insert(int l, int r)
{
node *temp = this->insert_helper(root, l, r);
return;
}
// Recursively traverse and insert an interval
node * Interval::insert_helper(node *current, int l, int r)
{
if (current == NULL)
return new node(l, r);
if (l < current->r.first)
current->left = insert_helper(current->left, l, r);
else
current->right = insert_helper(current->right, l, r);
if (current->max_right < r)
current->max_right = r;
return current;
}
// Search for an interval
range Interval::search(int l, int r)
{
return this->search_helper(root, l, r);
}
// Recursively traverse and search for an interval
range Interval::search_helper(node *current, int l, int r)
{
if(current == NULL)
{
return range(INF, INF);
}
if(current->overlap(l, r))
{
return current->r;
}
if(current->left != NULL && current->left->max_right >= l)
return this->search_helper(current->left, l, r);
return this->search_helper(current->right, l, r);
}
// Remove an interval
void Interval::remove(int l, int r)
{
node *temp = this->remove_helper(root, l, r);
}
// Recursively search and remove that interval
node * Interval::remove_helper(node *current, int l, int r)
{
if(current == NULL) return NULL;
if(current->r.first > l)
{
current->left = this->remove_helper(current->left, l, r);
}
else if(current->r.first < l)
{
current->right = this->remove_helper(current->right, l, r);
}
else
{
// If only 1 or 0 child
if(current->left == NULL)
{
node * temp = current->right;
delete current;
return temp;
}
else if(current->right = NULL)
{
node * temp = current->left;
delete current;
return temp;
}
// Left most node in the right subtree should replace this node
node * temp = current->right;
while(temp->left != NULL)
{
temp = temp->left;
}
// Remove the replaced node
current->r = temp->r;
current->right = this->remove_helper(current->right, l, r);
}
// Update max_right in this subtree
current = update_max(current);
return current;
}
// Helper Function
node * Interval::update_max(node *current)
{
if(current == NULL) return NULL;
this->update_max(current->left);
this->update_max(current->right);
if(current->right != NULL)
{
if(current->left != NULL)
{
current->max_right = max(current->r.second, max(current->left->max_right, current->right->max_right));
}
else
{
current->max_right = max(current->r.second, current->right->max_right);
}
}
else
{
if(current->left != NULL)
{
current->max_right = max(current->r.second, current->left->max_right);
}
else
{
current->max_right = current->r.second;
}
}
return current;
}
int main()
{
//Code
Interval tree;
// Insert some dummy intervals
tree.insert(5, 6);
tree.insert(5, 10);
tree.insert(1, 6);
tree.insert(15, 20);
tree.insert(0, 2);
// Search for an interval
range r = tree.search(1,10);
cout << r.first << " " << r.second << endl;
// Remove an interval
tree.remove(1,10);
// Search for the removed interval
r = tree.search(1,10);
cout << r.first << " " << r.second << endl;
return 0;
}<commit_msg>Bug Fix #1<commit_after>/*
*
* interval.cpp
*/
#include <iostream>
#include <utility>
// Include the prototype of the Interval Tree class
#include "interval.h"
using namespace std;
#define INF 1000000000
// Definition of the functions of Interval Class
// Constructor
Interval::Interval()
{
root = NULL;
}
// Insert an interval
void Interval::insert(int l, int r)
{
root = this->insert_helper(root, l, r);
return;
}
// Recursively traverse and insert an interval
node * Interval::insert_helper(node *current, int l, int r)
{
if (current == NULL)
return new node(l, r);
if (l < current->r.first)
current->left = insert_helper(current->left, l, r);
else
current->right = insert_helper(current->right, l, r);
if (current->max_right < r)
current->max_right = r;
return current;
}
// Search for an interval
range Interval::search(int l, int r)
{
return this->search_helper(root, l, r);
}
// Recursively traverse and search for an interval
range Interval::search_helper(node *current, int l, int r)
{
if(current == NULL)
{
return range(INF, INF);
}
if(current->overlap(l, r))
{
return current->r;
}
if(current->left != NULL && current->left->max_right >= l)
return this->search_helper(current->left, l, r);
return this->search_helper(current->right, l, r);
}
// Remove an interval
void Interval::remove(int l, int r)
{
root = this->remove_helper(root, l, r);
}
// Recursively search and remove that interval
node * Interval::remove_helper(node *current, int l, int r)
{
if(current == NULL) return NULL;
if(current->r.first > l)
{
current->left = this->remove_helper(current->left, l, r);
}
else if(current->r.first < l)
{
current->right = this->remove_helper(current->right, l, r);
}
else
{
// If only 1 or 0 child
if(current->left == NULL)
{
node * temp = current->right;
delete current;
return temp;
}
else if(current->right == NULL)
{
node * temp = current->left;
delete current;
return temp;
}
// Left most node in the right subtree should replace this node
node * temp = current->right;
while(temp->left != NULL)
{
temp = temp->left;
}
// Remove the replaced node
current->r = temp->r;
current->right = this->remove_helper(current->right, l, r);
}
// Update max_right in this subtree
current = update_max(current);
return current;
}
// Helper Function
node * Interval::update_max(node *current)
{
if(current == NULL) return NULL;
this->update_max(current->left);
this->update_max(current->right);
if(current->right != NULL)
{
if(current->left != NULL)
{
current->max_right = max(current->r.second, max(current->left->max_right, current->right->max_right));
}
else
{
current->max_right = max(current->r.second, current->right->max_right);
}
}
else
{
if(current->left != NULL)
{
current->max_right = max(current->r.second, current->left->max_right);
}
else
{
current->max_right = current->r.second;
}
}
return current;
}
int main()
{
//Code
Interval tree;
// Insert some dummy intervals
tree.insert(5, 6);
tree.insert(5, 10);
tree.insert(1, 6);
tree.insert(15, 20);
tree.insert(0, 2);
// Search for an interval
range r = tree.search(5,6);
cout << r.first << " " << r.second << endl;
// Remove an interval
tree.remove(5,6);
// Search for the removed interval
r = tree.search(5,6);
cout << r.first << " " << r.second << endl;
return 0;
}<|endoftext|> |
<commit_before>#include "Detour.h"
XHACKING_START_NAMESPACE
LONG WINAPI EHandler(EXCEPTION_POINTERS* /*ExceptionInfo*/);
bool EHApplied = false;
std::vector<Detour_i*> EHandlers;
Detour_i::Detour_i(BYTE* src, BYTE* dst, BYTE arguments) :
_src(src),
_dst(dst),
_arguments(arguments),
_withTrampoline(false),
_detourlen(0),
_type(DETOUR_JMP)
{}
BYTE Detour_i::MinLength()
{
switch (_type)
{
case DETOUR_JMP: return 5;
case DETOUR_RET: return 6;
case DETOUR_MEM: return 0;
default: return 0;
}
}
BYTE Detour_i::FillByType(BYTE* src, BYTE* dst)
{
switch (_type)
{
case DETOUR_JMP:
*(BYTE*)(src + 0) = 0xE9;
*(DWORD*)(src + 1) = (DWORD)(dst - src) - 5;
break;
case DETOUR_JMP_EAX:
*(BYTE*)(src + 0) = 0xB8;
*(DWORD*)(src + 1) = (DWORD)(dst);
*(WORD*)(src + 5) = 0xE0FF;
break;
case DETOUR_RET:
*(BYTE*)(src + 0) = 0x68;
*(DWORD*)(src + 1) = (DWORD)(dst);
*(BYTE*)(src + 5) = 0xC3;
break;
default:
break;
}
return MinLength();
}
BYTE* Detour_i::CreateTrampoline()
{
BYTE retlen = MinLength();
BYTE* trampoline = (BYTE*)malloc(4 + (_arguments * 4) + 5 + 2 + _detourlen + retlen);
if (!trampoline)
return false;
// PUSH EBP
// MOV EBP, ESP
// PUSH EAX
// FIXME: Is it really worth saving EAX?
*(BYTE*)(trampoline + 0) = 0x55;
*(WORD*)(trampoline + 1) = 0xEC8B;
*(BYTE*)(trampoline + 3) = 0x50;
trampoline += 4;
BYTE offset = _arguments * 4 + 4; // +3 (mov eax, []) + 1 (push eax) = +4
for (BYTE i = 0; i < _arguments; i++)
{
// MOV EAX, [EBP + (numarguments - i)*4]
*(WORD*)(trampoline + 0) = 0x458B;
*(BYTE*)(trampoline + 2) = offset;
// PUSH EAX
*(BYTE*)(trampoline + 3) = 0x50;
trampoline += 4;
offset -= 4;
}
// call dst
*(BYTE*)(trampoline + 0) = 0xE8;
*(DWORD*)(trampoline + 1) = (DWORD)(_dst - trampoline) - 5;
trampoline += 5;
// POP EAX
// POP EBP
*(BYTE*)(trampoline + 0) = 0x58;
*(BYTE*)(trampoline + 1) = 0x5D;
trampoline += 2;
// src bytes (detourlen)
memcpy(trampoline, _src, _detourlen);
trampoline += _detourlen;
// jmp src + len (retlen)
FillByType(trampoline, _src + _detourlen);
return (trampoline - _detourlen - 2 - 5 - (_arguments * 4) - 4);
}
BYTE* Detour_i::CreateHook()
{
BYTE* jump = (BYTE*)malloc(_detourlen + 5);
if (!jump)
return NULL;
memcpy(jump, _src, _detourlen);
jump += _detourlen;
// jmp back
jump[0] = 0xE9;
*(DWORD*)(jump + 1) = (DWORD)(_src + _detourlen - (DWORD)jump) - 5;
return jump - _detourlen;
}
bool Detour_i::Commit()
{
// MEM Detour!
if (_type == DETOUR_MEM)
{
DWORD old;
MEMORY_BASIC_INFORMATION meminfo;
VirtualQuery(_src, &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
if (!VirtualProtect(meminfo.BaseAddress, meminfo.RegionSize, meminfo.AllocationProtect | PAGE_GUARD, &old))
{
NAMESPACE::SetLastError(DETOUR_VIRTUAL_PROTECT_ERROR);
return false;
}
if (!EHApplied)
{
if (!AddVectoredExceptionHandler(1, EHandler) && !SetUnhandledExceptionFilter(EHandler))
{
NAMESPACE::SetLastError(DETOUR_VEH_ERROR);
return false;
}
EHApplied = true;
}
EHandlers.push_back(this);
return true;
}
// ASM Detour
if (!_detourlen)
_detourlen = MinLength();
else if (_detourlen < MinLength())
{
NAMESPACE::SetLastError(DETOUR_LENGTH_ERROR);
return false;
}
BYTE* hook = _withTrampoline ? CreateTrampoline() : CreateHook();
if (!hook)
{
NAMESPACE::SetLastError(DETOUR_MALLOC_ERROR);
return false;
}
DWORD old;
VirtualProtect(_src, _detourlen, PAGE_READWRITE, &old);
memset(_src, 0x90, _detourlen);
BYTE* dst = _dst;
if (_withTrampoline)
dst = hook;
FillByType(_src, dst);
// Allows calling in non trampoline environments, and code restoring
_callee = hook;
VirtualProtect(_src, _detourlen, old, &old);
return true;
}
bool Detour_i::Restore()
{
switch (_type)
{
case DETOUR_MEM:
{
DWORD old;
MEMORY_BASIC_INFORMATION meminfo;
VirtualQuery(_src, &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
if (!VirtualProtect(meminfo.BaseAddress, meminfo.RegionSize, meminfo.AllocationProtect & ~PAGE_GUARD, &old))
{
NAMESPACE::SetLastError(DETOUR_RESTORE_VP_ERROR);
return false;
}
EHandlers.erase(std::find(EHandlers.begin(), EHandlers.end(), this));
return true;
}
case DETOUR_JMP:
case DETOUR_RET:
{
DWORD old;
VirtualProtect(_src, _detourlen, PAGE_READWRITE, &old);
BYTE* dst = _callee;
if (_withTrampoline)
{
dst += 4 + (_arguments * 4) + 5 + 2;
}
memcpy(_src, dst, _detourlen);
VirtualProtect(_src, _detourlen, old, &old);
return true;
}
}
return false;
}
LONG WINAPI EHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) {
std::vector<Detour_i*>::iterator it = EHandlers.begin();
for (; it != EHandlers.end(); it++)
{
Detour_i* detour = *it;
if ((DWORD)ExceptionInfo->ExceptionRecord->ExceptionAddress == (DWORD)detour->getSource())
{
// We are going to force a call to our "detour" function
// That is, saving EBP (avoid messing up), pushing parameters, and calling
// Inline asm requieres DWORDS for calls/movs
DWORD offs = detour->getArguments() * 4 + 4;
DWORD dest = (DWORD)detour->getDest();
DWORD oEBP = 0;
// Save EBP (just in case)
__asm MOV oEBP, EBP
// Push parameters
for (int i = 0; i < detour->getArguments(); i++)
{
DWORD param = *(DWORD*)(ExceptionInfo->ContextRecord->Ebp + offs);
offs -= 4;
__asm PUSH param;
}
// Call dest
__asm MOV EAX, dest
__asm CALL EAX
// Restore EBP
__asm MOV EBP, oEBP
}
ExceptionInfo->ContextRecord->EFlags |= 0x100;
}
return EXCEPTION_CONTINUE_EXECUTION;
}
else if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP)
{
// TODO: We should avoid iterating all over the handlers, and use some kind of callback-structure to determine which address is to be protected
// TODO: VirtualQuery should not be done everytime, it should be saved in a structure (alonside with above) on detour/breakpoint creation
std::vector<Detour_i*>::iterator it = EHandlers.begin();
for (; it != EHandlers.end(); it++)
{
Detour_i* detour = *it;
DWORD old;
MEMORY_BASIC_INFORMATION meminfo;
VirtualQuery(detour->getSource(), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
VirtualProtect(meminfo.BaseAddress, meminfo.RegionSize, meminfo.AllocationProtect | PAGE_GUARD, &old);
}
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
XHACKING_END_NAMESPACE<commit_msg>Detour: Added missing code from last commit. Length was 7<commit_after>#include "Detour.h"
XHACKING_START_NAMESPACE
LONG WINAPI EHandler(EXCEPTION_POINTERS* /*ExceptionInfo*/);
bool EHApplied = false;
std::vector<Detour_i*> EHandlers;
Detour_i::Detour_i(BYTE* src, BYTE* dst, BYTE arguments) :
_src(src),
_dst(dst),
_arguments(arguments),
_withTrampoline(false),
_detourlen(0),
_type(DETOUR_JMP)
{}
BYTE Detour_i::MinLength()
{
switch (_type)
{
case DETOUR_JMP: return 5;
case DETOUR_JMP_EAX: return 7;
case DETOUR_RET: return 6;
case DETOUR_MEM: return 0;
default: return 0;
}
}
BYTE Detour_i::FillByType(BYTE* src, BYTE* dst)
{
switch (_type)
{
case DETOUR_JMP:
*(BYTE*)(src + 0) = 0xE9;
*(DWORD*)(src + 1) = (DWORD)(dst - src) - 5;
break;
case DETOUR_JMP_EAX:
*(BYTE*)(src + 0) = 0xB8;
*(DWORD*)(src + 1) = (DWORD)(dst);
*(WORD*)(src + 5) = 0xE0FF;
break;
case DETOUR_RET:
*(BYTE*)(src + 0) = 0x68;
*(DWORD*)(src + 1) = (DWORD)(dst);
*(BYTE*)(src + 5) = 0xC3;
break;
default:
break;
}
return MinLength();
}
BYTE* Detour_i::CreateTrampoline()
{
BYTE retlen = MinLength();
BYTE* trampoline = (BYTE*)malloc(4 + (_arguments * 4) + 5 + 2 + _detourlen + retlen);
if (!trampoline)
return false;
// PUSH EBP
// MOV EBP, ESP
// PUSH EAX
// FIXME: Is it really worth saving EAX?
*(BYTE*)(trampoline + 0) = 0x55;
*(WORD*)(trampoline + 1) = 0xEC8B;
*(BYTE*)(trampoline + 3) = 0x50;
trampoline += 4;
BYTE offset = _arguments * 4 + 4; // +3 (mov eax, []) + 1 (push eax) = +4
for (BYTE i = 0; i < _arguments; i++)
{
// MOV EAX, [EBP + (numarguments - i)*4]
*(WORD*)(trampoline + 0) = 0x458B;
*(BYTE*)(trampoline + 2) = offset;
// PUSH EAX
*(BYTE*)(trampoline + 3) = 0x50;
trampoline += 4;
offset -= 4;
}
// call dst
*(BYTE*)(trampoline + 0) = 0xE8;
*(DWORD*)(trampoline + 1) = (DWORD)(_dst - trampoline) - 5;
trampoline += 5;
// POP EAX
// POP EBP
*(BYTE*)(trampoline + 0) = 0x58;
*(BYTE*)(trampoline + 1) = 0x5D;
trampoline += 2;
// src bytes (detourlen)
memcpy(trampoline, _src, _detourlen);
trampoline += _detourlen;
// jmp src + len (retlen)
FillByType(trampoline, _src + _detourlen);
return (trampoline - _detourlen - 2 - 5 - (_arguments * 4) - 4);
}
BYTE* Detour_i::CreateHook()
{
BYTE* jump = (BYTE*)malloc(_detourlen + 5);
if (!jump)
return NULL;
memcpy(jump, _src, _detourlen);
jump += _detourlen;
// jmp back
jump[0] = 0xE9;
*(DWORD*)(jump + 1) = (DWORD)(_src + _detourlen - (DWORD)jump) - 5;
return jump - _detourlen;
}
bool Detour_i::Commit()
{
// MEM Detour!
if (_type == DETOUR_MEM)
{
DWORD old;
MEMORY_BASIC_INFORMATION meminfo;
VirtualQuery(_src, &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
if (!VirtualProtect(meminfo.BaseAddress, meminfo.RegionSize, meminfo.AllocationProtect | PAGE_GUARD, &old))
{
NAMESPACE::SetLastError(DETOUR_VIRTUAL_PROTECT_ERROR);
return false;
}
if (!EHApplied)
{
if (!AddVectoredExceptionHandler(1, EHandler) && !SetUnhandledExceptionFilter(EHandler))
{
NAMESPACE::SetLastError(DETOUR_VEH_ERROR);
return false;
}
EHApplied = true;
}
EHandlers.push_back(this);
return true;
}
// ASM Detour
if (!_detourlen)
_detourlen = MinLength();
else if (_detourlen < MinLength())
{
NAMESPACE::SetLastError(DETOUR_LENGTH_ERROR);
return false;
}
BYTE* hook = _withTrampoline ? CreateTrampoline() : CreateHook();
if (!hook)
{
NAMESPACE::SetLastError(DETOUR_MALLOC_ERROR);
return false;
}
DWORD old;
VirtualProtect(_src, _detourlen, PAGE_READWRITE, &old);
memset(_src, 0x90, _detourlen);
BYTE* dst = _dst;
if (_withTrampoline)
dst = hook;
FillByType(_src, dst);
// Allows calling in non trampoline environments, and code restoring
_callee = hook;
VirtualProtect(_src, _detourlen, old, &old);
return true;
}
bool Detour_i::Restore()
{
switch (_type)
{
case DETOUR_MEM:
{
DWORD old;
MEMORY_BASIC_INFORMATION meminfo;
VirtualQuery(_src, &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
if (!VirtualProtect(meminfo.BaseAddress, meminfo.RegionSize, meminfo.AllocationProtect & ~PAGE_GUARD, &old))
{
NAMESPACE::SetLastError(DETOUR_RESTORE_VP_ERROR);
return false;
}
EHandlers.erase(std::find(EHandlers.begin(), EHandlers.end(), this));
return true;
}
case DETOUR_JMP:
case DETOUR_RET:
{
DWORD old;
VirtualProtect(_src, _detourlen, PAGE_READWRITE, &old);
BYTE* dst = _callee;
if (_withTrampoline)
{
dst += 4 + (_arguments * 4) + 5 + 2;
}
memcpy(_src, dst, _detourlen);
VirtualProtect(_src, _detourlen, old, &old);
return true;
}
}
return false;
}
LONG WINAPI EHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) {
std::vector<Detour_i*>::iterator it = EHandlers.begin();
for (; it != EHandlers.end(); it++)
{
Detour_i* detour = *it;
if ((DWORD)ExceptionInfo->ExceptionRecord->ExceptionAddress == (DWORD)detour->getSource())
{
// We are going to force a call to our "detour" function
// That is, saving EBP (avoid messing up), pushing parameters, and calling
// Inline asm requieres DWORDS for calls/movs
DWORD offs = detour->getArguments() * 4 + 4;
DWORD dest = (DWORD)detour->getDest();
DWORD oEBP = 0;
// Save EBP (just in case)
__asm MOV oEBP, EBP
// Push parameters
for (int i = 0; i < detour->getArguments(); i++)
{
DWORD param = *(DWORD*)(ExceptionInfo->ContextRecord->Ebp + offs);
offs -= 4;
__asm PUSH param;
}
// Call dest
__asm MOV EAX, dest
__asm CALL EAX
// Restore EBP
__asm MOV EBP, oEBP
}
ExceptionInfo->ContextRecord->EFlags |= 0x100;
}
return EXCEPTION_CONTINUE_EXECUTION;
}
else if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP)
{
// TODO: We should avoid iterating all over the handlers, and use some kind of callback-structure to determine which address is to be protected
// TODO: VirtualQuery should not be done everytime, it should be saved in a structure (alonside with above) on detour/breakpoint creation
std::vector<Detour_i*>::iterator it = EHandlers.begin();
for (; it != EHandlers.end(); it++)
{
Detour_i* detour = *it;
DWORD old;
MEMORY_BASIC_INFORMATION meminfo;
VirtualQuery(detour->getSource(), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
VirtualProtect(meminfo.BaseAddress, meminfo.RegionSize, meminfo.AllocationProtect | PAGE_GUARD, &old);
}
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
XHACKING_END_NAMESPACE<|endoftext|> |
<commit_before>/***********************************************************************
dummy.cpp - Exists solely to fix a problem with Visual Studio: it won't
show the C/C++ project settings unless there is a *.cpp file in the
project. Rather than rename all the *.cc files, I'm just adding
this to the projects for now.
***********************************************************************/<commit_msg>No longer needed.<commit_after><|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: surfaceProcessor.C,v 1.6 2002/12/20 14:01:45 oliver Exp $
#include <BALL/STRUCTURE/surfaceProcessor.h>
namespace BALL
{
SurfaceProcessor::SurfaceProcessor()
: ses_(true),
surface_(),
spheres_(),
density_(4.5),
probe_radius_(1.5),
radius_offset_(0.0),
vdw_factor_(1.0)
{
}
bool SurfaceProcessor::start()
{
spheres_.clear();
return true;
}
Processor::Result SurfaceProcessor::operator () (Atom& atom)
{
Vector3 float_position(atom.getPosition());
TVector3<double> position((double)float_position.x,
(double)float_position.y,
(double)float_position.z);
if (atom.getElement() != Element::UNKNOWN)
{
if (atom.getElement().getVanDerWaalsRadius() > 0.0)
{
spheres_.push_back(TSphere3<double>(position, vdw_factor_*atom.getElement().getVanDerWaalsRadius() + radius_offset_));
}
else
{
spheres_.push_back(TSphere3<double>(position, radius_offset_+vdw_factor_));
}
}
else
{
spheres_.push_back(TSphere3<double>(position, radius_offset_+vdw_factor_));
}
return Processor::CONTINUE;
}
bool SurfaceProcessor::finish()
{
ReducedSurface* reduced_surface = new ReducedSurface(spheres_,probe_radius_);
reduced_surface->compute();
if (ses_)
{
SolventExcludedSurface* ses = new SolventExcludedSurface(reduced_surface);
ses->compute();
double diff = (probe_radius_ < 1.5 ? 0.1 : -0.1);
int i = 0;
bool ok = false;
while (!ok && (i < 10))
{
i++;
ok = ses->check();
if (!ok)
{
delete ses;
delete reduced_surface;
probe_radius_ += diff;
reduced_surface = new ReducedSurface(spheres_,probe_radius_);
reduced_surface->compute();
ses = new SolventExcludedSurface(reduced_surface);
ses->compute();
}
}
if (ok)
{
TriangulatedSES* surface = new TriangulatedSES(ses,density_);
surface->compute();
surface->exportSurface(surface_);
delete surface;
}
delete ses;
}
else
{
SolventAccessibleSurface* sas = new SolventAccessibleSurface(reduced_surface);
sas->compute();
TriangulatedSAS* surface = new TriangulatedSAS(sas,density_);
surface->compute();
surface->exportSurface(surface_);
delete surface;
delete sas;
}
delete reduced_surface;
return true;
}
const Surface& SurfaceProcessor::getSurface() const
{
return surface_;
}
void SurfaceProcessor::getSurface(Surface& surface) const
{
surface = surface_;
}
void SurfaceProcessor::setProbeRadius(double radius)
{
probe_radius_ = radius;
}
double SurfaceProcessor::getProbeRadius()
{
return probe_radius_;
}
void SurfaceProcessor::setDensity(double density)
{
density_ = density;
}
double SurfaceProcessor::getDensity()
{
return density_;
}
vector< TSphere3<double> >& SurfaceProcessor::getSpheres()
{
return spheres_;
}
} // namespace
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: surfaceProcessor.C,v 1.7 2003/02/19 16:15:39 amoll Exp $
#include <BALL/STRUCTURE/surfaceProcessor.h>
namespace BALL
{
SurfaceProcessor::SurfaceProcessor()
: UnaryProcessor<Atom>(),
UnaryProcessor<Atom*>(),
radius_offset_(0.0),
vdw_factor_(1.0),
ses_(true),
surface_(),
spheres_(),
density_(4.5),
probe_radius_(1.5)
{
}
bool SurfaceProcessor::start()
{
spheres_.clear();
return true;
}
Processor::Result SurfaceProcessor::operator () (Atom& atom)
{
TVector3<double> position((double)atom.getPosition().x,
(double)atom.getPosition().y,
(double)atom.getPosition().z);
if (atom.getElement() != Element::UNKNOWN && atom.getElement().getVanDerWaalsRadius() > 0.0)
{
spheres_.push_back(TSphere3<double>(position, vdw_factor_*atom.getElement().getVanDerWaalsRadius() + radius_offset_));
}
else
{
spheres_.push_back(TSphere3<double>(position, radius_offset_+vdw_factor_));
}
return Processor::CONTINUE;
}
bool SurfaceProcessor::finish()
{
if (spheres_.size() == 0)
{
Log.error() << "empty surface" << std::endl;
return true;
}
ReducedSurface* reduced_surface = new ReducedSurface(spheres_,probe_radius_);
reduced_surface->compute();
if (ses_)
{
SolventExcludedSurface* ses = new SolventExcludedSurface(reduced_surface);
ses->compute();
double diff = (probe_radius_ < 1.5 ? 0.1 : -0.1);
int i = 0;
bool ok = false;
while (!ok && (i < 10))
{
i++;
ok = ses->check();
if (!ok)
{
delete ses;
delete reduced_surface;
probe_radius_ += diff;
reduced_surface = new ReducedSurface(spheres_,probe_radius_);
reduced_surface->compute();
ses = new SolventExcludedSurface(reduced_surface);
ses->compute();
}
}
if (ok)
{
TriangulatedSES* surface = new TriangulatedSES(ses,density_);
surface->compute();
surface->exportSurface(surface_);
delete surface;
}
delete ses;
}
else
{
SolventAccessibleSurface* sas = new SolventAccessibleSurface(reduced_surface);
sas->compute();
TriangulatedSAS* surface = new TriangulatedSAS(sas,density_);
surface->compute();
surface->exportSurface(surface_);
delete surface;
delete sas;
}
delete reduced_surface;
return true;
}
const Surface& SurfaceProcessor::getSurface() const
{
return surface_;
}
void SurfaceProcessor::getSurface(Surface& surface) const
{
surface = surface_;
}
void SurfaceProcessor::setProbeRadius(double radius)
{
probe_radius_ = radius;
}
double SurfaceProcessor::getProbeRadius()
{
return probe_radius_;
}
void SurfaceProcessor::setDensity(double density)
{
density_ = density;
}
double SurfaceProcessor::getDensity()
{
return density_;
}
vector<TSphere3<double> >& SurfaceProcessor::getSpheres()
{
return spheres_;
}
} // namespace
<|endoftext|> |
<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
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 <algorithm>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "mlir-hlo/Dialect/lhlo/IR/lhlo_ops.h"
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "mlir-hlo/Transforms/GPUPassDetail.h"
#include "mlir-hlo/Transforms/gpu_passes.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/IR/Visitors.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Rewrite/FrozenRewritePatternSet.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/RegionUtils.h"
namespace mlir {
namespace {
class GpuFusionRewritePass
: public GpuFusionRewritePassBase<GpuFusionRewritePass> {
public:
explicit GpuFusionRewritePass() = default;
using Pass::runPipeline; // Give FusionRewritePattern access.
private:
void getDependentDialects(DialectRegistry& registry) const override;
void runOnOperation() override;
};
// Rewrites `lmhlo.fusion` to `gpu.launch_func` for fusion regions that the
// HLO to GPU pipeline can handle.
class FusionRewritePattern : public OpRewritePattern<lmhlo::FusionOp> {
public:
explicit FusionRewritePattern(MLIRContext* ctx,
GpuFusionRewritePass& parentPass,
SymbolTable& symbolTable);
private:
LogicalResult matchAndRewrite(lmhlo::FusionOp fusionOp,
PatternRewriter& rewriter) const override;
// Returns whether all ops in fusionOp's region are legal to rewritableTarget.
bool isRewritable(lmhlo::FusionOp fusionOp) const;
// Annotates gpu.launch_func with attribute specifying written operands.
//
// gpu.launch_func ..., %memref, ...
// %tensor = bufferize.to_tensor %memref
// memref.tensor_store %tensor, %argN
//
// is replaced with:
//
// gpu.launch_func ..., %argN, ... { written_operands = [..., unit, ...] }
//
// The 'written_operands' attribute is used later to retrieve which
// gpu.launch_func arguments are written vs. just read.
static void annotateLaunchFunc(func::FuncOp funcOp,
PatternRewriter& rewriter);
// Returns target where lowerable fusion ops are marked legal.
static ConversionTarget getRewritableTarget(MLIRContext* ctx);
GpuFusionRewritePass& parentPass;
SymbolTable& symbolTable;
ConversionTarget rewritableTarget = getRewritableTarget(getContext());
};
} // namespace
// Name of the 'gpu.launch_func' attribute which specifies the written operands.
static constexpr llvm::StringLiteral kWrittenOperandsAttrName =
"written_operands";
void GpuFusionRewritePass::getDependentDialects(
DialectRegistry& registry) const {
OpPassManager passManager;
createHloToGpuPipeline(passManager, /*tileSizes=*/{}, /*unrollFactors=*/{});
passManager.getDependentDialects(registry);
}
void GpuFusionRewritePass::runOnOperation() {
SymbolTable symbolTable(getOperation());
auto pattern =
std::make_unique<FusionRewritePattern>(&getContext(), *this, symbolTable);
mlir::FrozenRewritePatternSet patterns({&getContext(), std::move(pattern)});
auto callback = [&](lmhlo::FusionOp fusion) {
if (failed(applyOpPatternsAndFold(fusion, patterns)))
return WalkResult::interrupt();
return WalkResult::advance();
};
if (getOperation().walk(callback).wasInterrupted())
return signalPassFailure();
}
FusionRewritePattern::FusionRewritePattern(MLIRContext* ctx,
GpuFusionRewritePass& parentPass,
SymbolTable& symbolTable)
: OpRewritePattern<lmhlo::FusionOp>::OpRewritePattern(ctx),
parentPass(parentPass),
symbolTable(symbolTable) {}
// Returns the number of elements each thread should handle for 'type'.
// The intention is that loads and stores are vectorized later on to this width
// to maximize memory throughput.
static int64_t getElementsPerThread(TensorType type) {
// Don't vectorize if the number of elements cannot saturate the GPU.
// Use a coarse heuristic because we don't know the target GPU here.
const int64_t kNumFp32AlusOnV100 = 5376;
if (type.getNumElements() < kNumFp32AlusOnV100) return 1;
// Vectorize so that loads and stores are 128 bits per thread.
if (type.getElementType().isIntOrFloat())
return 128 / type.getElementType().getIntOrFloatBitWidth();
return 1; // Default to no vectorization.
}
// Returns the number of threads per block to use for 'type', given the number
// of elements each thread handles. The returned block size is in the [128, 384]
// range, preferrably close to 256 and evenly dividing the number of threads
// required to handle all elements in 'type'.
static int64_t getThreadsPerBlock(TensorType type, int64_t elementsPerThread) {
int64_t numThreads =
llvm::divideCeil(type.getNumElements(), elementsPerThread);
// Use a single block for small problems.
if (numThreads < 256) return numThreads;
// Use 256 if that block size evenly divides the problem.
if (numThreads % 256 == 0) return 256;
int64_t elementSizeBits = 32;
if (type.getElementType().isIntOrFloat())
elementSizeBits = type.getElementType().getIntOrFloatBitWidth();
int64_t threadSizeBits = elementSizeBits * elementsPerThread;
// Search block sizes in the [128, 384] range near 256 with decreasing
// power-of-2 factor, down to a multiple of a cache line (assumed to be 1024
// bits). Use the first one that evenly divides the problem, which allows the
// loop tail to be optimized away.
for (int i = 128; i * threadSizeBits >= 1024; i /= 2) {
// 2 * i: earlier iterations already handled even multiples of i.
for (int blockSize = 256 - i; blockSize >= 128; blockSize -= 2 * i)
if (numThreads % blockSize == 0) return blockSize;
for (int blockSize = 256 + i; blockSize <= 384; blockSize += 2 * i)
if (numThreads % blockSize == 0) return blockSize;
}
// None of the checked block sizes evenly divides the number of required
// threads. Use a default of 256 and accept the loop tail.
return 256;
}
LogicalResult FusionRewritePattern::matchAndRewrite(
lmhlo::FusionOp fusionOp, PatternRewriter& rewriter) const {
// If fusion_op (including its region) is not legal by rewriteable_target,
// we expect lowering to GPU to fail or produce incorrect results.
if (!isRewritable(fusionOp))
return rewriter.notifyMatchFailure(fusionOp, "not rewritable");
auto storeOps = fusionOp.getBody()->getOps<memref::TensorStoreOp>();
if (storeOps.empty())
return rewriter.notifyMatchFailure(fusionOp, "no memref.tensor_store ops");
// Collect values in fusion region defined above.
SetVector<Value> captures;
getUsedValuesDefinedAbove(fusionOp->getRegions(), captures);
// Converts statically shaped types to their 1D equivalent. This only works
// for element wise fusions and will have to become a more sophisticated
// pass when e.g. broadcasts are involved.
TypeConverter converter;
converter.addConversion([](Type type) { return type; });
converter.addConversion([](ShapedType type) {
if (!type.hasStaticShape()) return type;
return type.clone(type.getNumElements());
});
converter.addConversion([&](MemRefType type) {
if (!type.hasStaticShape() || !type.getLayout().isIdentity()) return type;
return MemRefType::get(type.getNumElements(), type.getElementType(),
MemRefLayoutAttrInterface(), type.getMemorySpace());
});
// Create a new module with a function, clone fusion region into it.
Location loc = fusionOp.getLoc();
auto moduleOp = rewriter.create<ModuleOp>(loc);
rewriter.setInsertionPointToEnd(moduleOp.getBody());
auto argTypes = llvm::to_vector(llvm::map_range(captures, [&](Value value) {
return converter.convertType(value.getType());
}));
auto funcType = rewriter.getFunctionType(argTypes, llvm::None);
auto funcOp = rewriter.create<func::FuncOp>(loc, "fusion", funcType);
rewriter.setInsertionPointToEnd(funcOp.addEntryBlock());
BlockAndValueMapping mapping;
for (const auto& [from, to] :
llvm::zip_first(captures, funcOp.getArguments())) {
mapping.map(from, to);
}
rewriter.cloneRegionBefore(fusionOp.getRegion(), funcOp.getRegion(),
funcOp.end(), mapping);
rewriter.mergeBlocks(&funcOp.back(), &funcOp.front());
funcOp->walk([&](Operation* op) {
for (auto result : op->getResults())
result.setType(converter.convertType(result.getType()));
});
// Create and run the HLO to GPU pass pipeline.
auto resultType = (*storeOps.begin()).tensor().getType().cast<TensorType>();
int64_t unrollFactor = getElementsPerThread(resultType);
int64_t tileSize = getThreadsPerBlock(resultType, unrollFactor);
// Note: passManager.enableIRPrinting() doesn't do anything on dynamic pass
// pipelines. Printing needs to be enabled on the parent pass manager.
PassManager passManager(getContext());
createHloToGpuPipeline(passManager, {tileSize},
{&unrollFactor, unrollFactor > 1});
if (failed(parentPass.runPipeline(passManager, moduleOp)))
return rewriter.notifyMatchFailure(fusionOp, "failed to run pipeline");
// Clone the (single) gpu module with the device function.
rewriter.setInsertionPoint(fusionOp->getParentOfType<func::FuncOp>());
for (auto gpuModuleOp : moduleOp.getBodyRegion().getOps<gpu::GPUModuleOp>()) {
StringAttr symbol =
symbolTable.insert(rewriter.clone(*gpuModuleOp.getOperation()));
if (failed(symbolTable.replaceAllSymbolUses(gpuModuleOp, symbol, funcOp)))
return rewriter.notifyMatchFailure(fusionOp, "failed to replace symbol");
}
// Add 'gpu.container_module' attribute to parent module.
fusionOp->getParentOfType<ModuleOp>()->setAttr(
gpu::GPUDialect::getContainerModuleAttrName(), rewriter.getUnitAttr());
// Annotate gpu.launch_func loc and attribute specifying written operands.
funcOp->walk([&](gpu::LaunchFuncOp op) { op->setLoc(loc); });
annotateLaunchFunc(funcOp, rewriter);
// Remove dead allocations that were only used by store_op erased above.
RewritePatternSet patterns(getContext());
memref::AllocOp::getCanonicalizationPatterns(patterns, getContext());
if (failed(applyPatternsAndFoldGreedily(funcOp, std::move(patterns))))
return rewriter.notifyMatchFailure(fusionOp, "failed to canonicalize");
// Replace fusion op with host function region.
rewriter.splitBlock(&funcOp.front(),
funcOp.front().getTerminator()->getIterator());
rewriter.mergeBlockBefore(&funcOp.front(), fusionOp, captures.getArrayRef());
rewriter.eraseOp(fusionOp);
rewriter.eraseOp(moduleOp);
return success();
}
bool FusionRewritePattern::isRewritable(lmhlo::FusionOp fusionOp) const {
auto callback = [this](Operation* op) {
if (rewritableTarget.isLegal(op)) return WalkResult::advance();
return WalkResult::interrupt();
};
return !fusionOp.getRegion().walk(callback).wasInterrupted();
}
void FusionRewritePattern::annotateLaunchFunc(func::FuncOp funcOp,
PatternRewriter& rewriter) {
llvm::SmallDenseMap<Operation*, SmallVector<bool>> writtenOperands;
funcOp.walk([&](memref::TensorStoreOp storeOp) {
auto toTensor =
storeOp.getTensor().getDefiningOp<bufferization::ToTensorOp>();
assert(toTensor && "not defined by bufferization.to_tensor");
for (auto& use : toTensor.getMemref().getUses()) {
Operation* user = use.getOwner();
if (isa<gpu::LaunchFuncOp>(user)) {
writtenOperands.try_emplace(user, user->getNumOperands())
.first->second[use.getOperandNumber()] = true;
use.set(storeOp.getMemref());
}
}
rewriter.eraseOp(storeOp);
rewriter.eraseOp(toTensor);
});
for (const auto& [op, vec] : writtenOperands)
op->setAttr(kWrittenOperandsAttrName, rewriter.getBoolArrayAttr(vec));
}
// Returns whether 'type' is can be lowered by the FusionRewritePattern.
static bool isRewritableType(Type type) {
auto shapedType = type.cast<ShapedType>();
// Complex types are not yet supported.
if (shapedType.getElementType().isa<ComplexType>()) return false;
// Zero ranked shapes are not yet supported.
if (shapedType.getRank() == 0) return false;
// MemRef types need to have identity layout.
if (auto memrefType = shapedType.dyn_cast<MemRefType>())
return memrefType.getLayout().isIdentity();
return true;
}
ConversionTarget FusionRewritePattern::getRewritableTarget(MLIRContext* ctx) {
ConversionTarget target(*ctx);
// Mark expected auxiliary ops as legal.
target.addLegalOp<lmhlo::TerminatorOp>();
target.addDynamicallyLegalOp<bufferization::ToTensorOp>(
[&](bufferization::ToTensorOp op) {
return isRewritableType(op.getMemref().getType()) &&
isRewritableType(op.getType());
});
target.addDynamicallyLegalOp<memref::TensorStoreOp>(
[&](memref::TensorStoreOp op) {
return isRewritableType(op.getTensor().getType()) &&
isRewritableType(op.getMemref().getType());
});
// For now, use an explicit allow-list of hlo ops inside the fusion. If any
// other op is present, the fusion will not be rewritten.
target.addLegalOp<mhlo::LogOp>();
target.addLegalOp<mhlo::AbsOp>();
return target;
}
std::unique_ptr<OperationPass<ModuleOp>> createGpuFusionRewritePass() {
return std::make_unique<GpuFusionRewritePass>();
}
ArrayAttr getWrittenOperandsAttribute(Operation* op) {
return op->getAttrOfType<ArrayAttr>(kWrittenOperandsAttrName);
}
} // namespace mlir
<commit_msg>[XLA:GPU] Work around temporary MLIR bug.<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
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 <algorithm>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "mlir-hlo/Dialect/lhlo/IR/lhlo_ops.h"
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "mlir-hlo/Transforms/GPUPassDetail.h"
#include "mlir-hlo/Transforms/gpu_passes.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/IR/Visitors.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Rewrite/FrozenRewritePatternSet.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/RegionUtils.h"
namespace mlir {
namespace {
class GpuFusionRewritePass
: public GpuFusionRewritePassBase<GpuFusionRewritePass> {
public:
explicit GpuFusionRewritePass() = default;
using Pass::runPipeline; // Give FusionRewritePattern access.
private:
void getDependentDialects(DialectRegistry& registry) const override;
void runOnOperation() override;
};
// Rewrites `lmhlo.fusion` to `gpu.launch_func` for fusion regions that the
// HLO to GPU pipeline can handle.
class FusionRewritePattern : public OpRewritePattern<lmhlo::FusionOp> {
public:
explicit FusionRewritePattern(MLIRContext* ctx,
GpuFusionRewritePass& parentPass,
SymbolTable& symbolTable);
private:
LogicalResult matchAndRewrite(lmhlo::FusionOp fusionOp,
PatternRewriter& rewriter) const override;
// Returns whether all ops in fusionOp's region are legal to rewritableTarget.
bool isRewritable(lmhlo::FusionOp fusionOp) const;
// Annotates gpu.launch_func with attribute specifying written operands.
//
// gpu.launch_func ..., %memref, ...
// %tensor = bufferize.to_tensor %memref
// memref.tensor_store %tensor, %argN
//
// is replaced with:
//
// gpu.launch_func ..., %argN, ... { written_operands = [..., unit, ...] }
//
// The 'written_operands' attribute is used later to retrieve which
// gpu.launch_func arguments are written vs. just read.
static void annotateLaunchFunc(func::FuncOp funcOp,
PatternRewriter& rewriter);
// Returns target where lowerable fusion ops are marked legal.
static ConversionTarget getRewritableTarget(MLIRContext* ctx);
GpuFusionRewritePass& parentPass;
SymbolTable& symbolTable;
ConversionTarget rewritableTarget = getRewritableTarget(getContext());
};
} // namespace
// Name of the 'gpu.launch_func' attribute which specifies the written operands.
static constexpr llvm::StringLiteral kWrittenOperandsAttrName =
"written_operands";
void GpuFusionRewritePass::getDependentDialects(
DialectRegistry& registry) const {
OpPassManager passManager;
createHloToGpuPipeline(passManager, /*tileSizes=*/{}, /*unrollFactors=*/{});
passManager.getDependentDialects(registry);
}
void GpuFusionRewritePass::runOnOperation() {
SymbolTable symbolTable(getOperation());
auto pattern =
std::make_unique<FusionRewritePattern>(&getContext(), *this, symbolTable);
mlir::FrozenRewritePatternSet patterns({&getContext(), std::move(pattern)});
auto callback = [&](lmhlo::FusionOp fusion) {
if (failed(applyOpPatternsAndFold(fusion, patterns)))
return WalkResult::interrupt();
return WalkResult::advance();
};
if (getOperation().walk(callback).wasInterrupted())
return signalPassFailure();
}
FusionRewritePattern::FusionRewritePattern(MLIRContext* ctx,
GpuFusionRewritePass& parentPass,
SymbolTable& symbolTable)
: OpRewritePattern<lmhlo::FusionOp>::OpRewritePattern(ctx),
parentPass(parentPass),
symbolTable(symbolTable) {}
// Returns the number of elements each thread should handle for 'type'.
// The intention is that loads and stores are vectorized later on to this width
// to maximize memory throughput.
static int64_t getElementsPerThread(TensorType type) {
// Don't vectorize if the number of elements cannot saturate the GPU.
// Use a coarse heuristic because we don't know the target GPU here.
const int64_t kNumFp32AlusOnV100 = 5376;
if (type.getNumElements() < kNumFp32AlusOnV100) return 1;
// Vectorize so that loads and stores are 128 bits per thread.
if (type.getElementType().isIntOrFloat())
return 128 / type.getElementType().getIntOrFloatBitWidth();
return 1; // Default to no vectorization.
}
// Returns the number of threads per block to use for 'type', given the number
// of elements each thread handles. The returned block size is in the [128, 384]
// range, preferrably close to 256 and evenly dividing the number of threads
// required to handle all elements in 'type'.
static int64_t getThreadsPerBlock(TensorType type, int64_t elementsPerThread) {
int64_t numThreads =
llvm::divideCeil(type.getNumElements(), elementsPerThread);
// Use a single block for small problems.
if (numThreads < 256) return numThreads;
// Use 256 if that block size evenly divides the problem.
if (numThreads % 256 == 0) return 256;
int64_t elementSizeBits = 32;
if (type.getElementType().isIntOrFloat())
elementSizeBits = type.getElementType().getIntOrFloatBitWidth();
int64_t threadSizeBits = elementSizeBits * elementsPerThread;
// Search block sizes in the [128, 384] range near 256 with decreasing
// power-of-2 factor, down to a multiple of a cache line (assumed to be 1024
// bits). Use the first one that evenly divides the problem, which allows the
// loop tail to be optimized away.
for (int i = 128; i * threadSizeBits >= 1024; i /= 2) {
// 2 * i: earlier iterations already handled even multiples of i.
for (int blockSize = 256 - i; blockSize >= 128; blockSize -= 2 * i)
if (numThreads % blockSize == 0) return blockSize;
for (int blockSize = 256 + i; blockSize <= 384; blockSize += 2 * i)
if (numThreads % blockSize == 0) return blockSize;
}
// None of the checked block sizes evenly divides the number of required
// threads. Use a default of 256 and accept the loop tail.
return 256;
}
LogicalResult FusionRewritePattern::matchAndRewrite(
lmhlo::FusionOp fusionOp, PatternRewriter& rewriter) const {
// If fusion_op (including its region) is not legal by rewriteable_target,
// we expect lowering to GPU to fail or produce incorrect results.
if (!isRewritable(fusionOp))
return rewriter.notifyMatchFailure(fusionOp, "not rewritable");
auto storeOps = fusionOp.getBody()->getOps<memref::TensorStoreOp>();
if (storeOps.empty())
return rewriter.notifyMatchFailure(fusionOp, "no memref.tensor_store ops");
// Collect values in fusion region defined above.
SetVector<Value> captures;
getUsedValuesDefinedAbove(fusionOp->getRegions(), captures);
// Converts statically shaped types to their 1D equivalent. This only works
// for element wise fusions and will have to become a more sophisticated
// pass when e.g. broadcasts are involved.
TypeConverter converter;
converter.addConversion([](Type type) { return type; });
converter.addConversion([](ShapedType type) {
if (!type.hasStaticShape()) return type;
return type.clone(type.getNumElements());
});
converter.addConversion([&](MemRefType type) {
if (!type.hasStaticShape() || !type.getLayout().isIdentity()) return type;
return MemRefType::get(type.getNumElements(), type.getElementType(),
MemRefLayoutAttrInterface(), type.getMemorySpace());
});
// Create a new module with a function, clone fusion region into it.
Location loc = fusionOp.getLoc();
auto moduleOp = rewriter.create<ModuleOp>(loc);
rewriter.setInsertionPointToEnd(moduleOp.getBody());
auto argTypes = llvm::to_vector(llvm::map_range(captures, [&](Value value) {
return converter.convertType(value.getType());
}));
auto funcType = rewriter.getFunctionType(argTypes, llvm::None);
auto funcOp = rewriter.create<func::FuncOp>(loc, "fusion", funcType);
rewriter.setInsertionPointToEnd(funcOp.addEntryBlock());
BlockAndValueMapping mapping;
for (const auto& [from, to] :
llvm::zip_first(captures, funcOp.getArguments())) {
mapping.map(from, to);
}
rewriter.cloneRegionBefore(fusionOp.getRegion(), funcOp.getRegion(),
funcOp.end(), mapping);
rewriter.mergeBlocks(&funcOp.back(), &funcOp.front());
funcOp->walk([&](Operation* op) {
for (auto result : op->getResults())
result.setType(converter.convertType(result.getType()));
});
// Create and run the HLO to GPU pass pipeline.
auto resultType = (*storeOps.begin()).tensor().getType().cast<TensorType>();
int64_t unrollFactor = getElementsPerThread(resultType);
int64_t tileSize = getThreadsPerBlock(resultType, unrollFactor);
// Note: passManager.enableIRPrinting() doesn't do anything on dynamic pass
// pipelines. Printing needs to be enabled on the parent pass manager.
PassManager passManager(getContext());
createHloToGpuPipeline(passManager, {tileSize},
{&unrollFactor, unrollFactor > 1});
if (failed(parentPass.runPipeline(passManager, moduleOp)))
return rewriter.notifyMatchFailure(fusionOp, "failed to run pipeline");
// Clone the (single) gpu module with the device function.
rewriter.setInsertionPoint(fusionOp->getParentOfType<func::FuncOp>());
for (auto gpuModuleOp : moduleOp.getBodyRegion().getOps<gpu::GPUModuleOp>()) {
StringAttr symbol =
symbolTable.insert(rewriter.clone(*gpuModuleOp.getOperation()));
if (symbol == gpuModuleOp.getNameAttr()) {
continue;
}
// gpu.module name changed, update symbol uses in gpu.launch_func.
funcOp->walk([&](gpu::LaunchFuncOp launch) {
launch.kernelAttr(
SymbolRefAttr::get(symbol, launch.kernel().getNestedReferences()));
});
}
// Add 'gpu.container_module' attribute to parent module.
fusionOp->getParentOfType<ModuleOp>()->setAttr(
gpu::GPUDialect::getContainerModuleAttrName(), rewriter.getUnitAttr());
// Annotate gpu.launch_func loc and attribute specifying written operands.
funcOp->walk([&](gpu::LaunchFuncOp op) { op->setLoc(loc); });
annotateLaunchFunc(funcOp, rewriter);
// Remove dead allocations that were only used by store_op erased above.
RewritePatternSet patterns(getContext());
memref::AllocOp::getCanonicalizationPatterns(patterns, getContext());
if (failed(applyPatternsAndFoldGreedily(funcOp, std::move(patterns))))
return rewriter.notifyMatchFailure(fusionOp, "failed to canonicalize");
// Replace fusion op with host function region.
rewriter.splitBlock(&funcOp.front(),
funcOp.front().getTerminator()->getIterator());
rewriter.mergeBlockBefore(&funcOp.front(), fusionOp, captures.getArrayRef());
rewriter.eraseOp(fusionOp);
rewriter.eraseOp(moduleOp);
return success();
}
bool FusionRewritePattern::isRewritable(lmhlo::FusionOp fusionOp) const {
auto callback = [this](Operation* op) {
if (rewritableTarget.isLegal(op)) return WalkResult::advance();
return WalkResult::interrupt();
};
return !fusionOp.getRegion().walk(callback).wasInterrupted();
}
void FusionRewritePattern::annotateLaunchFunc(func::FuncOp funcOp,
PatternRewriter& rewriter) {
llvm::SmallDenseMap<Operation*, SmallVector<bool>> writtenOperands;
funcOp.walk([&](memref::TensorStoreOp storeOp) {
auto toTensor =
storeOp.getTensor().getDefiningOp<bufferization::ToTensorOp>();
assert(toTensor && "not defined by bufferization.to_tensor");
for (auto& use : toTensor.getMemref().getUses()) {
Operation* user = use.getOwner();
if (isa<gpu::LaunchFuncOp>(user)) {
writtenOperands.try_emplace(user, user->getNumOperands())
.first->second[use.getOperandNumber()] = true;
use.set(storeOp.getMemref());
}
}
rewriter.eraseOp(storeOp);
rewriter.eraseOp(toTensor);
});
for (const auto& [op, vec] : writtenOperands)
op->setAttr(kWrittenOperandsAttrName, rewriter.getBoolArrayAttr(vec));
}
// Returns whether 'type' is can be lowered by the FusionRewritePattern.
static bool isRewritableType(Type type) {
auto shapedType = type.cast<ShapedType>();
// Complex types are not yet supported.
if (shapedType.getElementType().isa<ComplexType>()) return false;
// Zero ranked shapes are not yet supported.
if (shapedType.getRank() == 0) return false;
// MemRef types need to have identity layout.
if (auto memrefType = shapedType.dyn_cast<MemRefType>())
return memrefType.getLayout().isIdentity();
return true;
}
ConversionTarget FusionRewritePattern::getRewritableTarget(MLIRContext* ctx) {
ConversionTarget target(*ctx);
// Mark expected auxiliary ops as legal.
target.addLegalOp<lmhlo::TerminatorOp>();
target.addDynamicallyLegalOp<bufferization::ToTensorOp>(
[&](bufferization::ToTensorOp op) {
return isRewritableType(op.getMemref().getType()) &&
isRewritableType(op.getType());
});
target.addDynamicallyLegalOp<memref::TensorStoreOp>(
[&](memref::TensorStoreOp op) {
return isRewritableType(op.getTensor().getType()) &&
isRewritableType(op.getMemref().getType());
});
// For now, use an explicit allow-list of hlo ops inside the fusion. If any
// other op is present, the fusion will not be rewritten.
target.addLegalOp<mhlo::LogOp>();
target.addLegalOp<mhlo::AbsOp>();
return target;
}
std::unique_ptr<OperationPass<ModuleOp>> createGpuFusionRewritePass() {
return std::make_unique<GpuFusionRewritePass>();
}
ArrayAttr getWrittenOperandsAttribute(Operation* op) {
return op->getAttrOfType<ArrayAttr>(kWrittenOperandsAttrName);
}
} // namespace mlir
<|endoftext|> |
<commit_before>#include <engine/gfx/opengl_glew.hpp>
#include <engine/window/sdl_window.hpp>
#include <stlw/format.hpp>
#include <stlw/type_ctors.hpp>
namespace engine
{
namespace window
{
stlw::result<stlw::empty_type, std::string>
sdl_library::init()
{
// (from the docs) The requested attributes should be set before creating an
// OpenGL window
auto const set_attribute = [](auto const attribute, auto const value) {
bool const set_attribute_suceeded = SDL_GL_SetAttribute(attribute, value);
if (!set_attribute_suceeded) {
std::cerr << "Setting attribute '" << std::to_string(attribute) << "' failed, error is '"
<< SDL_GetError() << "'\n";
}
};
// Use OpenGL 3.1 core
set_attribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
set_attribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
set_attribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// Turn on double buffering with a 24bit Z buffer.
// You may need to change this to 16 or 32 for your system
set_attribute(SDL_GL_DOUBLEBUFFER, 1);
// Use v-sync
SDL_GL_SetSwapInterval(1);
// Initialize video subsystem
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
// Display error message
auto const error = stlw::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
return stlw::make_error(error);
}
return stlw::make_empty();
}
void
sdl_library::destroy()
{
if (SDL_WasInit(SDL_INIT_EVERYTHING)) {
SDL_Quit();
}
}
stlw::result<sdl_window, std::string>
sdl_library::make_window(int const height, int const width)
{
// Hidden dependency between the ordering here, so all the logic exists in one
// place.
//
// * The OpenGL context MUST be initialized before the call to glewInit()
// takes place.
// This is because there is a hidden dependency on glew, it expects an OpenGL
// context to be
// initialized. The glew library knows how to find the OpenGL context in
// memory without any
// reference, so it's a bit like magic.
//
// NOTE: We don't have to do anything to shutdown glew, the processing closing
// will handle it (by
// design.
// First, create the SDL window.
auto const title = "Hello World!";
auto const flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
int const x = SDL_WINDOWPOS_CENTERED;
int const y = SDL_WINDOWPOS_CENTERED;
auto raw = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width,
height, flags);
if (nullptr == raw) {
auto const error = stlw::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
return stlw::make_error(error);
}
window_ptr window_ptr{raw, &SDL_DestroyWindow};
// Second, create the graphics context.
auto gl_context = SDL_GL_CreateContext(window_ptr.get());
if (nullptr == gl_context) {
// Display error message
auto const error =
stlw::format("OpenGL context could not be created! SDL Error: {}\n", SDL_GetError());
return stlw::make_error(error);
}
SDL_GL_MakeCurrent(window_ptr.get(), gl_context);
// Third, initialize GLEW.
glewExperimental = GL_TRUE;
auto const glew_status = glewInit();
if (GLEW_OK != glew_status) {
auto const error = stlw::format("GLEW could not initialize! GLEW error: {}\n",
glewGetErrorString(glew_status));
return stlw::make_error(error);
}
return sdl_window{std::move(window_ptr), gl_context};
}
} // ns window
} // ns engine
<commit_msg>Setting sdl window attributes could fail.<commit_after>#include <engine/gfx/opengl_glew.hpp>
#include <engine/window/sdl_window.hpp>
#include <stlw/format.hpp>
#include <stlw/type_ctors.hpp>
#include <stlw/type_macros.hpp>
namespace engine
{
namespace window
{
stlw::result<stlw::empty_type, std::string>
sdl_library::init()
{
// (from the docs) The requested attributes should be set before creating an
// OpenGL window
auto const set_attribute = [](auto const attribute,
auto const value) -> stlw::result<stlw::empty_type, std::string> {
bool const set_attribute_suceeded = SDL_GL_SetAttribute(attribute, value);
if (!set_attribute_suceeded) {
auto const fmt = fmt::format("Setting attribute '{}' failed, error is '{}'\n",
std::to_string(attribute), SDL_GetError());
return stlw::make_error(fmt);
}
return stlw::make_empty();
};
// Use OpenGL 3.1 core
DO_EFFECT(set_attribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3));
DO_EFFECT(set_attribute(SDL_GL_CONTEXT_MINOR_VERSION, 1));
DO_EFFECT(set_attribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE));
// Turn on double buffering with a 24bit Z buffer.
// You may need to change this to 16 or 32 for your system
DO_EFFECT(set_attribute(SDL_GL_DOUBLEBUFFER, 1));
// Use v-sync
SDL_GL_SetSwapInterval(1);
// Initialize video subsystem
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
// Display error message
auto const error = stlw::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
return stlw::make_error(error);
}
return stlw::make_empty();
}
void
sdl_library::destroy()
{
if (SDL_WasInit(SDL_INIT_EVERYTHING)) {
SDL_Quit();
}
}
stlw::result<sdl_window, std::string>
sdl_library::make_window(int const height, int const width)
{
// Hidden dependency between the ordering here, so all the logic exists in one
// place.
//
// * The OpenGL context MUST be initialized before the call to glewInit()
// takes place.
// This is because there is a hidden dependency on glew, it expects an OpenGL
// context to be
// initialized. The glew library knows how to find the OpenGL context in
// memory without any
// reference, so it's a bit like magic.
//
// NOTE: We don't have to do anything to shutdown glew, the processing closing
// will handle it (by
// design.
// First, create the SDL window.
auto const title = "Hello World!";
auto const flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
int const x = SDL_WINDOWPOS_CENTERED;
int const y = SDL_WINDOWPOS_CENTERED;
auto raw = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width,
height, flags);
if (nullptr == raw) {
auto const error = stlw::format("SDL could not initialize! SDL_Error: {}\n", SDL_GetError());
return stlw::make_error(error);
}
window_ptr window_ptr{raw, &SDL_DestroyWindow};
// Second, create the graphics context.
auto gl_context = SDL_GL_CreateContext(window_ptr.get());
if (nullptr == gl_context) {
// Display error message
auto const error =
stlw::format("OpenGL context could not be created! SDL Error: {}\n", SDL_GetError());
return stlw::make_error(error);
}
SDL_GL_MakeCurrent(window_ptr.get(), gl_context);
// Third, initialize GLEW.
glewExperimental = GL_TRUE;
auto const glew_status = glewInit();
if (GLEW_OK != glew_status) {
auto const error = stlw::format("GLEW could not initialize! GLEW error: {}\n",
glewGetErrorString(glew_status));
return stlw::make_error(error);
}
return sdl_window{std::move(window_ptr), gl_context};
}
} // ns window
} // ns engine
<|endoftext|> |
<commit_before>/*************************************************************************/
/* translation_loader_po.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "translation_loader_po.h"
#include "os/file_access.h"
#include "translation.h"
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) {
enum Status {
STATUS_NONE,
STATUS_READING_ID,
STATUS_READING_STRING,
};
Status status = STATUS_NONE;
String msg_id;
String msg_str;
String config;
if (r_error)
*r_error = ERR_FILE_CORRUPT;
Ref<Translation> translation = Ref<Translation>(memnew(Translation));
int line = 1;
while (true) {
String l = f->get_line();
if (f->eof_reached()) {
if (status == STATUS_READING_STRING) {
if (msg_id != "")
translation->add_message(msg_id, msg_str);
else if (config == "")
config = msg_str;
break;
} else if (status == STATUS_NONE)
break;
memdelete(f);
ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
ERR_FAIL_V(RES());
}
l = l.strip_edges();
if (l.begins_with("msgid")) {
if (status == STATUS_READING_ID) {
memdelete(f);
ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
ERR_FAIL_V(RES());
}
if (msg_id != "")
translation->add_message(msg_id, msg_str);
else if (config == "")
config = msg_str;
l = l.substr(5, l.length()).strip_edges();
status = STATUS_READING_ID;
msg_id = "";
msg_str = "";
}
if (l.begins_with("msgstr")) {
if (status != STATUS_READING_ID) {
memdelete(f);
ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
ERR_FAIL_V(RES());
}
l = l.substr(6, l.length()).strip_edges();
status = STATUS_READING_STRING;
}
if (l == "" || l.begins_with("#")) {
line++;
continue; //nothing to read or comment
}
if (!l.begins_with("\"") || status == STATUS_NONE) {
//not a string? failure!
ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
ERR_FAIL_V(RES());
}
l = l.substr(1, l.length());
//find final quote
int end_pos = -1;
for (int i = 0; i < l.length(); i++) {
if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) {
end_pos = i;
break;
}
}
if (end_pos == -1) {
ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: ");
ERR_FAIL_V(RES());
}
l = l.substr(0, end_pos);
l = l.c_unescape();
if (status == STATUS_READING_ID)
msg_id += l;
else
msg_str += l;
line++;
}
f->close();
memdelete(f);
if (config == "") {
ERR_EXPLAIN("No config found in file: " + p_path);
ERR_FAIL_V(RES());
}
Vector<String> configs = config.split("\n");
for (int i = 0; i < configs.size(); i++) {
String c = configs[i].strip_edges();
int p = c.find(":");
if (p == -1)
continue;
String prop = c.substr(0, p).strip_edges();
String value = c.substr(p + 1, c.length()).strip_edges();
if (prop == "X-Language") {
translation->set_locale(value);
}
}
if (r_error)
*r_error = OK;
return translation;
}
RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
*r_error = ERR_CANT_OPEN;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_V(!f, RES());
return load_translation(f, r_error);
}
void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("po");
//p_extensions->push_back("mo"); //mo in the future...
}
bool TranslationLoaderPO::handles_type(const String &p_type) const {
return (p_type == "Translation");
}
String TranslationLoaderPO::get_resource_type(const String &p_path) const {
if (p_path.get_extension().to_lower() == "po")
return "Translation";
return "";
}
TranslationLoaderPO::TranslationLoaderPO() {
}
<commit_msg>Ignore fuzzy translations<commit_after>/*************************************************************************/
/* translation_loader_po.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "translation_loader_po.h"
#include "os/file_access.h"
#include "translation.h"
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) {
enum Status {
STATUS_NONE,
STATUS_READING_ID,
STATUS_READING_STRING,
};
Status status = STATUS_NONE;
String msg_id;
String msg_str;
String config;
if (r_error)
*r_error = ERR_FILE_CORRUPT;
Ref<Translation> translation = Ref<Translation>(memnew(Translation));
int line = 1;
bool skip_this;
bool skip_next;
while (true) {
String l = f->get_line();
if (f->eof_reached()) {
if (status == STATUS_READING_STRING) {
if (msg_id != "") {
if (!skip_this)
translation->add_message(msg_id, msg_str);
} else if (config == "")
config = msg_str;
break;
} else if (status == STATUS_NONE)
break;
memdelete(f);
ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
ERR_FAIL_V(RES());
}
l = l.strip_edges();
if (l.begins_with("msgid")) {
if (status == STATUS_READING_ID) {
memdelete(f);
ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
ERR_FAIL_V(RES());
}
if (msg_id != "") {
if (!skip_this)
translation->add_message(msg_id, msg_str);
} else if (config == "")
config = msg_str;
l = l.substr(5, l.length()).strip_edges();
status = STATUS_READING_ID;
msg_id = "";
msg_str = "";
skip_this = skip_next;
skip_next = false;
}
if (l.begins_with("msgstr")) {
if (status != STATUS_READING_ID) {
memdelete(f);
ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
ERR_FAIL_V(RES());
}
l = l.substr(6, l.length()).strip_edges();
status = STATUS_READING_STRING;
}
if (l == "" || l.begins_with("#")) {
if (l.find("fuzzy") != -1) {
skip_next = true;
}
line++;
continue; //nothing to read or comment
}
if (!l.begins_with("\"") || status == STATUS_NONE) {
//not a string? failure!
ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
ERR_FAIL_V(RES());
}
l = l.substr(1, l.length());
//find final quote
int end_pos = -1;
for (int i = 0; i < l.length(); i++) {
if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) {
end_pos = i;
break;
}
}
if (end_pos == -1) {
ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: ");
ERR_FAIL_V(RES());
}
l = l.substr(0, end_pos);
l = l.c_unescape();
if (status == STATUS_READING_ID)
msg_id += l;
else
msg_str += l;
line++;
}
f->close();
memdelete(f);
if (config == "") {
ERR_EXPLAIN("No config found in file: " + p_path);
ERR_FAIL_V(RES());
}
Vector<String> configs = config.split("\n");
for (int i = 0; i < configs.size(); i++) {
String c = configs[i].strip_edges();
int p = c.find(":");
if (p == -1)
continue;
String prop = c.substr(0, p).strip_edges();
String value = c.substr(p + 1, c.length()).strip_edges();
if (prop == "X-Language") {
translation->set_locale(value);
}
}
if (r_error)
*r_error = OK;
return translation;
}
RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
*r_error = ERR_CANT_OPEN;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_V(!f, RES());
return load_translation(f, r_error);
}
void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("po");
//p_extensions->push_back("mo"); //mo in the future...
}
bool TranslationLoaderPO::handles_type(const String &p_type) const {
return (p_type == "Translation");
}
String TranslationLoaderPO::get_resource_type(const String &p_path) const {
if (p_path.get_extension().to_lower() == "po")
return "Translation";
return "";
}
TranslationLoaderPO::TranslationLoaderPO() {
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test libc++'s implementation of align_val_t, and the relevant new/delete
// overloads in all dialects when -faligned-allocation is present.
// Libc++ defers to the underlying MSVC library to provide the new/delete
// definitions, which does not yet provide aligned allocation
// XFAIL: LIBCXX-WINDOWS-FIXME
// XFAIL: with_system_cxx_lib=macosx10.12 || availability=macosx10.12
// XFAIL: with_system_cxx_lib=macosx10.11 || availability=macosx10.11
// XFAIL: with_system_cxx_lib=macosx10.10 || availability=macosx10.10
// XFAIL: with_system_cxx_lib=macosx10.9 || availability=macosx10.9
// XFAIL: with_system_cxx_lib=macosx10.8 || availability=macosx10.8
// XFAIL: with_system_cxx_lib=macosx10.7 || availability=macosx10.7
// XFAIL: sanitizer-new-delete, ubsan
// GCC doesn't support the aligned-allocation flags.
// XFAIL: gcc
// RUN: %build -faligned-allocation -fsized-deallocation
// RUN: %run
// RUN: %build -faligned-allocation -fno-sized-deallocation -DNO_SIZE
// RUN: %run
// RUN: %build -fno-aligned-allocation -fsized-deallocation -DNO_ALIGN
// RUN: %run
// RUN: %build -fno-aligned-allocation -fno-sized-deallocation -DNO_ALIGN -DNO_SIZE
// RUN: %run
#include <new>
#include <typeinfo>
#include <string>
#include <cassert>
#include "test_macros.h"
struct alloc_stats {
alloc_stats() { reset(); }
int aligned_sized_called;
int aligned_called;
int sized_called;
int plain_called;
int last_size;
int last_align;
void reset() {
aligned_sized_called = aligned_called = sized_called = plain_called = 0;
last_align = last_size = -1;
}
bool expect_plain() const {
assert(aligned_sized_called == 0);
assert(aligned_called == 0);
assert(sized_called == 0);
assert(last_size == -1);
assert(last_align == -1);
return plain_called == 1;
}
bool expect_size(int n) const {
assert(plain_called == 0);
assert(aligned_sized_called == 0);
assert(aligned_called == 0);
assert(last_size == n);
assert(last_align == -1);
return sized_called == 1;
}
bool expect_align(int a) const {
assert(plain_called == 0);
assert(aligned_sized_called == 0);
assert(sized_called == 0);
assert(last_size == -1);
assert(last_align == a);
return aligned_called == 1;
}
bool expect_size_align(int n, int a) const {
assert(plain_called == 0);
assert(sized_called == 0);
assert(aligned_called == 0);
assert(last_size == n);
assert(last_align == a);
return aligned_sized_called == 1;
}
};
alloc_stats stats;
void operator delete(void* p)TEST_NOEXCEPT {
::free(p);
stats.plain_called++;
stats.last_size = stats.last_align = -1;
}
#ifndef NO_SIZE
void operator delete(void* p, size_t n)TEST_NOEXCEPT {
::free(p);
stats.sized_called++;
stats.last_size = n;
stats.last_align = -1;
}
#endif
#ifndef NO_ALIGN
void operator delete(void* p, std::align_val_t a)TEST_NOEXCEPT {
::free(p);
stats.aligned_called++;
stats.last_align = static_cast<int>(a);
stats.last_size = -1;
}
void operator delete(void* p, size_t n, std::align_val_t a)TEST_NOEXCEPT {
::free(p);
stats.aligned_sized_called++;
stats.last_align = static_cast<int>(a);
stats.last_size = n;
}
#endif
void test_libcpp_dealloc() {
void* p = nullptr;
size_t over_align_val = TEST_ALIGNOF(std::max_align_t) * 2;
size_t under_align_val = TEST_ALIGNOF(int);
size_t with_size_val = 2;
{
std::__libcpp_deallocate_unsized(p, under_align_val);
assert(stats.expect_plain());
}
stats.reset();
#if defined(NO_SIZE) && defined(NO_ALIGN)
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_plain());
}
stats.reset();
#elif defined(NO_SIZE)
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_align(over_align_val));
}
stats.reset();
#elif defined(NO_ALIGN)
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_size(with_size_val));
}
stats.reset();
#else
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_size_align(with_size_val, over_align_val));
}
stats.reset();
{
std::__libcpp_deallocate_unsized(p, over_align_val);
assert(stats.expect_align(over_align_val));
}
stats.reset();
{
std::__libcpp_deallocate(p, with_size_val, under_align_val);
assert(stats.expect_size(with_size_val));
}
stats.reset();
#endif
}
struct TEST_ALIGNAS(128) AlignedType {
AlignedType() : elem(0) {}
TEST_ALIGNAS(128) char elem;
};
void test_allocator_and_new_match() {
stats.reset();
#if defined(NO_SIZE) && defined(NO_ALIGN)
{
int* x = new int(42);
delete x;
assert(stats.expect_plain());
}
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_plain());
}
stats.reset();
#elif defined(NO_SIZE)
stats.reset();
#if TEST_STD_VER >= 11
{
int* x = new int(42);
delete x;
assert(stats.expect_plain());
}
#endif
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_align(TEST_ALIGNOF(AlignedType)));
}
stats.reset();
#elif defined(NO_ALIGN)
stats.reset();
{
int* x = new int(42);
delete x;
assert(stats.expect_size(sizeof(int)));
}
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_size(sizeof(AlignedType)));
}
stats.reset();
#else
stats.reset();
{
int* x = new int(42);
delete x;
assert(stats.expect_size(sizeof(int)));
}
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_size_align(sizeof(AlignedType),
TEST_ALIGNOF(AlignedType)));
}
stats.reset();
#endif
}
int main() {
test_libcpp_dealloc();
test_allocator_and_new_match();
}
<commit_msg>[libcxx] Fix XFAIL for aligned deallocation test with trunk Clang<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test libc++'s implementation of align_val_t, and the relevant new/delete
// overloads in all dialects when -faligned-allocation is present.
// Libc++ defers to the underlying MSVC library to provide the new/delete
// definitions, which does not yet provide aligned allocation
// XFAIL: LIBCXX-WINDOWS-FIXME
// Clang 10 (and older) will trigger an availability error when the deployment
// target does not support aligned allocation, even if we pass `-faligned-allocation`.
// XFAIL: apple-clang-10 && availability=macosx10.12
// The dylib shipped with macosx10.12 does not contain the aligned allocation
// functions, so trying to force using those with -faligned-allocation results
// in a link error.
// XFAIL: with_system_cxx_lib=macosx10.12
// The test will fail on deployment targets that do not support sized deallocation.
// XFAIL: availability=macosx10.11
// XFAIL: availability=macosx10.10
// XFAIL: availability=macosx10.9
// XFAIL: availability=macosx10.8
// XFAIL: availability=macosx10.7
// XFAIL: sanitizer-new-delete, ubsan
// GCC doesn't support the aligned-allocation flags.
// XFAIL: gcc
// RUN: %build -faligned-allocation -fsized-deallocation
// RUN: %run
// RUN: %build -faligned-allocation -fno-sized-deallocation -DNO_SIZE
// RUN: %run
// RUN: %build -fno-aligned-allocation -fsized-deallocation -DNO_ALIGN
// RUN: %run
// RUN: %build -fno-aligned-allocation -fno-sized-deallocation -DNO_ALIGN -DNO_SIZE
// RUN: %run
#include <new>
#include <typeinfo>
#include <string>
#include <cassert>
#include "test_macros.h"
struct alloc_stats {
alloc_stats() { reset(); }
int aligned_sized_called;
int aligned_called;
int sized_called;
int plain_called;
int last_size;
int last_align;
void reset() {
aligned_sized_called = aligned_called = sized_called = plain_called = 0;
last_align = last_size = -1;
}
bool expect_plain() const {
assert(aligned_sized_called == 0);
assert(aligned_called == 0);
assert(sized_called == 0);
assert(last_size == -1);
assert(last_align == -1);
return plain_called == 1;
}
bool expect_size(int n) const {
assert(plain_called == 0);
assert(aligned_sized_called == 0);
assert(aligned_called == 0);
assert(last_size == n);
assert(last_align == -1);
return sized_called == 1;
}
bool expect_align(int a) const {
assert(plain_called == 0);
assert(aligned_sized_called == 0);
assert(sized_called == 0);
assert(last_size == -1);
assert(last_align == a);
return aligned_called == 1;
}
bool expect_size_align(int n, int a) const {
assert(plain_called == 0);
assert(sized_called == 0);
assert(aligned_called == 0);
assert(last_size == n);
assert(last_align == a);
return aligned_sized_called == 1;
}
};
alloc_stats stats;
void operator delete(void* p)TEST_NOEXCEPT {
::free(p);
stats.plain_called++;
stats.last_size = stats.last_align = -1;
}
#ifndef NO_SIZE
void operator delete(void* p, size_t n)TEST_NOEXCEPT {
::free(p);
stats.sized_called++;
stats.last_size = n;
stats.last_align = -1;
}
#endif
#ifndef NO_ALIGN
void operator delete(void* p, std::align_val_t a)TEST_NOEXCEPT {
::free(p);
stats.aligned_called++;
stats.last_align = static_cast<int>(a);
stats.last_size = -1;
}
void operator delete(void* p, size_t n, std::align_val_t a)TEST_NOEXCEPT {
::free(p);
stats.aligned_sized_called++;
stats.last_align = static_cast<int>(a);
stats.last_size = n;
}
#endif
void test_libcpp_dealloc() {
void* p = nullptr;
size_t over_align_val = TEST_ALIGNOF(std::max_align_t) * 2;
size_t under_align_val = TEST_ALIGNOF(int);
size_t with_size_val = 2;
{
std::__libcpp_deallocate_unsized(p, under_align_val);
assert(stats.expect_plain());
}
stats.reset();
#if defined(NO_SIZE) && defined(NO_ALIGN)
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_plain());
}
stats.reset();
#elif defined(NO_SIZE)
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_align(over_align_val));
}
stats.reset();
#elif defined(NO_ALIGN)
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_size(with_size_val));
}
stats.reset();
#else
{
std::__libcpp_deallocate(p, with_size_val, over_align_val);
assert(stats.expect_size_align(with_size_val, over_align_val));
}
stats.reset();
{
std::__libcpp_deallocate_unsized(p, over_align_val);
assert(stats.expect_align(over_align_val));
}
stats.reset();
{
std::__libcpp_deallocate(p, with_size_val, under_align_val);
assert(stats.expect_size(with_size_val));
}
stats.reset();
#endif
}
struct TEST_ALIGNAS(128) AlignedType {
AlignedType() : elem(0) {}
TEST_ALIGNAS(128) char elem;
};
void test_allocator_and_new_match() {
stats.reset();
#if defined(NO_SIZE) && defined(NO_ALIGN)
{
int* x = new int(42);
delete x;
assert(stats.expect_plain());
}
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_plain());
}
stats.reset();
#elif defined(NO_SIZE)
stats.reset();
#if TEST_STD_VER >= 11
{
int* x = new int(42);
delete x;
assert(stats.expect_plain());
}
#endif
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_align(TEST_ALIGNOF(AlignedType)));
}
stats.reset();
#elif defined(NO_ALIGN)
stats.reset();
{
int* x = new int(42);
delete x;
assert(stats.expect_size(sizeof(int)));
}
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_size(sizeof(AlignedType)));
}
stats.reset();
#else
stats.reset();
{
int* x = new int(42);
delete x;
assert(stats.expect_size(sizeof(int)));
}
stats.reset();
{
AlignedType* a = new AlignedType();
delete a;
assert(stats.expect_size_align(sizeof(AlignedType),
TEST_ALIGNOF(AlignedType)));
}
stats.reset();
#endif
}
int main() {
test_libcpp_dealloc();
test_allocator_and_new_match();
}
<|endoftext|> |
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "config.h"
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
# include <dune/hdd/linearelliptic/testcases/OS2014.hh>
# include "linearelliptic-block-swipdg-expectations.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
typedef TestCases::OS2014::ParametricBlockConvergence< ALUGrid< 2, 2, simplex, conforming > > TestCaseType;
namespace Tests {
template< bool anything >
class BlockSWIPDGStudyExpectations< TestCaseType, 1, anything >
: public internal::BlockSWIPDGStudyExpectationsBase< TestCaseType, 1 >
{
public:
static std::vector< double > results(const TestCaseType& test_case, const std::string type)
{
if (test_case.num_refinements() != 3) {
EXPECT_TRUE(false) << "test results missing for num_refinements: " << test_case.num_refinements();
return {};
}
const auto mu = test_case.parameters().at("mu");
const auto mu_bar = test_case.parameters().at("mu_bar");
const auto mu_hat = test_case.parameters().at("mu_hat");
if (test_case.partitioning() == "[1 1 1]") {
if ( mu == 0.1
&& mu_bar == 0.1
&& mu_hat == 0.1) {
if (type == "energy_mu")
return {};
else if (type == "eta_DF_OS2014")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_mu")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if ( mu == 0.3
&& mu_bar == 0.3
&& mu_hat == 0.1) {
if (type == "energy_mu")
return {};
else if (type == "eta_DF_OS2014")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else if (type == "eff_OS2014_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if ( mu == 0.5
&& mu_bar == 0.5
&& mu_hat == 0.1) {
if (type == "energy_mu")
return {};
else if (type == "eta_DF_OS2014")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else if (type == "eff_OS2014_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if ( mu == 0.1
&& mu_bar == 0.1
&& mu_hat == 1) {
if (type == "eta_DF_OS2014")
return {1.01e+00, 1.21e+00, 1.35e+00, 1.41e+00};
else if (type == "eta_DF_OS2014_*")
return {1.16e+00, 6.90e-01, 3.34e-01, 1.62e-01};
else if (type == "eta_OS2014")
return {4.67e+00, 4.65e+00, 4.67e+00, 4.64e+00};
else if (type == "eta_OS2014_*")
return {5.15e+00, 3.01e+00, 1.45e+00, 6.97e-01};
else if (type == "eff_OS2014_*_mu")
return {5.86e+00, 5.65e+00, 5.77e+00, 6.41e+00};
else if (type == "eff_OS2014_mu")
return {5.31e+00, 8.74e+00, 1.86e+01, 4.27e+01};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
// } else if ( mu == Parameter("mu", )
// && mu_bar == Parameter("mu", )
// && mu_hat == Parameter("mu", )) {
// if (type == "energy_mu")
// return {};
// else if (type == "eta_DF_OS2014")
// return {};
// else if (type == "eta_DF_OS2014_*")
// return {};
// else if (type == "eta_OS2014")
// return {};
// else if (type == "eta_OS2014_*")
// return {};
// else if (type == "eff_OS2014_*_mu")
// return {};
// else if (type == "eff_OS2014_mu")
// return {};
// else
// EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if ( mu == 1
&& mu_bar == 1
&& mu_hat == 1) {
if (type == "energy_mu")
return {3.28e-01, 1.60e-01, 7.78e-02, 3.47e-02};
else if (type == "eta_NC_OS2014")
return {1.66e-01, 7.89e-02, 3.91e-02, 1.95e-02};
else if (type == "eta_R_OS2014_*")
return {1.02e+00, 5.09e-01, 2.55e-01, 1.28e-01};
else if (type == "eta_DF_OS2014_*")
return {3.55e-01, 1.76e-01, 8.73e-02, 4.35e-02};
else if (type == "eta_OS2014_*")
return {1.54e+00, 7.64e-01, 3.81e-01, 1.91e-01};
else if (type == "eff_OS2014_*_mu")
return {4.69e+00, 4.76e+00, 4.90e+00, 5.49e+00};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[2 2 1]") {
if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {5.08e-01, 2.55e-01, 1.27e-01, 6.38e-02};
else if (type == "eta_OS2014_*")
return {1.03e+00, 5.09e-01, 2.54e-01, 1.27e-01};
else if (type == "eff_OS2014_*_mu")
return {3.14e+00, 3.17e+00, 3.26e+00, 3.65e+00};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[2 2 1]_H_with_h") {
if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {5.08e-01, 1.27e-01, 3.11e-02, 6.71e-03};
else if (type == "eta_OS2014_*")
return {1.03e+00, 3.82e-01, 1.57e-01, 6.97e-02};
else if (type == "eff_OS2014_*_mu")
return {3.14e+00, 2.38e+00, 2.02e+00, 2.01e+00};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[4 4 1]") {
if (mu == 0.1 && mu_bar == 0.1 && mu_hat == 0.1) {
if (type == "eff_OS2014_*_mu")
return {2.24e+00, 2.22e+00, 2.27e+00, 2.49e+00};
else if (type == "eff_OS2014_mu")
return {2.24e+00, 2.22e+00, 2.27e+00, 2.49e+00};
else if (type == "eta_DF_OS2014")
return {1.25e+00, 7.37e-01, 3.69e-01, 1.83e-01};
else if (type == "eta_DF_OS2014_*")
return {1.25e+00, 7.37e-01, 3.69e-01, 1.83e-01};
else if (type == "eta_OS2014")
return {1.97e+00, 1.18e+00, 5.71e-01, 2.71e-01};
else if (type == "eta_OS2014_*")
return {1.97e+00, 1.18e+00, 5.71e-01, 2.71e-01};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 1 && mu_bar == 1 && mu_hat == 0.1) {
if (type == "eff_OS2014_*_mu")
return {1.68e+00, 1.69e+00, 1.73e+00, 1.94e+00};
else if (type == "eff_OS2014_mu")
return {1.44e+01, 2.75e+01, 5.52e+01, 1.22e+02};
else if (type == "eta_DF_OS2014")
return {1.36e+00, 1.33e+00, 1.33e+00, 1.32e+00};
else if (type == "eta_DF_OS2014_*")
return {4.13e-01, 2.05e-01, 1.02e-01, 5.06e-02};
else if (type == "eta_OS2014")
return {4.71e+00, 4.42e+00, 4.30e+00, 4.24e+00};
else if (type == "eta_OS2014_*")
return {5.50e-01, 2.71e-01, 1.35e-01, 6.74e-02};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 0.1 && mu_bar == 0.1 && mu_hat == 1) {
if (type == "eff_OS2014_*_mu")
return {4.99e+00, 4.94e+00, 5.01e+00, 5.53e+00};
else if (type == "eff_OS2014_mu")
return {4.44e+00, 8.02e+00, 1.78e+01, 4.18e+01};
else if (type == "eta_DF_OS2014")
return {1.01e+00, 1.21e+00, 1.35e+00, 1.41e+00};
else if (type == "eta_DF_OS2014_*")
return {1.16e+00, 6.90e-01, 3.34e-01, 1.62e-01};
else if (type == "eta_OS2014")
return {3.91e+00, 4.27e+00, 4.48e+00, 4.55e+00};
else if (type == "eta_OS2014_*")
return {4.39e+00, 2.63e+00, 1.26e+00, 6.01e-01};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {2.54e-01, 1.27e-01, 6.37e-02, 3.19e-02};
else if (type == "eta_OS2014_*")
return {7.74e-01, 3.82e-01, 1.90e-01, 9.49e-02};
else if (type == "eff_OS2014_*_mu")
return {2.36e+00, 2.38e+00, 2.44e+00, 2.73e+00};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[8 8 1]") {
if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {1.09e-01, 5.90e-02, 3.11e-02, 1.58e-02};
else if (type == "eta_OS2014_*")
return {6.29e-01, 3.14e-01, 1.57e-01, 7.89e-02};
else if (type == "eff_OS2014_*_mu")
return {1.92e+00, 1.95e+00, 2.02e+00, 2.27e+00};
} else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else
EXPECT_TRUE(false) << "test results missing for partitioning: " << test_case.partitioning();
return {};
} // ... results(...)
}; // BlockSWIPDGStudyExpectations
template class BlockSWIPDGStudyExpectations< TestCaseType, 1 >;
} // namespace Tests
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // HAVE_ALUGRID
<commit_msg>[test...expectations.OS2014] clear all since the testcase changed<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "config.h"
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
# include <dune/hdd/linearelliptic/testcases/OS2014.hh>
# include "linearelliptic-block-swipdg-expectations.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
typedef TestCases::OS2014::ParametricBlockConvergence< ALUGrid< 2, 2, simplex, conforming > > TestCaseType;
namespace Tests {
template< bool anything >
class BlockSWIPDGStudyExpectations< TestCaseType, 1, anything >
: public internal::BlockSWIPDGStudyExpectationsBase< TestCaseType, 1 >
{
public:
static std::vector< double > results(const TestCaseType& test_case, const std::string type)
{
if (test_case.num_refinements() != 3) {
EXPECT_TRUE(false) << "test results missing for num_refinements: " << test_case.num_refinements();
return {};
}
const auto mu = test_case.parameters().at("mu");
const auto mu_bar = test_case.parameters().at("mu_bar");
const auto mu_hat = test_case.parameters().at("mu_hat");
if (test_case.partitioning() == "[1 1 1]") {
if (mu == 0.1 && mu_bar == 0.1 && mu_hat == 1) {
if (type == "eta_DF_OS2014")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else if (type == "eff_OS2014_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "energy_mu")
return {};
else if (type == "eta_NC_OS2014")
return {};
else if (type == "eta_R_OS2014_*")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[2 2 1]") {
if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[2 2 1]_H_with_h") {
if (mu == 1 && mu_bar == 1 && mu_hat == 0.1) {
if (type == "eta_OS2014_*_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[4 4 1]") {
if (mu == 0.1 && mu_bar == 0.1 && mu_hat == 0.1) {
if (type == "eff_OS2014_*_mu")
return {};
else if (type == "eff_OS2014_mu")
return {};
else if (type == "eta_DF_OS2014")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014")
return {};
else if (type == "eta_OS2014_*")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 1 && mu_bar == 1 && mu_hat == 0.1) {
if (type == "eff_OS2014_*_mu")
return {};
else if (type == "eff_OS2014_mu")
return {};
else if (type == "eta_DF_OS2014")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014")
return {};
else if (type == "eta_OS2014_*")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 0.1 && mu_bar == 0.1 && mu_hat == 1) {
if (type == "eff_OS2014_*_mu")
return {};
else if (type == "eff_OS2014_mu")
return {};
else if (type == "eta_DF_OS2014")
return {};
else if (type == "eta_DF_OS2014_*")
return {};
else if (type == "eta_OS2014")
return {};
else if (type == "eta_OS2014_*")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else if (test_case.partitioning() == "[8 8 1]") {
if (mu == 1 && mu_bar == 1 && mu_hat == 1) {
if (type == "eta_R_OS2014_*")
return {};
else if (type == "eta_OS2014_*")
return {};
else if (type == "eff_OS2014_*_mu")
return {};
else
EXPECT_TRUE(false) << "test results missing for type: " << type;
} else
EXPECT_TRUE(false) << "test results missing for parameters: mu = " << mu << "\n"
<< " mu_bar = " << mu_bar << "\n"
<< " mu_hat = " << mu_hat;
} else
EXPECT_TRUE(false) << "test results missing for partitioning: " << test_case.partitioning();
return {};
} // ... results(...)
}; // BlockSWIPDGStudyExpectations
template class BlockSWIPDGStudyExpectations< TestCaseType, 1 >;
} // namespace Tests
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // HAVE_ALUGRID
<|endoftext|> |
<commit_before>/**
* @file joint_interpolation_planner.cpp
* @brief Joint interpolation planner for moveit.
*
* This class is used to represent a joint interpolated path planner for
* moveit. This planner does not have the inherent ability to avoid
* collision. It does check if the path created is collision free before it
* returns a trajectory. If a collision is found it returns an empty
* trajectory and moveit error.
*
* @author Levi Armstrong
* @date May 4, 2015
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2015, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 <constrained_ik/moveit_interface/joint_interpolation_planner.h>
#include <ros/ros.h>
#include <eigen3/Eigen/Core>
#include <eigen_conversions/eigen_msg.h>
#include <moveit/robot_state/conversions.h>
namespace constrained_ik
{
bool JointInterpolationPlanner::solve(planning_interface::MotionPlanDetailedResponse &res)
{
planning_interface::MotionPlanResponse response;
bool success = solve(response);
// construct the compact response from the detailed one
res.trajectory_.push_back(response.trajectory_);
res.processing_time_.push_back(response.planning_time_);
res.description_.push_back("Joint interpolation Planner");
res.error_code_ = response.error_code_;
return success;
}
bool JointInterpolationPlanner::solve(planning_interface::MotionPlanResponse &res)
{
ros::WallTime start_time = ros::WallTime::now();
robot_model::RobotModelConstPtr rob_model = planning_scene_->getRobotModel();
robot_state::RobotState start_state(rob_model);
robot_state::robotStateMsgToRobotState(request_.start_state, start_state);
robot_state::RobotState goal_state = start_state;
robot_state::RobotStatePtr mid_state;
const robot_model::JointModelGroup *group_model = rob_model->getJointModelGroup(request_.group_name);
std::vector<std::string> joint_names = group_model->getActiveJointModelNames();
std::vector<std::string> link_names = group_model->getLinkModelNames();
Eigen::Affine3d goal_pose;
std::vector<double> pos(1);
robot_trajectory::RobotTrajectoryPtr traj(new robot_trajectory::RobotTrajectory(rob_model, request_.group_name));
ROS_INFO_STREAM("Joint Interpolated Planner will plan for group: " << request_.group_name <<" with tip link '"<<link_names.back() <<"'");
// if we have path constraints, we prefer interpolating in pose space
if (!request_.goal_constraints[0].joint_constraints.empty())
{
for(unsigned int i = 0; i < request_.goal_constraints[0].joint_constraints.size(); i++)
{
pos[0]=request_.goal_constraints[0].joint_constraints[i].position;
goal_state.setJointPositions(joint_names[i], pos);
ROS_DEBUG("Setting joint %s from %f to position %f", request_.goal_constraints[0].joint_constraints[i].joint_name.c_str(),
*start_state.getJointPositions(joint_names[i]), request_.goal_constraints[0].joint_constraints[i].position);
}
}
else
{
geometry_msgs::Pose pose;
if (!request_.goal_constraints[0].position_constraints.empty() && !request_.goal_constraints[0].orientation_constraints.empty())
{
pose.position = request_.goal_constraints[0].position_constraints[0].constraint_region.primitive_poses[0].position;
pose.orientation = request_.goal_constraints[0].orientation_constraints[0].orientation;
}
else if (!request_.goal_constraints[0].position_constraints.empty() && request_.goal_constraints[0].orientation_constraints.empty())
{
tf::poseEigenToMsg(start_state.getFrameTransform(link_names.back()), pose);
pose.position = request_.goal_constraints[0].position_constraints[0].constraint_region.primitive_poses[0].position;
}
else if (request_.goal_constraints[0].position_constraints.empty() && !request_.goal_constraints[0].orientation_constraints.empty())
{
tf::poseEigenToMsg(start_state.getFrameTransform(link_names.back()), pose);
pose.orientation = request_.goal_constraints[0].orientation_constraints[0].orientation;
}
else
{
ROS_ERROR("No constraint was passed with request!");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS;
return false;
}
tf::poseMsgToEigen(pose, goal_pose);
if(!goal_state.setFromIK(group_model, goal_pose, link_names.back()))
{
ROS_ERROR("Joint Interpolated Planner goal pose is out of reach");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::NO_IK_SOLUTION;
return false;
}
}
// Calculate delta for for moveit interpolation function
double dt;
Eigen::VectorXd jv_step;
Eigen::VectorXd jv_start;
Eigen::VectorXd delta;
start_state.copyJointGroupPositions(request_.group_name, jv_start);
mid_state = robot_model::RobotStatePtr(new robot_model::RobotState(start_state));
start_state.interpolate(goal_state, 0.1, *mid_state);
mid_state->copyJointGroupPositions(request_.group_name, jv_step);
delta = (jv_step - jv_start).cwiseAbs();
dt = joint_discretization_step_*(0.1/delta.maxCoeff());
// Generate Path
int steps = (1.0/dt) + 1;
dt = 1.0/steps;
for (int j=0; j<=steps; j++)
{
if (j!=steps)
start_state.interpolate(goal_state, j*dt, *mid_state);
else
start_state.interpolate(goal_state, 1, *mid_state);
traj->addSuffixWayPoint(*mid_state, 0.0);
if (terminate_)
break;
res.planning_time_ = (ros::WallTime::now() - start_time).toSec();
if (res.planning_time_ > request_.allowed_planning_time)
{
ROS_ERROR("Joint Interpolated Planner timed out. :(");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::TIMED_OUT;
return false;
}
}
// Check if planner was terminated
if (terminate_)
{
ROS_INFO("Joint Interpolated Planner was terminated!");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
// Check if traj is a collision free path
if (planning_scene_->isPathValid(*traj, request_.group_name))
{
ROS_INFO("Joint Interpolated Planner generated a collision-free trajectory with %i points! :)",steps);
res.trajectory_=traj;
res.error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
return true;
}
else
{
ROS_INFO("Joint interpolated trajectory is not collision free. :(");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
}
void JointInterpolationPlanner::setPlannerConfiguration(double joint_discretization_step, bool debug_mode)
{
if (joint_discretization_step > 0)
joint_discretization_step_ = joint_discretization_step;
else
ROS_ERROR("Joint Interpolated Planner joint discretization step must be greater than zero.");
debug_mode_ = debug_mode;
}
void JointInterpolationPlanner::resetPlannerConfiguration()
{
joint_discretization_step_ = DEFAULT_JOINT_DISCRETIZATION_STEP;
debug_mode_ = false;
}
} //namespace constrained_ik
<commit_msg>use Eigen::Isometry3d or Affine3d based on ros version<commit_after>/**
* @file joint_interpolation_planner.cpp
* @brief Joint interpolation planner for moveit.
*
* This class is used to represent a joint interpolated path planner for
* moveit. This planner does not have the inherent ability to avoid
* collision. It does check if the path created is collision free before it
* returns a trajectory. If a collision is found it returns an empty
* trajectory and moveit error.
*
* @author Levi Armstrong
* @date May 4, 2015
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2015, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 <constrained_ik/moveit_interface/joint_interpolation_planner.h>
#include <ros/ros.h>
#include <eigen3/Eigen/Core>
#include <eigen_conversions/eigen_msg.h>
#include <moveit/robot_state/conversions.h>
namespace constrained_ik
{
bool JointInterpolationPlanner::solve(planning_interface::MotionPlanDetailedResponse &res)
{
planning_interface::MotionPlanResponse response;
bool success = solve(response);
// construct the compact response from the detailed one
res.trajectory_.push_back(response.trajectory_);
res.processing_time_.push_back(response.planning_time_);
res.description_.push_back("Joint interpolation Planner");
res.error_code_ = response.error_code_;
return success;
}
bool JointInterpolationPlanner::solve(planning_interface::MotionPlanResponse &res)
{
ros::WallTime start_time = ros::WallTime::now();
robot_model::RobotModelConstPtr rob_model = planning_scene_->getRobotModel();
robot_state::RobotState start_state(rob_model);
robot_state::robotStateMsgToRobotState(request_.start_state, start_state);
robot_state::RobotState goal_state = start_state;
robot_state::RobotStatePtr mid_state;
const robot_model::JointModelGroup *group_model = rob_model->getJointModelGroup(request_.group_name);
std::vector<std::string> joint_names = group_model->getActiveJointModelNames();
std::vector<std::string> link_names = group_model->getLinkModelNames();
#if ROS_VERSION_MINIMUM(1, 14, 0) //melodic
Eigen::Isometry3d goal_pose;
#else
Eigen::Affine3d goal_pose;
#endif
std::vector<double> pos(1);
robot_trajectory::RobotTrajectoryPtr traj(new robot_trajectory::RobotTrajectory(rob_model, request_.group_name));
ROS_INFO_STREAM("Joint Interpolated Planner will plan for group: " << request_.group_name <<" with tip link '"<<link_names.back() <<"'");
// if we have path constraints, we prefer interpolating in pose space
if (!request_.goal_constraints[0].joint_constraints.empty())
{
for(unsigned int i = 0; i < request_.goal_constraints[0].joint_constraints.size(); i++)
{
pos[0]=request_.goal_constraints[0].joint_constraints[i].position;
goal_state.setJointPositions(joint_names[i], pos);
ROS_DEBUG("Setting joint %s from %f to position %f", request_.goal_constraints[0].joint_constraints[i].joint_name.c_str(),
*start_state.getJointPositions(joint_names[i]), request_.goal_constraints[0].joint_constraints[i].position);
}
}
else
{
geometry_msgs::Pose pose;
if (!request_.goal_constraints[0].position_constraints.empty() && !request_.goal_constraints[0].orientation_constraints.empty())
{
pose.position = request_.goal_constraints[0].position_constraints[0].constraint_region.primitive_poses[0].position;
pose.orientation = request_.goal_constraints[0].orientation_constraints[0].orientation;
}
else if (!request_.goal_constraints[0].position_constraints.empty() && request_.goal_constraints[0].orientation_constraints.empty())
{
tf::poseEigenToMsg(start_state.getFrameTransform(link_names.back()), pose);
pose.position = request_.goal_constraints[0].position_constraints[0].constraint_region.primitive_poses[0].position;
}
else if (request_.goal_constraints[0].position_constraints.empty() && !request_.goal_constraints[0].orientation_constraints.empty())
{
tf::poseEigenToMsg(start_state.getFrameTransform(link_names.back()), pose);
pose.orientation = request_.goal_constraints[0].orientation_constraints[0].orientation;
}
else
{
ROS_ERROR("No constraint was passed with request!");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS;
return false;
}
tf::poseMsgToEigen(pose, goal_pose);
if(!goal_state.setFromIK(group_model, goal_pose, link_names.back()))
{
ROS_ERROR("Joint Interpolated Planner goal pose is out of reach");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::NO_IK_SOLUTION;
return false;
}
}
// Calculate delta for for moveit interpolation function
double dt;
Eigen::VectorXd jv_step;
Eigen::VectorXd jv_start;
Eigen::VectorXd delta;
start_state.copyJointGroupPositions(request_.group_name, jv_start);
mid_state = robot_model::RobotStatePtr(new robot_model::RobotState(start_state));
start_state.interpolate(goal_state, 0.1, *mid_state);
mid_state->copyJointGroupPositions(request_.group_name, jv_step);
delta = (jv_step - jv_start).cwiseAbs();
dt = joint_discretization_step_*(0.1/delta.maxCoeff());
// Generate Path
int steps = (1.0/dt) + 1;
dt = 1.0/steps;
for (int j=0; j<=steps; j++)
{
if (j!=steps)
start_state.interpolate(goal_state, j*dt, *mid_state);
else
start_state.interpolate(goal_state, 1, *mid_state);
traj->addSuffixWayPoint(*mid_state, 0.0);
if (terminate_)
break;
res.planning_time_ = (ros::WallTime::now() - start_time).toSec();
if (res.planning_time_ > request_.allowed_planning_time)
{
ROS_ERROR("Joint Interpolated Planner timed out. :(");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::TIMED_OUT;
return false;
}
}
// Check if planner was terminated
if (terminate_)
{
ROS_INFO("Joint Interpolated Planner was terminated!");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
// Check if traj is a collision free path
if (planning_scene_->isPathValid(*traj, request_.group_name))
{
ROS_INFO("Joint Interpolated Planner generated a collision-free trajectory with %i points! :)",steps);
res.trajectory_=traj;
res.error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
return true;
}
else
{
ROS_INFO("Joint interpolated trajectory is not collision free. :(");
res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
}
void JointInterpolationPlanner::setPlannerConfiguration(double joint_discretization_step, bool debug_mode)
{
if (joint_discretization_step > 0)
joint_discretization_step_ = joint_discretization_step;
else
ROS_ERROR("Joint Interpolated Planner joint discretization step must be greater than zero.");
debug_mode_ = debug_mode;
}
void JointInterpolationPlanner::resetPlannerConfiguration()
{
joint_discretization_step_ = DEFAULT_JOINT_DISCRETIZATION_STEP;
debug_mode_ = false;
}
} //namespace constrained_ik
<|endoftext|> |
<commit_before>/*
* SchemeSmobAtom.c
*
* Scheme small objects (SMOBS) for opencog atom properties
*
* Copyright (c) 2008,2009 Linas Vepstas <[email protected]>
*/
#ifdef HAVE_GUILE
#include <vector>
#include <libguile.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/TruthValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Verify that SCM arg is an actual opencog Handle; returning Handle
*
* This routine is meant for validating arguments passed into
* guile-wrapped C++ code.
*
* This routine takes an SCM arg and a string subroutine name. It
* verifies that the arg is actually a handle (and not, for example,
* an int, string, etc.) If its not a handle, it throws an SCM error,
* using the subroutine name in the error message. (Such an error is
* caught by the shell, and printed as a stack trace at the shell
* prompt). If the arg is a handle, then the actual opencog handle
* is returned.
*/
Handle SchemeSmob::verify_handle (SCM satom, const char * subrname, int pos)
{
Handle h(scm_to_handle(satom));
if (Handle::UNDEFINED == h)
scm_wrong_type_arg_msg(subrname, pos, satom, "opencog atom");
return h;
}
/* ============================================================== */
/**
* Return the string name of the atom
*/
SCM SchemeSmob::ss_name (SCM satom)
{
std::string name;
Handle h = verify_handle(satom, "cog-name");
NodePtr nnn(NodeCast(h));
if (nnn) name = nnn->getName();
SCM str = scm_from_locale_string(name.c_str());
return str;
}
SCM SchemeSmob::ss_type (SCM satom)
{
Handle h = verify_handle(satom, "cog-type");
Type t = h->getType();
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_locale_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
return sym;
}
SCM SchemeSmob::ss_arity (SCM satom)
{
Handle h = verify_handle(satom, "cog-arity");
Arity ari = 0;
LinkPtr lll(LinkCast(h));
if (lll) ari = lll->getArity();
/* Arity is currently an unsigned short */
SCM sari = scm_from_ushort(ari);
return sari;
}
SCM SchemeSmob::ss_tv (SCM satom)
{
Handle h = verify_handle(satom, "cog-tv");
TruthValuePtr tv(h->getTruthValue());
TruthValue *stv = tv->rawclone();
return take_tv(stv);
}
SCM SchemeSmob::ss_set_tv (SCM satom, SCM stv)
{
Handle h = verify_handle(satom, "cog-set-tv!");
TruthValue *tv = verify_tv(stv, "cog-set-tv!", 2);
h->setTruthValue(tv->clone());
return satom;
}
SCM SchemeSmob::ss_av (SCM satom)
{
Handle h = verify_handle(satom, "cog-av");
AttentionValue *sav = h->getAttentionValue()->rawclone();
return take_av(sav);
}
SCM SchemeSmob::ss_set_av (SCM satom, SCM sav)
{
Handle h = verify_handle(satom, "cog-set-av!");
AttentionValue *av = verify_av(sav, "cog-set-av!", 2);
h->setAttentionValue(av->clone());
return satom;
}
SCM SchemeSmob::ss_inc_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-inc-vlti!");
atomspace->incVLTI(h);
return satom;
}
SCM SchemeSmob::ss_dec_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-dec-vlti!");
atomspace->decVLTI(h);
return satom;
}
/* ============================================================== */
/**
* Convert the outgoing set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_outgoing_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-outgoping-set");
LinkPtr lll(LinkCast(h));
if (NULL == lll) return SCM_EOL;
const HandleSeq& oset = lll->getOutgoingSet();
SCM list = SCM_EOL;
for (int i = oset.size()-1; i >= 0; i--)
{
Handle h = oset[i];
SCM smob = handle_to_scm(h);
list = scm_cons (smob, list);
}
return list;
}
/* ============================================================== */
/**
* Convert the incoming set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_incoming_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-incoming-set");
std::vector<Handle> iset = atomspace->getIncoming(h);
size_t isz = iset.size();
if (0 == isz) return SCM_EOL;
// This reverses the order of the incoming set, but so what ...
SCM head = SCM_EOL;
for (size_t i=0; i<isz; i++) {
Handle hi = iset[i];
SCM smob = handle_to_scm(hi);
head = scm_cons(smob, head);
}
return head;
}
/* ============================================================== */
/**
* Apply proceedure proc to all atoms of type stype
* If the proceedure returns something other than #f,
* terminate the loop.
*/
SCM SchemeSmob::ss_map_type (SCM proc, SCM stype)
{
Type t = verify_atom_type (stype, "cog-map-type");
// Get all of the handles of the indicated type
std::list<Handle> handle_set;
atomspace->getHandlesByType(back_inserter(handle_set), t, false);
// Loop over all handles in the handle set.
// Call proc on each handle, in turn.
// Break out of the loop if proc returns anything other than #f
std::list<Handle>::iterator i;
for (i = handle_set.begin(); i != handle_set.end(); i++) {
Handle h = *i;
SCM smob = handle_to_scm(h);
SCM rc = scm_call_1(proc, smob);
if (!scm_is_false(rc)) return rc;
}
return SCM_BOOL_F;
}
/* ============================================================== */
/**
* Return a list of all of the atom types in the system.
*/
SCM SchemeSmob::ss_get_types (void)
{
SCM list = SCM_EOL;
Type t = classserver().getNumberOfClasses();
while (1) {
t--;
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_locale_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
if (0 == t) break;
}
return list;
}
/**
* Return a list of the subtypes of the indicated type
*/
SCM SchemeSmob::ss_get_subtypes (SCM stype)
{
SCM list = SCM_EOL;
Type t = verify_atom_type(stype, "cog-get-subtypes");
std::vector<Type> subl;
unsigned int ns = classserver().getChildren(t, std::back_inserter(subl));
for (unsigned int i=0; i<ns; i++) {
t = subl[i];
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_locale_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
}
return list;
}
/**
* Return true if a type
*/
SCM SchemeSmob::ss_type_p (SCM stype)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
char * ct = scm_to_locale_string(stype);
Type t = classserver().getType(ct);
free(ct);
if (NOTYPE == t) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if a subtype
*/
SCM SchemeSmob::ss_subtype_p (SCM stype, SCM schild)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
char * ct = scm_to_locale_string(stype);
Type parent = classserver().getType(ct);
free(ct);
if (NOTYPE == parent) return SCM_BOOL_F;
// Now investigate the child ...
if (scm_is_true(scm_symbol_p(schild)))
schild = scm_symbol_to_string(schild);
if (scm_is_false(scm_string_p(schild)))
return SCM_BOOL_F;
ct = scm_to_locale_string(schild);
Type child = classserver().getType(ct);
free(ct);
if (NOTYPE == child) return SCM_BOOL_F;
if (classserver().isA(child, parent)) return SCM_BOOL_T;
return SCM_BOOL_F;
}
#endif
/* ===================== END OF FILE ============================ */
<commit_msg>whitespace cleanup<commit_after>/*
* SchemeSmobAtom.c
*
* Scheme small objects (SMOBS) for opencog atom properties
*
* Copyright (c) 2008,2009 Linas Vepstas <[email protected]>
*/
#ifdef HAVE_GUILE
#include <vector>
#include <libguile.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/TruthValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Verify that SCM arg is an actual opencog Handle; returning Handle
*
* This routine is meant for validating arguments passed into
* guile-wrapped C++ code.
*
* This routine takes an SCM arg and a string subroutine name. It
* verifies that the arg is actually a handle (and not, for example,
* an int, string, etc.) If its not a handle, it throws an SCM error,
* using the subroutine name in the error message. (Such an error is
* caught by the shell, and printed as a stack trace at the shell
* prompt). If the arg is a handle, then the actual opencog handle
* is returned.
*/
Handle SchemeSmob::verify_handle (SCM satom, const char * subrname, int pos)
{
Handle h(scm_to_handle(satom));
if (Handle::UNDEFINED == h)
scm_wrong_type_arg_msg(subrname, pos, satom, "opencog atom");
return h;
}
/* ============================================================== */
/**
* Return the string name of the atom
*/
SCM SchemeSmob::ss_name (SCM satom)
{
std::string name;
Handle h = verify_handle(satom, "cog-name");
NodePtr nnn(NodeCast(h));
if (nnn) name = nnn->getName();
SCM str = scm_from_locale_string(name.c_str());
return str;
}
SCM SchemeSmob::ss_type (SCM satom)
{
Handle h = verify_handle(satom, "cog-type");
Type t = h->getType();
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_locale_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
return sym;
}
SCM SchemeSmob::ss_arity (SCM satom)
{
Handle h = verify_handle(satom, "cog-arity");
Arity ari = 0;
LinkPtr lll(LinkCast(h));
if (lll) ari = lll->getArity();
/* Arity is currently an unsigned short */
SCM sari = scm_from_ushort(ari);
return sari;
}
SCM SchemeSmob::ss_tv (SCM satom)
{
Handle h = verify_handle(satom, "cog-tv");
TruthValuePtr tv(h->getTruthValue());
TruthValue *stv = tv->rawclone();
return take_tv(stv);
}
SCM SchemeSmob::ss_set_tv (SCM satom, SCM stv)
{
Handle h = verify_handle(satom, "cog-set-tv!");
TruthValue *tv = verify_tv(stv, "cog-set-tv!", 2);
h->setTruthValue(tv->clone());
return satom;
}
SCM SchemeSmob::ss_av (SCM satom)
{
Handle h = verify_handle(satom, "cog-av");
AttentionValue *sav = h->getAttentionValue()->rawclone();
return take_av(sav);
}
SCM SchemeSmob::ss_set_av (SCM satom, SCM sav)
{
Handle h = verify_handle(satom, "cog-set-av!");
AttentionValue *av = verify_av(sav, "cog-set-av!", 2);
h->setAttentionValue(av->clone());
return satom;
}
SCM SchemeSmob::ss_inc_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-inc-vlti!");
atomspace->incVLTI(h);
return satom;
}
SCM SchemeSmob::ss_dec_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-dec-vlti!");
atomspace->decVLTI(h);
return satom;
}
/* ============================================================== */
/**
* Convert the outgoing set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_outgoing_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-outgoping-set");
LinkPtr lll(LinkCast(h));
if (NULL == lll) return SCM_EOL;
const HandleSeq& oset = lll->getOutgoingSet();
SCM list = SCM_EOL;
for (int i = oset.size()-1; i >= 0; i--)
{
Handle h = oset[i];
SCM smob = handle_to_scm(h);
list = scm_cons (smob, list);
}
return list;
}
/* ============================================================== */
/**
* Convert the incoming set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_incoming_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-incoming-set");
std::vector<Handle> iset = atomspace->getIncoming(h);
size_t isz = iset.size();
if (0 == isz) return SCM_EOL;
// This reverses the order of the incoming set, but so what ...
SCM head = SCM_EOL;
for (size_t i=0; i<isz; i++) {
Handle hi = iset[i];
SCM smob = handle_to_scm(hi);
head = scm_cons(smob, head);
}
return head;
}
/* ============================================================== */
/**
* Apply proceedure proc to all atoms of type stype
* If the proceedure returns something other than #f,
* terminate the loop.
*/
SCM SchemeSmob::ss_map_type (SCM proc, SCM stype)
{
Type t = verify_atom_type (stype, "cog-map-type");
// Get all of the handles of the indicated type
std::list<Handle> handle_set;
atomspace->getHandlesByType(back_inserter(handle_set), t, false);
// Loop over all handles in the handle set.
// Call proc on each handle, in turn.
// Break out of the loop if proc returns anything other than #f
std::list<Handle>::iterator i;
for (i = handle_set.begin(); i != handle_set.end(); i++) {
Handle h = *i;
SCM smob = handle_to_scm(h);
SCM rc = scm_call_1(proc, smob);
if (!scm_is_false(rc)) return rc;
}
return SCM_BOOL_F;
}
/* ============================================================== */
/**
* Return a list of all of the atom types in the system.
*/
SCM SchemeSmob::ss_get_types (void)
{
SCM list = SCM_EOL;
Type t = classserver().getNumberOfClasses();
while (1) {
t--;
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_locale_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
if (0 == t) break;
}
return list;
}
/**
* Return a list of the subtypes of the indicated type
*/
SCM SchemeSmob::ss_get_subtypes (SCM stype)
{
SCM list = SCM_EOL;
Type t = verify_atom_type(stype, "cog-get-subtypes");
std::vector<Type> subl;
unsigned int ns = classserver().getChildren(t, std::back_inserter(subl));
for (unsigned int i=0; i<ns; i++) {
t = subl[i];
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_locale_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
}
return list;
}
/**
* Return true if a type
*/
SCM SchemeSmob::ss_type_p (SCM stype)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
char * ct = scm_to_locale_string(stype);
Type t = classserver().getType(ct);
free(ct);
if (NOTYPE == t) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if a subtype
*/
SCM SchemeSmob::ss_subtype_p (SCM stype, SCM schild)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
char * ct = scm_to_locale_string(stype);
Type parent = classserver().getType(ct);
free(ct);
if (NOTYPE == parent) return SCM_BOOL_F;
// Now investigate the child ...
if (scm_is_true(scm_symbol_p(schild)))
schild = scm_symbol_to_string(schild);
if (scm_is_false(scm_string_p(schild)))
return SCM_BOOL_F;
ct = scm_to_locale_string(schild);
Type child = classserver().getType(ct);
free(ct);
if (NOTYPE == child) return SCM_BOOL_F;
if (classserver().isA(child, parent)) return SCM_BOOL_T;
return SCM_BOOL_F;
}
#endif
/* ===================== END OF FILE ============================ */
<|endoftext|> |
<commit_before>#include "features2d.h"
#include "features2d_DescriptorMatcher.h"
#include "features2d_FeatureDetector.h"
#include "features2d_AgastFeatureDetector.h"
#include "features2d_AKAZE.h"
#include "features2d_BRISK.h"
#include "features2d_GFTTDetector.h"
#include "features2d_KAZE.h"
#include "features2d_MSER.h"
#include "features2d_ORB.h"
#include "features2d_SimpleBlobDetector.h"
#include "features2d_FastFeatureDetector.h"
#include "features2d_KeyPointsFilter.h"
<commit_msg>resolved compile mistake of BOWKMeansTrainer<commit_after>#include "features2d.h"
#include "features2d_AgastFeatureDetector.h"
#include "features2d_AKAZE.h"
#include "features2d_BOW.h"
#include "features2d_BRISK.h"
#include "features2d_DescriptorMatcher.h"
#include "features2d_FastFeatureDetector.h"
#include "features2d_FeatureDetector.h"
#include "features2d_GFTTDetector.h"
#include "features2d_KAZE.h"
#include "features2d_KeyPointsFilter.h"
#include "features2d_MSER.h"
#include "features2d_ORB.h"
#include "features2d_SimpleBlobDetector.h"
<|endoftext|> |
<commit_before>#include "analysis/ReachingDefinitions/Srg/MarkerSRGBuilderFS.h"
using namespace dg::analysis::rd::srg;
/**
* Saves the current definition of certain variable in given block
* Used from value numbering procedures.
*/
void MarkerSRGBuilderFS::writeVariableStrong(const DefSite& var, NodeT *assignment, BlockT *block) {
detail::Interval interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
current_weak_def[var.target][block].killOverlapping(interval);
current_def[var.target][block].killOverlapping(interval);
// remember the last definition
current_def[var.target][block].add(std::move(interval), assignment);
}
void MarkerSRGBuilderFS::writeVariableWeak(const DefSite& var, NodeT *assignment, BlockT *block) {
current_weak_def[var.target][block].add(concretize(detail::Interval{var.offset, var.len}, var.target->getSize()), assignment);
}
std::vector<MarkerSRGBuilderFS::NodeT *> MarkerSRGBuilderFS::readVariable(const DefSite& var, BlockT *read, BlockT *start, const Intervals& covered) {
assert( read );
// use specialized method for unknown memory
if (var.target == UNKNOWN_MEMORY) {
std::unordered_map<NodeT *, detail::DisjointIntervalSet> found;
return std::vector<NodeT *> { readUnknown(read, found) };
}
auto& block_defs = current_def[var.target];
auto it = block_defs.find(read);
std::vector<NodeT *> result;
const auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
// find weak defs
auto block_weak_defs = current_weak_def[var.target][read].collectAll(interval);
auto unknown_defs = current_weak_def[UNKNOWN_MEMORY][read].collectAll(interval);
// find the last definition
if (it != block_defs.end()) {
Intervals cov;
bool is_covered = false;
std::tie(result, cov, is_covered) = it->second.collect(interval, covered);
if (!is_covered && (!interval.isUnknown() || read != start)) {
NodeT *phi = readVariableRecursive(var, read, start, cov);
result.push_back(phi);
}
} else {
result.push_back(readVariableRecursive(var, read, start, covered));
}
// add weak defs & unknown weak defs
std::move(block_weak_defs.begin(), block_weak_defs.end(), std::back_inserter(result));
std::move(unknown_defs.begin(), unknown_defs.end(), std::back_inserter(result));
return result;
}
MarkerSRGBuilderFS::NodeT *MarkerSRGBuilderFS::addPhiOperands(const DefSite& var, std::unique_ptr<MarkerSRGBuilderFS::NodeT>&& phi, BlockT *block, BlockT *start, const std::vector<detail::Interval>& covered) {
const auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
phi->addDef(var, true);
phi->addUse(var);
for (BlockT *pred : block->predecessors()) {
std::vector<NodeT *> assignments;
Intervals cov;
bool is_covered = false;
std::tie(assignments, cov, is_covered) = last_def[var.target][pred].collect(interval, covered);
// add weak updates
auto weak_defs = last_weak_def[var.target][pred].collectAll(interval);
std::move(weak_defs.begin(), weak_defs.end(), std::back_inserter(assignments));
if (!is_covered || (interval.isUnknown() && block != start)) {
std::vector<NodeT *> assignments2 = readVariable(var, pred, start, cov);
std::move(assignments2.begin(), assignments2.end(), std::back_inserter(assignments));
}
for (auto& assignment : assignments)
insertSrgEdge(assignment, phi.get(), var);
}
auto *node = tryRemoveTrivialPhi(phi.release());
if (node->getType() == RDNodeType::PHI) {
phi_nodes.push_back(std::unique_ptr<NodeT>{node});
}
return node;
}
MarkerSRGBuilderFS::NodeT* MarkerSRGBuilderFS::tryRemoveTrivialPhi(NodeT *phi) {
auto operands = srg.find(phi);
// is @phi undef?
if (operands == srg.end()) {
return phi;
}
NodeT *same = nullptr;
// is phi node non-trivial?
for (auto& edge : operands->second) {
NodeT* dest = edge.second;
if (dest == same || dest == phi) {
continue;
} else if (same != nullptr) {
return phi;
}
same = dest;
}
if (same == nullptr) {
// the phi is unreachable or in the start block
return phi;
}
replacePhi(phi, same);
auto users_it = reverse_srg.find(phi);
if (users_it == reverse_srg.end()) {
// no users...
return phi;
}
auto& users = users_it->second;
for (auto& edge : users) {
NodeT* user = edge.second;
if (user != phi && user->getType() == RDNodeType::PHI) {
NodeT *replacement = tryRemoveTrivialPhi(user);
assert(replacement);
if (replacement->getType() == RDNodeType::PHI) {
phi_nodes.push_back(std::unique_ptr<NodeT>{ replacement });
}
}
}
return same;
}
void MarkerSRGBuilderFS::replacePhi(NodeT *phi, NodeT *replacement) {
// the purpose of this method is to reroute definitions to uses
auto uses_it = reverse_srg.find(phi);
if (uses_it == reverse_srg.end() || uses_it->second.size() == 0) {
// there is nothing to transplant
return;
}
auto& uses = uses_it->second;
for (auto& use_edge : uses) {
DefSite var = use_edge.first;
NodeT *dest = use_edge.second;
removeSrgEdge(dest, phi, var);
insertSrgEdge(dest, replacement, var);
}
}
MarkerSRGBuilderFS::NodeT *MarkerSRGBuilderFS::readVariableRecursive(const DefSite& var, BlockT *block, BlockT *start, const std::vector<detail::Interval>& covered) {
std::vector<NodeT *> result;
auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
auto phi = std::unique_ptr<NodeT>(new NodeT(RDNodeType::PHI));
phi->setBasicBlock(block);
// writeVariableStrong kills current weak definitions, which are needed in the phi node, so we need to lookup them first.
auto weak_defs = current_weak_def[var.target][block].collectAll(interval);
for (auto& assignment : weak_defs)
insertSrgEdge(assignment, phi.get(), var);
writeVariableStrong(var, phi.get(), block);
NodeT *val = addPhiOperands(var, std::move(phi), block, start, covered);
return val;
}
/*
Find relevant definitions of all variables and join them into a single phi node.
Only search until all variables are 'covered' or an allocation is found.
Branching will be solved via phi nodes
*/
MarkerSRGBuilderFS::NodeT *MarkerSRGBuilderFS::readUnknown(BlockT *read, std::unordered_map<NodeT *, detail::DisjointIntervalSet>& found) {
std::vector<NodeT *> result;
// try to find definitions of UNKNOWN_MEMORY in the current block.
auto& block_defs = current_def[UNKNOWN_MEMORY];
auto it = block_defs.find(read);
const auto interval = detail::Interval{Offset::UNKNOWN, Offset::UNKNOWN};
// does any definition exist in this block?
if (it != block_defs.end()) {
Intervals cov;
bool is_covered = false;
result = it->second.collectAll(interval);
// no phi necessary for single definition
if (result.size() == 1) {
return *result.begin();
} else {
std::unique_ptr<NodeT> phi{new NodeT(RDNodeType::PHI)};
NodeT *ptr = phi.get();
phi->setBasicBlock(read);
writeVariableStrong(UNKNOWN_MEMORY, phi.get(), read);
for (auto& node : result) {
insertSrgEdge(node, phi.get(), UNKNOWN_MEMORY);
}
phi_nodes.push_back(std::move(phi));
return ptr;
}
}
// otherwise, we need to traverse the entire program
// find definitions in current block
for (auto& var_blocks : current_def) {
// we do not care which variable it is -- we are searching for definitions of all variables
auto& var = var_blocks.second;
// TODO: if not already covered(@var)
// second thought: the coverage check cost might be too high
for (auto& block_defs : var_blocks.second) {
if (block_defs.first == read) {
for (auto& interval_val : block_defs.second) {
// now we are iterating over the interval map
result.push_back(interval_val.second);
// TODO: only if @interval_val.second is a strong update, add coverage information
}
}
}
}
// find weak definitions in current block
for (auto& var_blocks : current_weak_def) {
// we do not care which variable it is -- we are searching for all definitions of all variables
for (auto& block_defs : var_blocks.second) {
if (block_defs.first == read) {
for (auto& interval_val : block_defs.second) {
// now we are iterating the interval map
result.push_back(interval_val.second);
}
}
}
}
// continue the search for definitions in previous blocks
for (auto& pred : read->predecessors()) {
auto assignment = readUnknown(pred, found);
result.push_back(assignment);
}
// if not phi node necessary
if (result.size() == 1) {
return *result.begin();
}
// make a phi node for unknown memory
auto phi = std::unique_ptr<NodeT>(new NodeT(RDNodeType::PHI));
phi->setBasicBlock(read);
for (auto& node : result) {
insertSrgEdge(node, phi.get(), UNKNOWN_MEMORY);
}
writeVariableStrong(UNKNOWN_MEMORY, phi.get(), read);
NodeT *ptr = phi.get();
phi_nodes.push_back(std::move(phi));
// TODO: return also coverage information
return ptr;
}
<commit_msg>rd: srg: disconnect replaced phi nodes from defs<commit_after>#include "analysis/ReachingDefinitions/Srg/MarkerSRGBuilderFS.h"
using namespace dg::analysis::rd::srg;
/**
* Saves the current definition of certain variable in given block
* Used from value numbering procedures.
*/
void MarkerSRGBuilderFS::writeVariableStrong(const DefSite& var, NodeT *assignment, BlockT *block) {
detail::Interval interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
current_weak_def[var.target][block].killOverlapping(interval);
current_def[var.target][block].killOverlapping(interval);
// remember the last definition
current_def[var.target][block].add(std::move(interval), assignment);
}
void MarkerSRGBuilderFS::writeVariableWeak(const DefSite& var, NodeT *assignment, BlockT *block) {
current_weak_def[var.target][block].add(concretize(detail::Interval{var.offset, var.len}, var.target->getSize()), assignment);
}
std::vector<MarkerSRGBuilderFS::NodeT *> MarkerSRGBuilderFS::readVariable(const DefSite& var, BlockT *read, BlockT *start, const Intervals& covered) {
assert( read );
// use specialized method for unknown memory
if (var.target == UNKNOWN_MEMORY) {
std::unordered_map<NodeT *, detail::DisjointIntervalSet> found;
return std::vector<NodeT *> { readUnknown(read, found) };
}
auto& block_defs = current_def[var.target];
auto it = block_defs.find(read);
std::vector<NodeT *> result;
const auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
// find weak defs
auto block_weak_defs = current_weak_def[var.target][read].collectAll(interval);
auto unknown_defs = current_weak_def[UNKNOWN_MEMORY][read].collectAll(interval);
// find the last definition
if (it != block_defs.end()) {
Intervals cov;
bool is_covered = false;
std::tie(result, cov, is_covered) = it->second.collect(interval, covered);
if (!is_covered && (!interval.isUnknown() || read != start)) {
NodeT *phi = readVariableRecursive(var, read, start, cov);
result.push_back(phi);
}
} else {
result.push_back(readVariableRecursive(var, read, start, covered));
}
// add weak defs & unknown weak defs
std::move(block_weak_defs.begin(), block_weak_defs.end(), std::back_inserter(result));
std::move(unknown_defs.begin(), unknown_defs.end(), std::back_inserter(result));
return result;
}
MarkerSRGBuilderFS::NodeT *MarkerSRGBuilderFS::addPhiOperands(const DefSite& var, std::unique_ptr<MarkerSRGBuilderFS::NodeT>&& phi, BlockT *block, BlockT *start, const std::vector<detail::Interval>& covered) {
const auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
phi->addDef(var, true);
phi->addUse(var);
for (BlockT *pred : block->predecessors()) {
std::vector<NodeT *> assignments;
Intervals cov;
bool is_covered = false;
std::tie(assignments, cov, is_covered) = last_def[var.target][pred].collect(interval, covered);
// add weak updates
auto weak_defs = last_weak_def[var.target][pred].collectAll(interval);
std::move(weak_defs.begin(), weak_defs.end(), std::back_inserter(assignments));
if (!is_covered || (interval.isUnknown() && block != start)) {
std::vector<NodeT *> assignments2 = readVariable(var, pred, start, cov);
std::move(assignments2.begin(), assignments2.end(), std::back_inserter(assignments));
}
for (auto& assignment : assignments)
insertSrgEdge(assignment, phi.get(), var);
}
auto *node = tryRemoveTrivialPhi(phi.release());
if (node->getType() == RDNodeType::PHI) {
phi_nodes.push_back(std::unique_ptr<NodeT>{node});
}
return node;
}
MarkerSRGBuilderFS::NodeT* MarkerSRGBuilderFS::tryRemoveTrivialPhi(NodeT *phi) {
auto operands = srg.find(phi);
// is @phi undef?
if (operands == srg.end()) {
return phi;
}
NodeT *same = nullptr;
// is phi node non-trivial?
for (auto& edge : operands->second) {
NodeT* dest = edge.second;
if (dest == same || dest == phi) {
continue;
} else if (same != nullptr) {
return phi;
}
same = dest;
}
if (same == nullptr) {
// the phi is unreachable or in the start block
return phi;
}
replacePhi(phi, same);
auto users_it = reverse_srg.find(phi);
if (users_it == reverse_srg.end()) {
// no users...
return phi;
}
auto& users = users_it->second;
for (auto& edge : users) {
NodeT* user = edge.second;
if (user != phi && user->getType() == RDNodeType::PHI) {
NodeT *replacement = tryRemoveTrivialPhi(user);
assert(replacement);
if (replacement->getType() == RDNodeType::PHI) {
phi_nodes.push_back(std::unique_ptr<NodeT>{ replacement });
}
}
}
return same;
}
void MarkerSRGBuilderFS::replacePhi(NodeT *phi, NodeT *replacement) {
// the purpose of this method is to reroute definitions to uses
auto uses_it = reverse_srg.find(phi);
if (uses_it == reverse_srg.end() || uses_it->second.size() == 0) {
// there is nothing to transplant
return;
}
auto defs_it = srg.find(phi);
if (defs_it != srg.end()) {
auto& defs = defs_it->second;
for (auto& def_edge : defs) {
DefSite& var = def_edge.first;
NodeT *dest = def_edge.second;
removeSrgEdge(phi, dest, var);
}
}
auto& uses = uses_it->second;
for (auto& use_edge : uses) {
DefSite var = use_edge.first;
NodeT *dest = use_edge.second;
removeSrgEdge(dest, phi, var);
insertSrgEdge(dest, replacement, var);
}
}
MarkerSRGBuilderFS::NodeT *MarkerSRGBuilderFS::readVariableRecursive(const DefSite& var, BlockT *block, BlockT *start, const std::vector<detail::Interval>& covered) {
std::vector<NodeT *> result;
auto interval = concretize(detail::Interval{var.offset, var.len}, var.target->getSize());
auto phi = std::unique_ptr<NodeT>(new NodeT(RDNodeType::PHI));
phi->setBasicBlock(block);
// writeVariableStrong kills current weak definitions, which are needed in the phi node, so we need to lookup them first.
auto weak_defs = current_weak_def[var.target][block].collectAll(interval);
for (auto& assignment : weak_defs)
insertSrgEdge(assignment, phi.get(), var);
writeVariableStrong(var, phi.get(), block);
NodeT *val = addPhiOperands(var, std::move(phi), block, start, covered);
return val;
}
/*
Find relevant definitions of all variables and join them into a single phi node.
Only search until all variables are 'covered' or an allocation is found.
Branching will be solved via phi nodes
*/
MarkerSRGBuilderFS::NodeT *MarkerSRGBuilderFS::readUnknown(BlockT *read, std::unordered_map<NodeT *, detail::DisjointIntervalSet>& found) {
std::vector<NodeT *> result;
// try to find definitions of UNKNOWN_MEMORY in the current block.
auto& block_defs = current_def[UNKNOWN_MEMORY];
auto it = block_defs.find(read);
const auto interval = detail::Interval{Offset::UNKNOWN, Offset::UNKNOWN};
// does any definition exist in this block?
if (it != block_defs.end()) {
Intervals cov;
bool is_covered = false;
result = it->second.collectAll(interval);
// no phi necessary for single definition
if (result.size() == 1) {
return *result.begin();
} else {
std::unique_ptr<NodeT> phi{new NodeT(RDNodeType::PHI)};
NodeT *ptr = phi.get();
phi->setBasicBlock(read);
writeVariableStrong(UNKNOWN_MEMORY, phi.get(), read);
for (auto& node : result) {
insertSrgEdge(node, phi.get(), UNKNOWN_MEMORY);
}
phi_nodes.push_back(std::move(phi));
return ptr;
}
}
// otherwise, we need to traverse the entire program
// find definitions in current block
for (auto& var_blocks : current_def) {
// we do not care which variable it is -- we are searching for definitions of all variables
auto& var = var_blocks.second;
// TODO: if not already covered(@var)
// second thought: the coverage check cost might be too high
for (auto& block_defs : var_blocks.second) {
if (block_defs.first == read) {
for (auto& interval_val : block_defs.second) {
// now we are iterating over the interval map
result.push_back(interval_val.second);
// TODO: only if @interval_val.second is a strong update, add coverage information
}
}
}
}
// find weak definitions in current block
for (auto& var_blocks : current_weak_def) {
// we do not care which variable it is -- we are searching for all definitions of all variables
for (auto& block_defs : var_blocks.second) {
if (block_defs.first == read) {
for (auto& interval_val : block_defs.second) {
// now we are iterating the interval map
result.push_back(interval_val.second);
}
}
}
}
// continue the search for definitions in previous blocks
for (auto& pred : read->predecessors()) {
auto assignment = readUnknown(pred, found);
result.push_back(assignment);
}
// if not phi node necessary
if (result.size() == 1) {
return *result.begin();
}
// make a phi node for unknown memory
auto phi = std::unique_ptr<NodeT>(new NodeT(RDNodeType::PHI));
phi->setBasicBlock(read);
for (auto& node : result) {
insertSrgEdge(node, phi.get(), UNKNOWN_MEMORY);
}
writeVariableStrong(UNKNOWN_MEMORY, phi.get(), read);
NodeT *ptr = phi.get();
phi_nodes.push_back(std::move(phi));
// TODO: return also coverage information
return ptr;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 by Glenn Hickey ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include "sgsql.h"
using namespace std;
using namespace hal;
SGSQL::SGSQL() : _sgBuilder(0), _sg(0)
{
}
SGSQL::~SGSQL()
{
}
void SGSQL::writeDb(const SGBuilder* sgBuilder, const string& sqlInsertPath,
const string& fastaPath)
{
_sgBuilder = sgBuilder;
_sg = _sgBuilder->getSideGraph();
assert(_sg != NULL);
_outPath = sqlInsertPath;
_outStream.open(_outPath.c_str());
assert(_outStream);
_faPath = fastaPath;
_faStream.open(_faPath.c_str());
assert(_faStream);
_checksumMap.clear();
writeFasta();
writeFastaInsert();
writeSequenceInserts();
writeReferenceInserts();
writeJoinInserts();
writePathInserts();
_outStream.close();
_faStream.close();
}
void SGSQL::writeFasta()
{
string dnaBuffer;
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
_sgBuilder->getSequenceString(seq, dnaBuffer);
assert((sg_int_t)dnaBuffer.length() == seq->getLength());
_faStream << ">" << seq->getName() << "\n";
size_t len;
for (size_t pos = 0; pos < dnaBuffer.length(); pos += len)
{
len = min((size_t)80, dnaBuffer.length() - pos);
_faStream << dnaBuffer.substr(pos, len) << "\n";
}
string checksum;
getChecksum(dnaBuffer, checksum);
_checksumMap.insert(pair<sg_seqid_t, string>(seq->getID(), checksum));
}
}
/*
CREATE TABLE FASTA (ID INTEGER PRIMARY KEY,
fastaURI TEXT NOT NULL);
*/
void SGSQL::writeFastaInsert()
{
_outStream << "INSERT INTO FASTA VALUES ("
<< 0 << ", "
<< "file://" << _faPath << ")\n";
_outStream << endl;
}
/*
CREATE TABLE Sequence (ID INTEGER PRIMARY KEY,
-- FASTA file URI and record name within it containing sequence
fastaID INTEGER, -- If null, query enclosing ReferenceSet's fastaID
sequenceRecordName TEXT NOT NULL,
md5checksum TEXT NOT NULL,
length INTEGER NOT NULL,
FOREIGN KEY(fastaID) REFERENCES FASTA(ID));
*/
void SGSQL::writeSequenceInserts()
{
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
map<sg_seqid_t, string>::const_iterator j = _checksumMap.find(seq->getID());
assert(j != _checksumMap.end());
_outStream << "INSERT INTO Sequence VALUES ("
<< seq->getID() << ", "
<< 0 << ", "
<< "\'"<< seq->getName() << "\', "
<< "\'" << j->second << "\', "
<< seq->getLength() << ");\n";
}
_outStream << endl;
}
/*
-- References
CREATE TABLE Reference (ID INTEGER PRIMARY KEY,
name TEXT NOT NULL,
updateTime DATE NOT NULL,
sequenceID INTEGER NOT NULL,
start INTEGER NOT NULL, -- default 0.
length INTEGER, -- if null, assume sequence.lenght - start
md5checksum TEXT, -- if null, assume sequence.md5checksum
isDerived BOOLEAN NOT NULL,
sourceDivergence REAL, -- may be null if isDerived is FALSE (not sure if it needs to be stored)?
ncbiTaxonID INTEGER, -- ID from http://www.ncbi.nlm.nih.gov/taxonomy, may be null
isPrimary BOOLEAN NOT NULL,
FOREIGN KEY(sequenceID) REFERENCES Sequence(ID));
CREATE TABLE ReferenceAccession (ID INTEGER PRIMARY KEY,
referenceID INTEGER NOT NULL,
accessionID TEXT NOT NULL,
FOREIGN KEY(referenceID) REFERENCES Reference(ID));
-- Reference sets
CREATE TABLE ReferenceSet (ID INTEGER PRIMARY KEY,
ncbiTaxonID INT, -- may be null, may differ from ncbiTaxonID of contained Reference record
description TEXT, -- may be null, but shouldn't be?
fastaID INTEGER, -- may be null. TODO: What if both this and a member Reference's Sequence fastaID are null?
assemblyID TEXT, -- may be null, but REALLY shouldn't be?
isDerived BOOLEAN NOT NULL,
FOREIGN KEY(fastaID) REFERENCES FASTA(ID));
CREATE TABLE ReferenceSetAccession (ID INTEGER PRIMARY KEY,
referenceSetID INTEGER NOT NULL,
accessionID TEXT NOT NULL,
FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID));
CREATE TABLE Reference_ReferenceSet_Join (referenceID INTEGER NOT NULL,
referenceSetID INTEGER NOT NULL,
PRIMARY KEY(referenceID, referenceSetID),
FOREIGN KEY(referenceID) REFERENCES Reference(ID),
FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID));
*/
void SGSQL::writeReferenceInserts()
{
// make a reference set for each input genome from the HAL
_refMap.clear();
_refMap.insert(pair<string, size_t>(_sgBuilder->getPrimaryGenomeName(), 0));
_outStream << "INSERT INTO ReferenceSet VALUES "
<< "(0, NULL, "
<< "\'HAL Genome " + _sgBuilder->getPrimaryGenomeName() << "\'"
<< ", 0, NULL, \'FALSE\')\n";
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
string halGenomeName = _sgBuilder->getHalGenomeName(seq);
if (_refMap.find(halGenomeName) == _refMap.end())
{
sg_int_t id = _refMap.size();
_refMap.insert(pair<string, size_t>(halGenomeName, id));
// single reference set
_outStream << "INSERT INTO ReferenceSet VALUES "
<< "(" << id
<< ", NULL, "
<< "\'HAL Genome " + halGenomeName << "\'"
<< ", 0, NULL, \'FALSE\')\n";
}
}
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
string halGenomeName = _sgBuilder->getHalGenomeName(seq);
bool primary = halGenomeName == _sgBuilder->getPrimaryGenomeName();
_outStream << "INSERT INTO Reference VALUES ("
<< seq->getID() << ", "
<< "\'"<< seq->getName() << "\', "
<< "date(\'now\')" << ", "
<< seq->getID() << ", "
<< _refMap.find(halGenomeName)->second << ", "
<< "NULL " << ", "
<< "NULL " << ", "
<< "\'FALSE\'" << ", "
<< "NULL " << ", "
<< "NULL " << ", "
<< (primary ? "\'TRUE\'" : "\'FALSE\'")
<< ");\n";
}
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
_outStream << "INSERT INTO Reference_ReferenceSet_Join VALUES ("
<< seq->getID() << ", 0);\n";
}
_outStream << endl;
}
/*
CREATE TABLE GraphJoin (ID INTEGER PRIMARY KEY,
-- startJoin defines parent sequence & position that 5' end attaches to.
side1SequenceID INTEGER NOT NULL,
side1Position INTEGER NOT NULL,
side1StrandIsForward BOOLEAN NOT NULL,
-- endJoin defines parent sequence & position that 3' end attaches to.
side2SequenceID INTEGER NOT NULL,
side2Position INTEGER NOT NULL,
side2StrandIsForward BOOLEAN NOT NULL,
FOREIGN KEY(side1SequenceID) REFERENCES Sequence(ID),
FOREIGN KEY(side2SequenceID) REFERENCES Sequence(ID));
*/
void SGSQL::writeJoinInserts()
{
const SideGraph::JoinSet* joinSet = _sg->getJoinSet();
SideGraph::JoinSet::const_iterator i;
size_t count = 0;
for (i = joinSet->begin(); i != joinSet->end(); ++i)
{
const SGJoin* join = *i;
const SGSide& side1 = join->getSide1();
const SGSide& side2 = join->getSide2();
_outStream << "INSERT INTO GraphJoin VALUES ("
<< count++ << ", "
<< side1.getBase().getSeqID() << ", "
<< side1.getBase().getPos() << ", "
<< (side1.getForward() ? "TRUE" : "FALSE") << ", "
<< side2.getBase().getSeqID() << ", "
<< side2.getBase().getPos() << ", "
<< (side2.getForward() ? "TRUE" : "FALSE") << ")\n";
}
_outStream << endl;
}
/*
-- Tables common to both site and allelic models
CREATE TABLE VariantSet (ID INTEGER PRIMARY KEY,
referenceSetID INTEGER NOT NULL,
-- datasetID -- TODO: what is this? What table would it point to?
vcfURI TEXT NOT NULL,
FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID));
-- Site (classical) model tables
-- We shouldn't be storing anything here besides what's needed for the Allele table join.
CREATE TABLE Variant (ID INTEGER PRIMARY KEY,
variantName TEXT NOT NULL, -- corresponding variant in the VCF, accessible via index?
variantSetID INTEGER NOT NULL,
FOREIGN KEY(variantSetID) REFERENCES VariantSet(ID)); -- any metadata needed here?
-- is the Call table even needed here? Can't it all be obtained from the VCF?
CREATE TABLE Call (callSetID INTEGER,
variantID INTEGER NOT NULL,
PRIMARY KEY(callSetID, variantID),
FOREIGN KEY(callSetID) REFERENCES CallSet(ID),
FOREIGN KEY(variantID) REFERENCES Variant(ID));
-- Allelic model tables
CREATE TABLE Allele (ID INTEGER PRIMARY KEY,
variantSetID INTEGER, -- TODO: Can this be null? cf. Heng Li's question about Alleles and VariantSets
FOREIGN KEY(variantSetID) REFERENCES VariantSet(ID));
CREATE TABLE AllelePathItem (alleleID INTEGER,
pathItemIndex INTEGER NOT NULL, -- one-based index of this pathItem within the entire path
sequenceID INTEGER NOT NULL, start INTEGER NOT NULL,
length INTEGER NOT NULL, strandIsForward BOOLEAN NOT NULL,
PRIMARY KEY(alleleID, pathItemIndex),
FOREIGN KEY(alleleID) REFERENCES allele(ID),
FOREIGN KEY(sequenceID) REFERENCES Sequence(ID));
*/
void SGSQL::writePathInserts()
{
// For every genome in the input HAL, we create one Variant Set.
// For every sequence in a genome, we create one
// Allele, and a list of Allele Path Items.
// create a variant set for every genome
size_t i;
map<string, size_t>::const_iterator j;
for (i = 0, j = _refMap.begin(); j != _refMap.end(); ++j, ++i)
{
_outStream << "INSERT INTO VariantSet VALUES ("
<< i << ", "
<< i << ", "
<< "hal2sg genome " <<j->first << ");\n";
}
_outStream << endl;
// create an allele for every sequence;
const vector<const Sequence*>& halSequences = _sgBuilder->getHalSequences();
for (i = 0; i < halSequences.size(); ++i)
{
_outStream << "INSERT INTO Allele ("
<< i << ", "
<< _refMap.find(halSequences[i]->getGenome()->getName())->second
<< ");\n";
}
_outStream << endl;
// create a path (AellePathItem) for every sequence
for (i = 0; i < halSequences.size(); ++i)
{
_outStream << "-- PATH for HAL input sequence "
<< halSequences[i]->getFullName() << "\n";
vector<SGSegment> path;
_sgBuilder->getHalSequencePath(halSequences[i], path);
for (size_t j = 0; j < path.size(); ++j)
{
_outStream << "INSERT INTO AllelePathItem VALUES ("
<< i << ", "
<< i << ", "
<< path[j].getSide().getBase().getSeqID() << ", "
<< path[j].getSide().getBase().getPos() << ", "
<< path[j].getLength() << ", "
<< (path[j].getSide().getForward() ? "\'TRUE\'" : "\'FALSE\'")
<< ")\n";
}
_outStream <<endl;
}
}
void SGSQL::getChecksum(const string& inputString, string& outputString)
{
outputString = "md5";
}
<commit_msg>Making AllelePathItem item index correct. Closes #2.<commit_after>/*
* Copyright (C) 2015 by Glenn Hickey ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include "sgsql.h"
using namespace std;
using namespace hal;
SGSQL::SGSQL() : _sgBuilder(0), _sg(0)
{
}
SGSQL::~SGSQL()
{
}
void SGSQL::writeDb(const SGBuilder* sgBuilder, const string& sqlInsertPath,
const string& fastaPath)
{
_sgBuilder = sgBuilder;
_sg = _sgBuilder->getSideGraph();
assert(_sg != NULL);
_outPath = sqlInsertPath;
_outStream.open(_outPath.c_str());
assert(_outStream);
_faPath = fastaPath;
_faStream.open(_faPath.c_str());
assert(_faStream);
_checksumMap.clear();
writeFasta();
writeFastaInsert();
writeSequenceInserts();
writeReferenceInserts();
writeJoinInserts();
writePathInserts();
_outStream.close();
_faStream.close();
}
void SGSQL::writeFasta()
{
string dnaBuffer;
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
_sgBuilder->getSequenceString(seq, dnaBuffer);
assert((sg_int_t)dnaBuffer.length() == seq->getLength());
_faStream << ">" << seq->getName() << "\n";
size_t len;
for (size_t pos = 0; pos < dnaBuffer.length(); pos += len)
{
len = min((size_t)80, dnaBuffer.length() - pos);
_faStream << dnaBuffer.substr(pos, len) << "\n";
}
string checksum;
getChecksum(dnaBuffer, checksum);
_checksumMap.insert(pair<sg_seqid_t, string>(seq->getID(), checksum));
}
}
/*
CREATE TABLE FASTA (ID INTEGER PRIMARY KEY,
fastaURI TEXT NOT NULL);
*/
void SGSQL::writeFastaInsert()
{
_outStream << "INSERT INTO FASTA VALUES ("
<< 0 << ", "
<< "file://" << _faPath << ")\n";
_outStream << endl;
}
/*
CREATE TABLE Sequence (ID INTEGER PRIMARY KEY,
-- FASTA file URI and record name within it containing sequence
fastaID INTEGER, -- If null, query enclosing ReferenceSet's fastaID
sequenceRecordName TEXT NOT NULL,
md5checksum TEXT NOT NULL,
length INTEGER NOT NULL,
FOREIGN KEY(fastaID) REFERENCES FASTA(ID));
*/
void SGSQL::writeSequenceInserts()
{
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
map<sg_seqid_t, string>::const_iterator j = _checksumMap.find(seq->getID());
assert(j != _checksumMap.end());
_outStream << "INSERT INTO Sequence VALUES ("
<< seq->getID() << ", "
<< 0 << ", "
<< "\'"<< seq->getName() << "\', "
<< "\'" << j->second << "\', "
<< seq->getLength() << ");\n";
}
_outStream << endl;
}
/*
-- References
CREATE TABLE Reference (ID INTEGER PRIMARY KEY,
name TEXT NOT NULL,
updateTime DATE NOT NULL,
sequenceID INTEGER NOT NULL,
start INTEGER NOT NULL, -- default 0.
length INTEGER, -- if null, assume sequence.lenght - start
md5checksum TEXT, -- if null, assume sequence.md5checksum
isDerived BOOLEAN NOT NULL,
sourceDivergence REAL, -- may be null if isDerived is FALSE (not sure if it needs to be stored)?
ncbiTaxonID INTEGER, -- ID from http://www.ncbi.nlm.nih.gov/taxonomy, may be null
isPrimary BOOLEAN NOT NULL,
FOREIGN KEY(sequenceID) REFERENCES Sequence(ID));
CREATE TABLE ReferenceAccession (ID INTEGER PRIMARY KEY,
referenceID INTEGER NOT NULL,
accessionID TEXT NOT NULL,
FOREIGN KEY(referenceID) REFERENCES Reference(ID));
-- Reference sets
CREATE TABLE ReferenceSet (ID INTEGER PRIMARY KEY,
ncbiTaxonID INT, -- may be null, may differ from ncbiTaxonID of contained Reference record
description TEXT, -- may be null, but shouldn't be?
fastaID INTEGER, -- may be null. TODO: What if both this and a member Reference's Sequence fastaID are null?
assemblyID TEXT, -- may be null, but REALLY shouldn't be?
isDerived BOOLEAN NOT NULL,
FOREIGN KEY(fastaID) REFERENCES FASTA(ID));
CREATE TABLE ReferenceSetAccession (ID INTEGER PRIMARY KEY,
referenceSetID INTEGER NOT NULL,
accessionID TEXT NOT NULL,
FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID));
CREATE TABLE Reference_ReferenceSet_Join (referenceID INTEGER NOT NULL,
referenceSetID INTEGER NOT NULL,
PRIMARY KEY(referenceID, referenceSetID),
FOREIGN KEY(referenceID) REFERENCES Reference(ID),
FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID));
*/
void SGSQL::writeReferenceInserts()
{
// make a reference set for each input genome from the HAL
_refMap.clear();
_refMap.insert(pair<string, size_t>(_sgBuilder->getPrimaryGenomeName(), 0));
_outStream << "INSERT INTO ReferenceSet VALUES "
<< "(0, NULL, "
<< "\'HAL Genome " + _sgBuilder->getPrimaryGenomeName() << "\'"
<< ", 0, NULL, \'FALSE\')\n";
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
string halGenomeName = _sgBuilder->getHalGenomeName(seq);
if (_refMap.find(halGenomeName) == _refMap.end())
{
sg_int_t id = _refMap.size();
_refMap.insert(pair<string, size_t>(halGenomeName, id));
// single reference set
_outStream << "INSERT INTO ReferenceSet VALUES "
<< "(" << id
<< ", NULL, "
<< "\'HAL Genome " + halGenomeName << "\'"
<< ", 0, NULL, \'FALSE\')\n";
}
}
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
string halGenomeName = _sgBuilder->getHalGenomeName(seq);
bool primary = halGenomeName == _sgBuilder->getPrimaryGenomeName();
_outStream << "INSERT INTO Reference VALUES ("
<< seq->getID() << ", "
<< "\'"<< seq->getName() << "\', "
<< "date(\'now\')" << ", "
<< seq->getID() << ", "
<< _refMap.find(halGenomeName)->second << ", "
<< "NULL " << ", "
<< "NULL " << ", "
<< "\'FALSE\'" << ", "
<< "NULL " << ", "
<< "NULL " << ", "
<< (primary ? "\'TRUE\'" : "\'FALSE\'")
<< ");\n";
}
for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i)
{
const SGSequence* seq = _sg->getSequence(i);
_outStream << "INSERT INTO Reference_ReferenceSet_Join VALUES ("
<< seq->getID() << ", 0);\n";
}
_outStream << endl;
}
/*
CREATE TABLE GraphJoin (ID INTEGER PRIMARY KEY,
-- startJoin defines parent sequence & position that 5' end attaches to.
side1SequenceID INTEGER NOT NULL,
side1Position INTEGER NOT NULL,
side1StrandIsForward BOOLEAN NOT NULL,
-- endJoin defines parent sequence & position that 3' end attaches to.
side2SequenceID INTEGER NOT NULL,
side2Position INTEGER NOT NULL,
side2StrandIsForward BOOLEAN NOT NULL,
FOREIGN KEY(side1SequenceID) REFERENCES Sequence(ID),
FOREIGN KEY(side2SequenceID) REFERENCES Sequence(ID));
*/
void SGSQL::writeJoinInserts()
{
const SideGraph::JoinSet* joinSet = _sg->getJoinSet();
SideGraph::JoinSet::const_iterator i;
size_t count = 0;
for (i = joinSet->begin(); i != joinSet->end(); ++i)
{
const SGJoin* join = *i;
const SGSide& side1 = join->getSide1();
const SGSide& side2 = join->getSide2();
_outStream << "INSERT INTO GraphJoin VALUES ("
<< count++ << ", "
<< side1.getBase().getSeqID() << ", "
<< side1.getBase().getPos() << ", "
<< (side1.getForward() ? "TRUE" : "FALSE") << ", "
<< side2.getBase().getSeqID() << ", "
<< side2.getBase().getPos() << ", "
<< (side2.getForward() ? "TRUE" : "FALSE") << ")\n";
}
_outStream << endl;
}
/*
-- Tables common to both site and allelic models
CREATE TABLE VariantSet (ID INTEGER PRIMARY KEY,
referenceSetID INTEGER NOT NULL,
-- datasetID -- TODO: what is this? What table would it point to?
vcfURI TEXT NOT NULL,
FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID));
-- Site (classical) model tables
-- We shouldn't be storing anything here besides what's needed for the Allele table join.
CREATE TABLE Variant (ID INTEGER PRIMARY KEY,
variantName TEXT NOT NULL, -- corresponding variant in the VCF, accessible via index?
variantSetID INTEGER NOT NULL,
FOREIGN KEY(variantSetID) REFERENCES VariantSet(ID)); -- any metadata needed here?
-- is the Call table even needed here? Can't it all be obtained from the VCF?
CREATE TABLE Call (callSetID INTEGER,
variantID INTEGER NOT NULL,
PRIMARY KEY(callSetID, variantID),
FOREIGN KEY(callSetID) REFERENCES CallSet(ID),
FOREIGN KEY(variantID) REFERENCES Variant(ID));
-- Allelic model tables
CREATE TABLE Allele (ID INTEGER PRIMARY KEY,
variantSetID INTEGER, -- TODO: Can this be null? cf. Heng Li's question about Alleles and VariantSets
FOREIGN KEY(variantSetID) REFERENCES VariantSet(ID));
CREATE TABLE AllelePathItem (alleleID INTEGER,
pathItemIndex INTEGER NOT NULL, -- one-based index of this pathItem within the entire path
sequenceID INTEGER NOT NULL, start INTEGER NOT NULL,
length INTEGER NOT NULL, strandIsForward BOOLEAN NOT NULL,
PRIMARY KEY(alleleID, pathItemIndex),
FOREIGN KEY(alleleID) REFERENCES allele(ID),
FOREIGN KEY(sequenceID) REFERENCES Sequence(ID));
*/
void SGSQL::writePathInserts()
{
// For every genome in the input HAL, we create one Variant Set.
// For every sequence in a genome, we create one
// Allele, and a list of Allele Path Items.
// create a variant set for every genome
size_t i;
map<string, size_t>::const_iterator j;
for (i = 0, j = _refMap.begin(); j != _refMap.end(); ++j, ++i)
{
_outStream << "INSERT INTO VariantSet VALUES ("
<< i << ", "
<< i << ", "
<< "hal2sg genome " <<j->first << ");\n";
}
_outStream << endl;
// create an allele for every sequence;
const vector<const Sequence*>& halSequences = _sgBuilder->getHalSequences();
for (i = 0; i < halSequences.size(); ++i)
{
_outStream << "INSERT INTO Allele ("
<< i << ", "
<< _refMap.find(halSequences[i]->getGenome()->getName())->second
<< ");\n";
}
_outStream << endl;
// create a path (AellePathItem) for every sequence
for (i = 0; i < halSequences.size(); ++i)
{
_outStream << "-- PATH for HAL input sequence "
<< halSequences[i]->getFullName() << "\n";
vector<SGSegment> path;
_sgBuilder->getHalSequencePath(halSequences[i], path);
for (size_t j = 0; j < path.size(); ++j)
{
_outStream << "INSERT INTO AllelePathItem VALUES ("
<< i << ", "
<< j << ", "
<< path[j].getSide().getBase().getSeqID() << ", "
<< path[j].getSide().getBase().getPos() << ", "
<< path[j].getLength() << ", "
<< (path[j].getSide().getForward() ? "\'TRUE\'" : "\'FALSE\'")
<< ")\n";
}
_outStream <<endl;
}
}
void SGSQL::getChecksum(const string& inputString, string& outputString)
{
outputString = "md5";
}
<|endoftext|> |
<commit_before><commit_msg>using placeholders works better at the module level for use throughout the file only use the placeholders that are in use<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include "debug.h"
#include "util.h"
#include "object.h"
#include "index.h"
using namespace std;
/// Entry consist of the hash and the serialized object info.
#define INDEX_ENTRYSIZE (64 + 16)
Index::Index()
{
fd = -1;
}
Index::~Index()
{
close();
}
void
Index::open(const string &indexFile)
{
int i, entries;
struct stat sb;
fileName = indexFile;
// Read index
fd = ::open(indexFile.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd < 0) {
perror("open");
cout << "Could not open the index file!" << endl;
assert(false);
return;
};
if (::fstat(fd, &sb) < 0) {
perror("fstat");
return;
}
if (sb.st_size % INDEX_ENTRYSIZE != 0) {
cout << "Index seems dirty please rebuild it!" << endl;
::close(fd);
fd = -1;
exit(1);
return;
}
entries = sb.st_size / INDEX_ENTRYSIZE;
for (i = 0; i < entries; i++) {
int status;
char entry[INDEX_ENTRYSIZE];
string hash, info;
ObjectInfo objInfo;
status = read(fd, &entry, INDEX_ENTRYSIZE);
assert(status == INDEX_ENTRYSIZE);
hash.assign(entry, 64);
info.assign(entry + 64, 16);
objInfo = ObjectInfo(hash.c_str());
objInfo.setInfo(info);
index[hash] = objInfo;
}
::close(fd);
// Reopen append only
fd = ::open(indexFile.c_str(), O_WRONLY | O_APPEND);
assert(fd >= 0); // Assume that the repository lock protects the index
// Delete temporary index if present
if (Util_FileExists(indexFile + ".tmp")) {
Util_DeleteFile(indexFile + ".tmp");
}
}
void
Index::close()
{
if (fd != -1) {
::fsync(fd);
::close(fd);
fd = -1;
}
}
void
Index::rewrite()
{
int fdNew, tmpFd;
string newIndex = fileName + ".tmp";
map<string, ObjectInfo>::iterator it;
fdNew = ::open(newIndex.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fdNew < 0) {
perror("open");
cout << "Could not open a temporary index file!" << endl;
return;
};
// Write new index
for (it = index.begin(); it != index.end(); it++)
{
int status;
string indexLine;
indexLine = (*it).first;
indexLine += (*it).second.getInfo();
status = write(fdNew, indexLine.data(), indexLine.size());
assert(status == indexLine.size());
}
Util_RenameFile(newIndex, fileName);
tmpFd = fd;
fd = fdNew;
::close(tmpFd);
}
void
Index::dump()
{
map<string, ObjectInfo>::iterator it;
cout << "***** BEGIN REPOSITORY INDEX *****" << endl;
for (it = index.begin(); it != index.end(); it++)
{
cout << (*it).first << endl;
}
cout << "***** END REPOSITORY INDEX *****" << endl;
}
void
Index::updateInfo(const string &objId, const ObjectInfo &info)
{
string indexLine;
assert(objId.size() == 64);
/*
* XXX: Extra sanity checking for the hash string
* for (int i = 0; i < 64; i++) {
* char c = objId[i];
* assert((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'));
* }
*/
indexLine = objId;
indexLine += info.getInfo();
write(fd, indexLine.data(), indexLine.size());
}
const ObjectInfo &
Index::getInfo(const string &objId) const
{
map<string, ObjectInfo>::const_iterator it = index.find(objId);
assert(it != index.end());
return (*it).second;
}
bool
Index::hasObject(const string &objId) const
{
map<string, ObjectInfo>::const_iterator it;
it = index.find(objId);
return it != index.end();
}
set<ObjectInfo>
Index::getList()
{
set<ObjectInfo> lst;
map<string, ObjectInfo>::iterator it;
for (it = index.begin(); it != index.end(); it++)
{
lst.insert((*it).second);
}
return lst;
}
<commit_msg>Adding checksum to index.<commit_after>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include "debug.h"
#include "util.h"
#include "object.h"
#include "index.h"
using namespace std;
/// Entry consist of the object hash, object info, and a checksum.
#define INDEX_ENTRYSIZE (64 + 16 + 16)
Index::Index()
{
fd = -1;
}
Index::~Index()
{
close();
}
void
Index::open(const string &indexFile)
{
int i, entries;
struct stat sb;
fileName = indexFile;
// Read index
fd = ::open(indexFile.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd < 0) {
perror("open");
cout << "Could not open the index file!" << endl;
assert(false);
return;
};
if (::fstat(fd, &sb) < 0) {
perror("fstat");
return;
}
if (sb.st_size % INDEX_ENTRYSIZE != 0) {
// XXX: Attempt truncating last entries
cout << "Index seems dirty please rebuild it!" << endl;
::close(fd);
fd = -1;
exit(1);
return;
}
entries = sb.st_size / INDEX_ENTRYSIZE;
for (i = 0; i < entries; i++) {
int status;
char entry[INDEX_ENTRYSIZE];
string hash, info;
ObjectInfo objInfo;
status = read(fd, &entry, INDEX_ENTRYSIZE);
assert(status == INDEX_ENTRYSIZE);
hash.assign(entry, 64);
info.assign(entry + 64, 16);
string entryStr = string().assign(entry, 64 + 16);
string chksum = string().assign(entry + 64 + 16, 16);
string chksumComputed = Util_HashString(entryStr).substr(0, 16);
if (chksum != chksumComputed) {
// XXX: Attempt truncating last entries
cout << "Index has corrupt entries please rebuild it!" << endl;
::close(fd);
fd = -1;
exit(1);
return;
}
objInfo = ObjectInfo(hash.c_str());
objInfo.setInfo(info);
index[hash] = objInfo;
}
::close(fd);
// Reopen append only
fd = ::open(indexFile.c_str(), O_WRONLY | O_APPEND);
assert(fd >= 0); // Assume that the repository lock protects the index
// Delete temporary index if present
if (Util_FileExists(indexFile + ".tmp")) {
Util_DeleteFile(indexFile + ".tmp");
}
}
void
Index::close()
{
if (fd != -1) {
::fsync(fd);
::close(fd);
fd = -1;
}
}
void
Index::rewrite()
{
int fdNew, tmpFd;
string newIndex = fileName + ".tmp";
map<string, ObjectInfo>::iterator it;
fdNew = ::open(newIndex.c_str(), O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fdNew < 0) {
perror("open");
cout << "Could not open a temporary index file!" << endl;
return;
};
// Write new index
for (it = index.begin(); it != index.end(); it++)
{
int status;
string indexLine;
string hash;
indexLine = (*it).first;
indexLine += (*it).second.getInfo();
hash = Util_HashString(indexLine);
indexLine += hash.substr(0, 16);
status = write(fdNew, indexLine.data(), indexLine.size());
assert(status == indexLine.size());
}
Util_RenameFile(newIndex, fileName);
tmpFd = fd;
fd = fdNew;
::close(tmpFd);
}
void
Index::dump()
{
map<string, ObjectInfo>::iterator it;
cout << "***** BEGIN REPOSITORY INDEX *****" << endl;
for (it = index.begin(); it != index.end(); it++)
{
cout << (*it).first << endl;
}
cout << "***** END REPOSITORY INDEX *****" << endl;
}
void
Index::updateInfo(const string &objId, const ObjectInfo &info)
{
string indexLine;
string hash;
assert(objId.size() == 64);
/*
* XXX: Extra sanity checking for the hash string
* for (int i = 0; i < 64; i++) {
* char c = objId[i];
* assert((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'));
* }
*/
indexLine = objId;
indexLine += info.getInfo();
hash = Util_HashString(indexLine);
indexLine += hash.substr(0, 16);
write(fd, indexLine.data(), indexLine.size());
}
const ObjectInfo &
Index::getInfo(const string &objId) const
{
map<string, ObjectInfo>::const_iterator it = index.find(objId);
assert(it != index.end());
return (*it).second;
}
bool
Index::hasObject(const string &objId) const
{
map<string, ObjectInfo>::const_iterator it;
it = index.find(objId);
return it != index.end();
}
set<ObjectInfo>
Index::getList()
{
set<ObjectInfo> lst;
map<string, ObjectInfo>::iterator it;
for (it = index.begin(); it != index.end(); it++)
{
lst.insert((*it).second);
}
return lst;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "GlobalContext.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "VisitorUtils.hpp"
#include "Type.hpp"
#include "ast/GetConstantValue.hpp"
using namespace eddic;
GlobalContext::GlobalContext() : Context(NULL) {
Val zero = 0;
variables["_mem_start"] = std::make_shared<Variable>("_mem_start", INT, Position(PositionType::GLOBAL, "_mem_start"), zero);
variables["_mem_start"]->addReference(); //In order to not display a warning
variables["_mem_last"] = std::make_shared<Variable>("_mem_last", INT, Position(PositionType::GLOBAL, "_mem_last"), zero);
variables["_mem_last"]->addReference(); //In order to not display a warning
defineStandardFunctions();
}
std::unordered_map<std::string, std::shared_ptr<Variable>> GlobalContext::getVariables(){
return variables;
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type){
//Only global array have no value, other types have all values
assert(type->is_array());
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position);
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type, ast::Value& value){
auto val = visit(ast::GetConstantValue(), value);
if(type->is_const()){
Position position(PositionType::CONST);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
void GlobalContext::addFunction(std::shared_ptr<Function> function){
m_functions[function->mangledName] = function;
}
std::shared_ptr<Function> GlobalContext::getFunction(const std::string& function){
ASSERT(exists(function), "The function must exists");
return m_functions[function];
}
bool GlobalContext::exists(const std::string& function){
return m_functions.find(function) != m_functions.end();
}
void GlobalContext::add_struct(std::shared_ptr<Struct> struct_){
m_structs[struct_->name] = struct_;
}
std::shared_ptr<Struct> GlobalContext::get_struct(const std::string& struct_){
return m_structs[struct_];
}
int GlobalContext::member_offset(std::shared_ptr<Struct> struct_, const std::string& member){
int offset = 0;
for(auto m : struct_->members){
if(m->name == member){
return offset;
}
offset += m->type->size();
}
ASSERT_PATH_NOT_TAKEN("The member is not part of the struct");
}
int GlobalContext::size_of_struct(const std::string& struct_name){
int struct_size = 0;
auto struct_ = get_struct(struct_name);
for(auto m : struct_->members){
struct_size += m->type->size();
}
return struct_size;
}
bool GlobalContext::is_recursively_nested(const std::string& struct_name, unsigned int left){
if(left == 0){
return true;
}
auto struct_ = get_struct(struct_name);
for(auto m : struct_->members){
auto type = m->type;
if(type->is_custom_type()){
if(is_recursively_nested(type->type(), left - 1)){
return true;
}
}
}
return false;
}
bool GlobalContext::is_recursively_nested(const std::string& struct_){
return is_recursively_nested(struct_, 100);
}
bool GlobalContext::struct_exists(const std::string& struct_){
return m_structs.find(struct_) != m_structs.end();
}
void GlobalContext::addReference(const std::string& function){
ASSERT(exists(function), "The function must exists");
++(m_functions[function]->references);
}
void GlobalContext::removeReference(const std::string& function){
ASSERT(exists(function), "The function must exists");
--(m_functions[function]->references);
}
int GlobalContext::referenceCount(const std::string& function){
ASSERT(exists(function), "The function must exists");
return m_functions[function]->references;
}
void GlobalContext::addPrintFunction(const std::string& function, std::shared_ptr<const Type> parameterType){
auto printFunction = std::make_shared<Function>(VOID, "print");
printFunction->standard = true;
printFunction->mangledName = function;
printFunction->parameters.push_back({"a", parameterType});
addFunction(printFunction);
}
void GlobalContext::defineStandardFunctions(){
auto printLineFunction = std::make_shared<Function>(VOID, "print");
printLineFunction->standard = true;
printLineFunction->mangledName = "_F7println";
addFunction(printLineFunction);
//print string
addPrintFunction("_F5printS", STRING);
addPrintFunction("_F7printlnS", STRING);
//print integer
addPrintFunction("_F5printI", INT);
addPrintFunction("_F7printlnI", INT);
//print bool
addPrintFunction("_F5printB", BOOL);
addPrintFunction("_F7printlnB", BOOL);
//print float
addPrintFunction("_F5printF", FLOAT);
addPrintFunction("_F7printlnF", FLOAT);
//concat function
auto concatFunction = std::make_shared<Function>(STRING, "concat");
concatFunction->standard = true;
concatFunction->mangledName = "_F6concatSS";
concatFunction->parameters.push_back({"a", STRING});
concatFunction->parameters.push_back({"b", STRING});
addFunction(concatFunction);
//alloc function
auto allocFunction = std::make_shared<Function>(new_pointer_type(INT), "alloc");
allocFunction->standard = true;
allocFunction->mangledName = "_F5allocI";
allocFunction->parameters.push_back({"a", INT});
addFunction(allocFunction);
//free function
auto freeFunction = std::make_shared<Function>(VOID, "free");
freeFunction->standard = true;
freeFunction->mangledName = "_F4freePI";
freeFunction->parameters.push_back({"a", INT});
addFunction(freeFunction);
//time function
auto timeFunction = std::make_shared<Function>(VOID, "time");
timeFunction->standard = true;
timeFunction->mangledName = "_F4timeAI";
timeFunction->parameters.push_back({"a", new_array_type(INT)});
addFunction(timeFunction);
//duration function
auto durationFunction = std::make_shared<Function>(VOID, "duration");
durationFunction->standard = true;
durationFunction->mangledName = "_F8durationAIAI";
durationFunction->parameters.push_back({"a", new_array_type(INT)});
durationFunction->parameters.push_back({"b", new_array_type(INT)});
addFunction(durationFunction);
}
GlobalContext::FunctionMap GlobalContext::functions(){
return m_functions;
}
<commit_msg>Add function declarations to print char<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "GlobalContext.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "VisitorUtils.hpp"
#include "Type.hpp"
#include "ast/GetConstantValue.hpp"
using namespace eddic;
GlobalContext::GlobalContext() : Context(NULL) {
Val zero = 0;
variables["_mem_start"] = std::make_shared<Variable>("_mem_start", INT, Position(PositionType::GLOBAL, "_mem_start"), zero);
variables["_mem_start"]->addReference(); //In order to not display a warning
variables["_mem_last"] = std::make_shared<Variable>("_mem_last", INT, Position(PositionType::GLOBAL, "_mem_last"), zero);
variables["_mem_last"]->addReference(); //In order to not display a warning
defineStandardFunctions();
}
std::unordered_map<std::string, std::shared_ptr<Variable>> GlobalContext::getVariables(){
return variables;
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type){
//Only global array have no value, other types have all values
assert(type->is_array());
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position);
}
std::shared_ptr<Variable> GlobalContext::addVariable(const std::string& variable, std::shared_ptr<const Type> type, ast::Value& value){
auto val = visit(ast::GetConstantValue(), value);
if(type->is_const()){
Position position(PositionType::CONST);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
Position position(PositionType::GLOBAL, variable);
return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}
void GlobalContext::addFunction(std::shared_ptr<Function> function){
m_functions[function->mangledName] = function;
}
std::shared_ptr<Function> GlobalContext::getFunction(const std::string& function){
ASSERT(exists(function), "The function must exists");
return m_functions[function];
}
bool GlobalContext::exists(const std::string& function){
return m_functions.find(function) != m_functions.end();
}
void GlobalContext::add_struct(std::shared_ptr<Struct> struct_){
m_structs[struct_->name] = struct_;
}
std::shared_ptr<Struct> GlobalContext::get_struct(const std::string& struct_){
return m_structs[struct_];
}
int GlobalContext::member_offset(std::shared_ptr<Struct> struct_, const std::string& member){
int offset = 0;
for(auto m : struct_->members){
if(m->name == member){
return offset;
}
offset += m->type->size();
}
ASSERT_PATH_NOT_TAKEN("The member is not part of the struct");
}
int GlobalContext::size_of_struct(const std::string& struct_name){
int struct_size = 0;
auto struct_ = get_struct(struct_name);
for(auto m : struct_->members){
struct_size += m->type->size();
}
return struct_size;
}
bool GlobalContext::is_recursively_nested(const std::string& struct_name, unsigned int left){
if(left == 0){
return true;
}
auto struct_ = get_struct(struct_name);
for(auto m : struct_->members){
auto type = m->type;
if(type->is_custom_type()){
if(is_recursively_nested(type->type(), left - 1)){
return true;
}
}
}
return false;
}
bool GlobalContext::is_recursively_nested(const std::string& struct_){
return is_recursively_nested(struct_, 100);
}
bool GlobalContext::struct_exists(const std::string& struct_){
return m_structs.find(struct_) != m_structs.end();
}
void GlobalContext::addReference(const std::string& function){
ASSERT(exists(function), "The function must exists");
++(m_functions[function]->references);
}
void GlobalContext::removeReference(const std::string& function){
ASSERT(exists(function), "The function must exists");
--(m_functions[function]->references);
}
int GlobalContext::referenceCount(const std::string& function){
ASSERT(exists(function), "The function must exists");
return m_functions[function]->references;
}
void GlobalContext::addPrintFunction(const std::string& function, std::shared_ptr<const Type> parameterType){
auto printFunction = std::make_shared<Function>(VOID, "print");
printFunction->standard = true;
printFunction->mangledName = function;
printFunction->parameters.push_back({"a", parameterType});
addFunction(printFunction);
}
void GlobalContext::defineStandardFunctions(){
auto printLineFunction = std::make_shared<Function>(VOID, "print");
printLineFunction->standard = true;
printLineFunction->mangledName = "_F7println";
addFunction(printLineFunction);
//print string
addPrintFunction("_F5printS", STRING);
addPrintFunction("_F7printlnS", STRING);
//print integer
addPrintFunction("_F5printI", INT);
addPrintFunction("_F7printlnI", INT);
//print char
addPrintFunction("_F5printC", CHAR);
addPrintFunction("_F7printlnC", CHAR);
//print bool
addPrintFunction("_F5printB", BOOL);
addPrintFunction("_F7printlnB", BOOL);
//print float
addPrintFunction("_F5printF", FLOAT);
addPrintFunction("_F7printlnF", FLOAT);
//concat function
auto concatFunction = std::make_shared<Function>(STRING, "concat");
concatFunction->standard = true;
concatFunction->mangledName = "_F6concatSS";
concatFunction->parameters.push_back({"a", STRING});
concatFunction->parameters.push_back({"b", STRING});
addFunction(concatFunction);
//alloc function
auto allocFunction = std::make_shared<Function>(new_pointer_type(INT), "alloc");
allocFunction->standard = true;
allocFunction->mangledName = "_F5allocI";
allocFunction->parameters.push_back({"a", INT});
addFunction(allocFunction);
//free function
auto freeFunction = std::make_shared<Function>(VOID, "free");
freeFunction->standard = true;
freeFunction->mangledName = "_F4freePI";
freeFunction->parameters.push_back({"a", INT});
addFunction(freeFunction);
//time function
auto timeFunction = std::make_shared<Function>(VOID, "time");
timeFunction->standard = true;
timeFunction->mangledName = "_F4timeAI";
timeFunction->parameters.push_back({"a", new_array_type(INT)});
addFunction(timeFunction);
//duration function
auto durationFunction = std::make_shared<Function>(VOID, "duration");
durationFunction->standard = true;
durationFunction->mangledName = "_F8durationAIAI";
durationFunction->parameters.push_back({"a", new_array_type(INT)});
durationFunction->parameters.push_back({"b", new_array_type(INT)});
addFunction(durationFunction);
}
GlobalContext::FunctionMap GlobalContext::functions(){
return m_functions;
}
<|endoftext|> |
<commit_before>// IBM_PROLOG_BEGIN_TAG
// This is an automatically generated prolog.
//
// $Source: src/kernel/blockmsghdlr.C $
//
// IBM CONFIDENTIAL
//
// COPYRIGHT International Business Machines Corp. 2011
//
// p1
//
// Object Code Only (OCO) source materials
// Licensed Internal Code Source Materials
// IBM HostBoot Licensed Internal Code
//
// The source code for this program is not published or other-
// wise divested of its trade secrets, irrespective of what has
// been deposited with the U.S. Copyright Office.
//
// Origin: 30
//
// IBM_PROLOG_END
#include <kernel/blockmsghdlr.H>
#include <kernel/block.H>
#include <kernel/pagemgr.H>
#include <kernel/basesegment.H>
MessageHandler::HandleResult BlockReadMsgHdlr::handleResponse(
msg_sys_types_t i_type, void* i_key, task_t* i_task, int i_rc)
{
if (i_rc != 0)
{
// Indicate nothing specific has been done for this response. Request
// default behavior of resume/kill task based on rc.
return UNHANDLED_RC;
}
else
{
// Call the function that attaches PTE and sets the
// sPTE entry to present while updating permissions
// on the sPTE entry of the physical addr.
iv_block->attachSPTE(i_key);
return SUCCESS;
}
}
MessageHandler::HandleResult BlockWriteMsgHdlr::handleResponse(
msg_sys_types_t i_type, void* i_key, task_t* i_task, int i_rc)
{
//Default to indicate nothing specific has been done for this response.
MessageHandler::HandleResult l_result = UNHANDLED_RC;
if (i_rc != 0)
{
//Request default behavior of resume/kill task based on rc.
return l_result;
}
//Find the virtual address to page address mapping to know which page
//address to release since only the virtual address is available on the msg
PageAddrNode* l_paNode = iv_va2paList.find(i_key);
if (l_paNode)
{
l_result = SUCCESS;
//Complete page removal and remove list entry
PageManager::freePage(reinterpret_cast<void*>(l_paNode->pageAddr));
iv_va2paList.erase(l_paNode);
delete l_paNode;
}
//Not handling a reponse from kernel
if (i_task != NULL)
{
//Find the task's msg count to know how many messages were sent
//to remove pages and whether to continue deferring the task or not
TaskMsgNode* l_tmNode = iv_msgGrpList.find(i_task);
if (l_tmNode)
{
//Last message for the given task
if (l_tmNode->msgCount == 1 &&
(l_tmNode->next == NULL && l_tmNode->prev == NULL))
{
l_result = SUCCESS;
iv_msgGrpList.erase(l_tmNode);
delete l_tmNode;
}
else
{
l_result = CONTINUE_DEFER;
l_tmNode->msgCount--;
}
}
}
return l_result;
}
void BlockWriteMsgHdlr::incMsgCount(task_t* i_task)
{
TaskMsgNode* l_tmNode = iv_msgGrpList.find(i_task);
if (l_tmNode == NULL)
{
//Add task to list and set message count to 1
l_tmNode = new TaskMsgNode();
l_tmNode->key = i_task;
l_tmNode->msgCount = 0;
iv_msgGrpList.insert(l_tmNode);
}
l_tmNode->msgCount++;
}
void BlockWriteMsgHdlr::addVirtAddr(void* i_vaddr,uint64_t i_pgAddr)
{
PageAddrNode* l_paNode = new PageAddrNode();
l_paNode->key = i_vaddr;
l_paNode->pageAddr = i_pgAddr;
iv_va2paList.insert(l_paNode);
}
<commit_msg>Fix deadlock in vmm write operations.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/kernel/blockmsghdlr.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* COPYRIGHT International Business Machines Corp. 2011,2013 */
/* */
/* p1 */
/* */
/* Object Code Only (OCO) source materials */
/* Licensed Internal Code Source Materials */
/* IBM HostBoot Licensed Internal Code */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* Origin: 30 */
/* */
/* IBM_PROLOG_END_TAG */
#include <kernel/blockmsghdlr.H>
#include <kernel/block.H>
#include <kernel/pagemgr.H>
#include <kernel/basesegment.H>
MessageHandler::HandleResult BlockReadMsgHdlr::handleResponse(
msg_sys_types_t i_type, void* i_key, task_t* i_task, int i_rc)
{
if (i_rc != 0)
{
// Indicate nothing specific has been done for this response. Request
// default behavior of resume/kill task based on rc.
return UNHANDLED_RC;
}
else
{
// Call the function that attaches PTE and sets the
// sPTE entry to present while updating permissions
// on the sPTE entry of the physical addr.
iv_block->attachSPTE(i_key);
return SUCCESS;
}
}
MessageHandler::HandleResult BlockWriteMsgHdlr::handleResponse(
msg_sys_types_t i_type, void* i_key, task_t* i_task, int i_rc)
{
//Default to indicate nothing specific has been done for this response.
MessageHandler::HandleResult l_result = UNHANDLED_RC;
if (i_rc != 0)
{
//Request default behavior of resume/kill task based on rc.
return l_result;
}
//Find the virtual address to page address mapping to know which page
//address to release since only the virtual address is available on the msg
PageAddrNode* l_paNode = iv_va2paList.find(i_key);
if (l_paNode)
{
l_result = SUCCESS;
//Complete page removal and remove list entry
PageManager::freePage(reinterpret_cast<void*>(l_paNode->pageAddr));
iv_va2paList.erase(l_paNode);
delete l_paNode;
}
//Not handling a reponse from kernel
if (i_task != NULL)
{
//Find the task's msg count to know how many messages were sent
//to remove pages and whether to continue deferring the task or not
TaskMsgNode* l_tmNode = iv_msgGrpList.find(i_task);
if (l_tmNode)
{
//Last message for the given task
if (l_tmNode->msgCount == 1)
{
l_result = SUCCESS;
iv_msgGrpList.erase(l_tmNode);
delete l_tmNode;
}
else
{
l_result = CONTINUE_DEFER;
l_tmNode->msgCount--;
}
}
}
return l_result;
}
void BlockWriteMsgHdlr::incMsgCount(task_t* i_task)
{
TaskMsgNode* l_tmNode = iv_msgGrpList.find(i_task);
if (l_tmNode == NULL)
{
//Add task to list and set message count to 1
l_tmNode = new TaskMsgNode();
l_tmNode->key = i_task;
l_tmNode->msgCount = 0;
iv_msgGrpList.insert(l_tmNode);
}
l_tmNode->msgCount++;
}
void BlockWriteMsgHdlr::addVirtAddr(void* i_vaddr,uint64_t i_pgAddr)
{
PageAddrNode* l_paNode = new PageAddrNode();
l_paNode->key = i_vaddr;
l_paNode->pageAddr = i_pgAddr;
iv_va2paList.insert(l_paNode);
}
<|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.
*/
#pragma once
#include "stdafx.h"
#include "MZ3.h"
#include "MZ3Parser.h"
#include "MixiParser.h"
#include "TwitterParser.h"
/// MZ3pHTMLp[T
namespace mz3parser {
/// XgnHTML̉
bool MyDoParseMixiListHtml( ACCESS_TYPE aType, CMixiDataList& body, CHtmlArray& html )
{
// Xg̏
switch (aType) {
case ACCESS_TWITTER_FRIENDS_TIMELINE:
case ACCESS_WASSR_FRIENDS_TIMELINE:
// ȂB
break;
default:
body.clear();
break;
}
switch (aType) {
case ACCESS_LIST_DIARY: return mixi::ListNewFriendDiaryParser::parse( body, html );
case ACCESS_LIST_NEW_COMMENT: return mixi::NewCommentParser::parse( body, html );
case ACCESS_LIST_COMMENT: return mixi::ListCommentParser::parse( body, html );
case ACCESS_LIST_NEW_BBS: return mixi::NewBbsParser::parse( body, html );
case ACCESS_LIST_MYDIARY: return mixi::ListDiaryParser::parse( body, html );
// case ACCESS_LIST_FOOTSTEP: return mixi::ShowLogParser::parse( body, html );
case ACCESS_LIST_FOOTSTEP: return mixi::TrackParser::parse( body, html );
case ACCESS_LIST_MESSAGE_IN: return mixi::ListMessageParser::parse( body, html );
case ACCESS_LIST_MESSAGE_OUT: return mixi::ListMessageParser::parse( body, html );
case ACCESS_LIST_NEWS: return mixi::ListNewsCategoryParser::parse( body, html );
case ACCESS_LIST_FAVORITE_USER: return mixi::ListBookmarkParser::parse( body, html );
case ACCESS_LIST_FAVORITE_COMMUNITY: return mixi::ListBookmarkParser::parse( body, html );
case ACCESS_LIST_FRIEND: return mixi::ListFriendParser::parse( body, html );
case ACCESS_LIST_COMMUNITY: return mixi::ListCommunityParser::parse( body, html );
case ACCESS_LIST_INTRO: return mixi::ShowIntroParser::parse( body, html );
case ACCESS_LIST_BBS: return mixi::ListBbsParser::parse( body, html );
case ACCESS_LIST_NEW_BBS_COMMENT: return mixi::ListNewBbsCommentParser::parse( body, html );
case ACCESS_LIST_CALENDAR: return mixi::ShowCalendarParser::parse( body, html );
case ACCESS_MIXI_RECENT_ECHO: return mixi::RecentEchoParser::parse( body, html );
case ACCESS_TWITTER_FRIENDS_TIMELINE: return twitter::TwitterFriendsTimelineXmlParser::parse( body, html );
case ACCESS_TWITTER_FAVORITES: return twitter::TwitterFriendsTimelineXmlParser::parse( body, html ); // b
case ACCESS_TWITTER_DIRECT_MESSAGES: return twitter::TwitterDirectMessagesXmlParser::parse( body, html );
case ACCESS_WASSR_FRIENDS_TIMELINE: return twitter::WassrFriendsTimelineXmlParser::parse( body, html );
case ACCESS_RSS_READER_FEED: return mz3parser::RssFeedParser::parse( body, html );
default:
{
CString msg;
msg.Format( L"T|[gÕANZXʂł(%d:%s)", aType, theApp.m_accessTypeInfo.getShortText(aType) );
MZ3LOGGER_ERROR(msg);
MessageBox(NULL, msg, NULL, MB_OK);
}
return false;
}
}
/// ViewnHTML̉
void MyDoParseMixiHtml( ACCESS_TYPE aType, CMixiData& mixi, CHtmlArray& html )
{
switch (aType) {
case ACCESS_DIARY: mixi::ViewDiaryParser::parse( mixi, html ); break;
case ACCESS_BBS: mixi::ViewBbsParser::parse( mixi, html ); break;
case ACCESS_ENQUETE: mixi::ViewEnqueteParser::parse( mixi, html ); break;
case ACCESS_EVENT_JOIN:
case ACCESS_EVENT: mixi::ViewEventParser::parse( mixi, html ); break;
case ACCESS_EVENT_MEMBER: mixi::ListEventMemberParser::parse( mixi, html ); break;
case ACCESS_BIRTHDAY:
case ACCESS_PROFILE: mixi::ShowFriendParser::parse( mixi, html ); break;
case ACCESS_MYDIARY: mixi::ViewDiaryParser::parse( mixi, html ); break;
case ACCESS_MESSAGE: mixi::ViewMessageParser::parse( mixi, html ); break;
case ACCESS_NEWS: mixi::ViewNewsParser::parse( mixi, html ); break;
case ACCESS_HELP: mixi::HelpParser::parse( mixi, html ); break;
case ACCESS_ERRORLOG: mixi::ErrorlogParser::parse( mixi, html ); break;
case ACCESS_SCHEDULE:
case ACCESS_PLAIN: mixi::PlainTextParser::parse( mixi, html ); break;
default:
{
CString msg;
msg.Format( L"T|[gÕANZXʂł(%d:%s)", aType, theApp.m_accessTypeInfo.getShortText(aType) );
MZ3LOGGER_ERROR(msg);
MessageBox(NULL, msg, NULL, MB_OK);
}
break;
}
}
bool RssFeedParser::parse( CMixiDataList& out_, const std::vector<TCHAR>& text_, CString* pStrTitle )
{
MZ3LOGGER_DEBUG( L"RssFeedParser.parse() start." );
// XML
xml2stl::Container root;
if (!xml2stl::SimpleXmlParser::loadFromText( root, text_ )) {
MZ3LOGGER_ERROR( L"XML ͎s" );
return false;
}
// RSS o[W
enum RSS_TYPE {
RSS_TYPE_INVALID,
RSS_TYPE_1_0,
RSS_TYPE_2_0,
};
RSS_TYPE rss_type = RSS_TYPE_INVALID;
// RSS 1.0
try {
const xml2stl::Node& rdf = root.getNode( L"rdf:RDF" );
rdf.getNode(L"channel");
rdf.getNode(L"item");
// OK.
rss_type = RSS_TYPE_1_0;
} catch (xml2stl::NodeNotFoundException&) {
}
// RSS 2.0
try {
const xml2stl::Node& rss = root.getNode( L"rss", xml2stl::Property(L"version", L"2.0") );
const xml2stl::Node& channel = rss.getNode(L"channel");
channel.getNode(L"item");
// OK.
rss_type = RSS_TYPE_2_0;
} catch (xml2stl::NodeNotFoundException&) {
}
bool rval = true;
switch (rss_type) {
case RSS_TYPE_1_0:
// parseRss1(out_, root);
// rdf:RDF/channel ɑ鏈
// rdf:RDF/item ɑ鏈
try {
const xml2stl::Node& rdf = root.getNode(L"rdf:RDF");
for (xml2stl::NodeRef nodeRef=rdf.getNodeRef(); !nodeRef.isEnd(); nodeRef.next()) {
const xml2stl::Node& item = nodeRef.getCurrentNode();
if (item.getName() != L"item") {
continue;
}
CMixiData data;
// description, title ̎擾
CString title = item.getNode(L"title").getTextAll().c_str();
CString description = item.getNode(L"description").getTextAll().c_str();
// `Ċi[
RssFeedParser::setDescriptionTitle(data, description, title);
// link = rdf:about
CString s = item.getProperty(L"rdf:about").c_str();
data.m_linkList.push_back(CMixiData::Link(s, data.GetTitle().Left(20)));
// dc:date
try {
CString s = item.getNode(L"dc:date").getTextAll().c_str();
mixi::ParserUtil::ParseDate(s, data);
} catch (xml2stl::NodeNotFoundException&) {
}
data.SetAccessType(ACCESS_RSS_READER_ITEM);
out_.push_back(data);
}
// ^Cg擾
if (pStrTitle!=NULL) {
const xml2stl::Node& channel = rdf.getNode(L"channel");
CString title = channel.getNode(L"title").getTextAll().c_str();
(*pStrTitle) = title;
}
} catch (xml2stl::NodeNotFoundException& e) {
MZ3LOGGER_ERROR( util::FormatString( L"node not found... : %s", e.getMessage().c_str()) );
rval = false;
}
break;
case RSS_TYPE_2_0:
// parseRss2(out_, root);
// rdf:RDF/channel ɑ鏈
try {
const xml2stl::Node& rss = root.getNode( L"rss", xml2stl::Property(L"version", L"2.0") );
const xml2stl::Node& channel = rss.getNode(L"channel");
for (xml2stl::NodeRef nodeRef=channel.getNodeRef(); !nodeRef.isEnd(); nodeRef.next()) {
const xml2stl::Node& item = nodeRef.getCurrentNode();
if (item.getName() != L"item") {
continue;
}
CMixiData data;
// description, title ̎擾
CString description = item.getNode(L"description").getTextAll().c_str();
CString title = item.getNode(L"title").getTextAll().c_str();
// `Ċi[
RssFeedParser::setDescriptionTitle(data, description, title);
// link
CString link = item.getNode(L"link").getTextAll().c_str();
data.m_linkList.push_back(CMixiData::Link(link, data.GetTitle().Left(20)));
// pubDate
try {
CString s = item.getNode(L"pubDate").getTextAll().c_str();
mixi::ParserUtil::ParseDate(s, data);
} catch (xml2stl::NodeNotFoundException&) {
}
// dc:date
try {
CString s = item.getNode(L"dc:date").getTextAll().c_str();
mixi::ParserUtil::ParseDate(s, data);
} catch (xml2stl::NodeNotFoundException&) {
}
data.SetAccessType(ACCESS_RSS_READER_ITEM);
out_.push_back(data);
}
// ^Cg擾
if (pStrTitle!=NULL) {
CString title = channel.getNode(L"title").getTextAll().c_str();
(*pStrTitle) = title;
}
} catch (xml2stl::NodeNotFoundException& e) {
MZ3LOGGER_ERROR( util::FormatString( L"node not found... : %s", e.getMessage().c_str()) );
rval = false;
}
break;
default:
MZ3LOGGER_ERROR(L"T|[gRSSł");
rval = false;
break;
}
MZ3LOGGER_DEBUG( L"RssFeedParser.parse() finished." );
return rval;
}
void RssFeedParser::setDescriptionTitle( CMixiData& data, CString description, CString title )
{
// description ̐`
mixi::ParserUtil::ReplaceEntityReferenceToCharacter( description );
description = description.Trim();
// body Ƃ description no-tag łݒ肷
mixi::ParserUtil::StripAllTags(description);
description = description.Trim();
data.AddBody(description);
// title = title
mixi::ParserUtil::ReplaceEntityReferenceToCharacter( title );
if (!title.IsEmpty()) {
title += L"\r\n";
}
// title += description;
title = title.Trim();
data.SetTitle( title );
}
bool RssAutoDiscoveryParser::parse( CMixiDataList& out_, const std::vector<TCHAR>& text_ )
{
MZ3LOGGER_DEBUG( L"RssAutoDiscoveryParser.parse() start." );
// XML
xml2stl::Container root;
if (!xml2stl::SimpleXmlParser::loadFromText( root, text_ )) {
MZ3LOGGER_ERROR( L"XML ͎s" );
return false;
}
bool rval = true;
// html/head/link[rel=alternate,type=application/rss+xml] 擾
// XHTML Ƃ͌Ȃ̂ŁASĂ link ^OΏۂƂ
try {
// html/... HTML/... Ŏs
try {
parseLinkRecursive( out_, root.getNode(L"HTML") );
} catch (xml2stl::NodeNotFoundException&) {
parseLinkRecursive( out_, root.getNode(L"html") );
}
} catch (xml2stl::NodeNotFoundException& e) {
MZ3LOGGER_ERROR( util::FormatString( L"node not found... : %s", e.getMessage().c_str()) );
rval = false;
}
MZ3LOGGER_DEBUG( L"RssAutoDiscoveryParser.parse() finished." );
return rval;
}
bool RssAutoDiscoveryParser::parseLinkRecursive( CMixiDataList& out_, const xml2stl::Node& node )
{
for (unsigned int i=0; i<node.getChildrenCount(); i++) {
const xml2stl::Node& item = node.getNode(i);
try {
if (item.getName() == L"link" &&
item.getProperty(L"rel")==L"alternate" &&
item.getProperty(L"type")==L"application/rss+xml")
{
// lj
CMixiData data;
CString title = item.getProperty(L"title").c_str();
CString href = item.getProperty(L"href").c_str();
mixi::ParserUtil::ReplaceEntityReferenceToCharacter( title );
data.SetTitle(title);
data.SetURL(href);
data.SetAccessType(ACCESS_RSS_READER_FEED);
out_.push_back(data);
continue;
}
if (item.getChildrenCount()>0) {
parseLinkRecursive(out_, item);
}
} catch (xml2stl::NodeNotFoundException&) {
continue;
}
}
return true;
}
}//namespace mixi
<commit_msg>RSSのimgタグ抽出対応(広告がうざいのでとりあえずコメントアウト)<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.
*/
#pragma once
#include "stdafx.h"
#include "MZ3.h"
#include "MZ3Parser.h"
#include "MixiParser.h"
#include "TwitterParser.h"
/// MZ3pHTMLp[T
namespace mz3parser {
/// XgnHTML̉
bool MyDoParseMixiListHtml( ACCESS_TYPE aType, CMixiDataList& body, CHtmlArray& html )
{
// Xg̏
switch (aType) {
case ACCESS_TWITTER_FRIENDS_TIMELINE:
case ACCESS_WASSR_FRIENDS_TIMELINE:
// ȂB
break;
default:
body.clear();
break;
}
switch (aType) {
case ACCESS_LIST_DIARY: return mixi::ListNewFriendDiaryParser::parse( body, html );
case ACCESS_LIST_NEW_COMMENT: return mixi::NewCommentParser::parse( body, html );
case ACCESS_LIST_COMMENT: return mixi::ListCommentParser::parse( body, html );
case ACCESS_LIST_NEW_BBS: return mixi::NewBbsParser::parse( body, html );
case ACCESS_LIST_MYDIARY: return mixi::ListDiaryParser::parse( body, html );
// case ACCESS_LIST_FOOTSTEP: return mixi::ShowLogParser::parse( body, html );
case ACCESS_LIST_FOOTSTEP: return mixi::TrackParser::parse( body, html );
case ACCESS_LIST_MESSAGE_IN: return mixi::ListMessageParser::parse( body, html );
case ACCESS_LIST_MESSAGE_OUT: return mixi::ListMessageParser::parse( body, html );
case ACCESS_LIST_NEWS: return mixi::ListNewsCategoryParser::parse( body, html );
case ACCESS_LIST_FAVORITE_USER: return mixi::ListBookmarkParser::parse( body, html );
case ACCESS_LIST_FAVORITE_COMMUNITY: return mixi::ListBookmarkParser::parse( body, html );
case ACCESS_LIST_FRIEND: return mixi::ListFriendParser::parse( body, html );
case ACCESS_LIST_COMMUNITY: return mixi::ListCommunityParser::parse( body, html );
case ACCESS_LIST_INTRO: return mixi::ShowIntroParser::parse( body, html );
case ACCESS_LIST_BBS: return mixi::ListBbsParser::parse( body, html );
case ACCESS_LIST_NEW_BBS_COMMENT: return mixi::ListNewBbsCommentParser::parse( body, html );
case ACCESS_LIST_CALENDAR: return mixi::ShowCalendarParser::parse( body, html );
case ACCESS_MIXI_RECENT_ECHO: return mixi::RecentEchoParser::parse( body, html );
case ACCESS_TWITTER_FRIENDS_TIMELINE: return twitter::TwitterFriendsTimelineXmlParser::parse( body, html );
case ACCESS_TWITTER_FAVORITES: return twitter::TwitterFriendsTimelineXmlParser::parse( body, html ); // b
case ACCESS_TWITTER_DIRECT_MESSAGES: return twitter::TwitterDirectMessagesXmlParser::parse( body, html );
case ACCESS_WASSR_FRIENDS_TIMELINE: return twitter::WassrFriendsTimelineXmlParser::parse( body, html );
case ACCESS_RSS_READER_FEED: return mz3parser::RssFeedParser::parse( body, html );
default:
{
CString msg;
msg.Format( L"T|[gÕANZXʂł(%d:%s)", aType, theApp.m_accessTypeInfo.getShortText(aType) );
MZ3LOGGER_ERROR(msg);
MessageBox(NULL, msg, NULL, MB_OK);
}
return false;
}
}
/// ViewnHTML̉
void MyDoParseMixiHtml( ACCESS_TYPE aType, CMixiData& mixi, CHtmlArray& html )
{
switch (aType) {
case ACCESS_DIARY: mixi::ViewDiaryParser::parse( mixi, html ); break;
case ACCESS_BBS: mixi::ViewBbsParser::parse( mixi, html ); break;
case ACCESS_ENQUETE: mixi::ViewEnqueteParser::parse( mixi, html ); break;
case ACCESS_EVENT_JOIN:
case ACCESS_EVENT: mixi::ViewEventParser::parse( mixi, html ); break;
case ACCESS_EVENT_MEMBER: mixi::ListEventMemberParser::parse( mixi, html ); break;
case ACCESS_BIRTHDAY:
case ACCESS_PROFILE: mixi::ShowFriendParser::parse( mixi, html ); break;
case ACCESS_MYDIARY: mixi::ViewDiaryParser::parse( mixi, html ); break;
case ACCESS_MESSAGE: mixi::ViewMessageParser::parse( mixi, html ); break;
case ACCESS_NEWS: mixi::ViewNewsParser::parse( mixi, html ); break;
case ACCESS_HELP: mixi::HelpParser::parse( mixi, html ); break;
case ACCESS_ERRORLOG: mixi::ErrorlogParser::parse( mixi, html ); break;
case ACCESS_SCHEDULE:
case ACCESS_PLAIN: mixi::PlainTextParser::parse( mixi, html ); break;
default:
{
CString msg;
msg.Format( L"T|[gÕANZXʂł(%d:%s)", aType, theApp.m_accessTypeInfo.getShortText(aType) );
MZ3LOGGER_ERROR(msg);
MessageBox(NULL, msg, NULL, MB_OK);
}
break;
}
}
bool RssFeedParser::parse( CMixiDataList& out_, const std::vector<TCHAR>& text_, CString* pStrTitle )
{
MZ3LOGGER_DEBUG( L"RssFeedParser.parse() start." );
// XML
xml2stl::Container root;
if (!xml2stl::SimpleXmlParser::loadFromText( root, text_ )) {
MZ3LOGGER_ERROR( L"XML ͎s" );
return false;
}
// RSS o[W
enum RSS_TYPE {
RSS_TYPE_INVALID,
RSS_TYPE_1_0,
RSS_TYPE_2_0,
};
RSS_TYPE rss_type = RSS_TYPE_INVALID;
// RSS 1.0
try {
const xml2stl::Node& rdf = root.getNode( L"rdf:RDF" );
rdf.getNode(L"channel");
rdf.getNode(L"item");
// OK.
rss_type = RSS_TYPE_1_0;
} catch (xml2stl::NodeNotFoundException&) {
}
// RSS 2.0
try {
const xml2stl::Node& rss = root.getNode( L"rss", xml2stl::Property(L"version", L"2.0") );
const xml2stl::Node& channel = rss.getNode(L"channel");
channel.getNode(L"item");
// OK.
rss_type = RSS_TYPE_2_0;
} catch (xml2stl::NodeNotFoundException&) {
}
bool rval = true;
switch (rss_type) {
case RSS_TYPE_1_0:
// parseRss1(out_, root);
// rdf:RDF/channel ɑ鏈
// rdf:RDF/item ɑ鏈
try {
const xml2stl::Node& rdf = root.getNode(L"rdf:RDF");
for (xml2stl::NodeRef nodeRef=rdf.getNodeRef(); !nodeRef.isEnd(); nodeRef.next()) {
const xml2stl::Node& item = nodeRef.getCurrentNode();
if (item.getName() != L"item") {
continue;
}
CMixiData data;
// description, title ̎擾
CString title = item.getNode(L"title").getTextAll().c_str();
CString description = item.getNode(L"description").getTextAll().c_str();
// `Ċi[
RssFeedParser::setDescriptionTitle(data, description, title);
// link = rdf:about
CString s = item.getProperty(L"rdf:about").c_str();
data.m_linkList.push_back(CMixiData::Link(s, data.GetTitle().Left(20)));
// dc:date
try {
CString s = item.getNode(L"dc:date").getTextAll().c_str();
mixi::ParserUtil::ParseDate(s, data);
} catch (xml2stl::NodeNotFoundException&) {
}
data.SetAccessType(ACCESS_RSS_READER_ITEM);
out_.push_back(data);
}
// ^Cg擾
if (pStrTitle!=NULL) {
const xml2stl::Node& channel = rdf.getNode(L"channel");
CString title = channel.getNode(L"title").getTextAll().c_str();
(*pStrTitle) = title;
}
} catch (xml2stl::NodeNotFoundException& e) {
MZ3LOGGER_ERROR( util::FormatString( L"node not found... : %s", e.getMessage().c_str()) );
rval = false;
}
break;
case RSS_TYPE_2_0:
// parseRss2(out_, root);
// rdf:RDF/channel ɑ鏈
try {
const xml2stl::Node& rss = root.getNode( L"rss", xml2stl::Property(L"version", L"2.0") );
const xml2stl::Node& channel = rss.getNode(L"channel");
for (xml2stl::NodeRef nodeRef=channel.getNodeRef(); !nodeRef.isEnd(); nodeRef.next()) {
const xml2stl::Node& item = nodeRef.getCurrentNode();
if (item.getName() != L"item") {
continue;
}
CMixiData data;
// description, title ̎擾
CString description = item.getNode(L"description").getTextAll().c_str();
CString title = item.getNode(L"title").getTextAll().c_str();
// `Ċi[
RssFeedParser::setDescriptionTitle(data, description, title);
// link
CString link = item.getNode(L"link").getTextAll().c_str();
data.m_linkList.push_back(CMixiData::Link(link, data.GetTitle().Left(20)));
// pubDate
try {
CString s = item.getNode(L"pubDate").getTextAll().c_str();
mixi::ParserUtil::ParseDate(s, data);
} catch (xml2stl::NodeNotFoundException&) {
}
// dc:date
try {
CString s = item.getNode(L"dc:date").getTextAll().c_str();
mixi::ParserUtil::ParseDate(s, data);
} catch (xml2stl::NodeNotFoundException&) {
}
data.SetAccessType(ACCESS_RSS_READER_ITEM);
out_.push_back(data);
}
// ^Cg擾
if (pStrTitle!=NULL) {
CString title = channel.getNode(L"title").getTextAll().c_str();
(*pStrTitle) = title;
}
} catch (xml2stl::NodeNotFoundException& e) {
MZ3LOGGER_ERROR( util::FormatString( L"node not found... : %s", e.getMessage().c_str()) );
rval = false;
}
break;
default:
MZ3LOGGER_ERROR(L"T|[gRSSł");
rval = false;
break;
}
MZ3LOGGER_DEBUG( L"RssFeedParser.parse() finished." );
return rval;
}
void RssFeedParser::setDescriptionTitle( CMixiData& data, CString description, CString title )
{
// description ̐`
mixi::ParserUtil::ReplaceEntityReferenceToCharacter( description );
description = description.Trim();
// description img ^O͂Ao^
/* static MyRegex s_reg;
if (util::CompileRegex(s_reg, L"<img[^>]*src=\"([^\"]+)\"[^>]*>")) {
if (s_reg.exec(description) && s_reg.results.size() == 2 ) {
// <img>^O
MZ3_TRACE(L"RssFeedParser::setDescriptionTitle(), img-url[%s], description[%s]\n",
s_reg.results[1].str.c_str(),
description);
data.AddImage(s_reg.results[1].str.c_str());
}
}
*/
// body Ƃ description no-tag łݒ肷
mixi::ParserUtil::StripAllTags(description);
description = description.Trim();
data.AddBody(description);
// title = title
mixi::ParserUtil::ReplaceEntityReferenceToCharacter( title );
if (!title.IsEmpty()) {
title += L"\r\n";
}
// title += description;
title = title.Trim();
data.SetTitle( title );
}
bool RssAutoDiscoveryParser::parse( CMixiDataList& out_, const std::vector<TCHAR>& text_ )
{
MZ3LOGGER_DEBUG( L"RssAutoDiscoveryParser.parse() start." );
// XML
xml2stl::Container root;
if (!xml2stl::SimpleXmlParser::loadFromText( root, text_ )) {
MZ3LOGGER_ERROR( L"XML ͎s" );
return false;
}
bool rval = true;
// html/head/link[rel=alternate,type=application/rss+xml] 擾
// XHTML Ƃ͌Ȃ̂ŁASĂ link ^OΏۂƂ
try {
// html/... HTML/... Ŏs
try {
parseLinkRecursive( out_, root.getNode(L"HTML") );
} catch (xml2stl::NodeNotFoundException&) {
parseLinkRecursive( out_, root.getNode(L"html") );
}
} catch (xml2stl::NodeNotFoundException& e) {
MZ3LOGGER_ERROR( util::FormatString( L"node not found... : %s", e.getMessage().c_str()) );
rval = false;
}
MZ3LOGGER_DEBUG( L"RssAutoDiscoveryParser.parse() finished." );
return rval;
}
bool RssAutoDiscoveryParser::parseLinkRecursive( CMixiDataList& out_, const xml2stl::Node& node )
{
for (unsigned int i=0; i<node.getChildrenCount(); i++) {
const xml2stl::Node& item = node.getNode(i);
try {
if (item.getName() == L"link" &&
item.getProperty(L"rel")==L"alternate" &&
item.getProperty(L"type")==L"application/rss+xml")
{
// lj
CMixiData data;
CString title = item.getProperty(L"title").c_str();
CString href = item.getProperty(L"href").c_str();
mixi::ParserUtil::ReplaceEntityReferenceToCharacter( title );
data.SetTitle(title);
data.SetURL(href);
data.SetAccessType(ACCESS_RSS_READER_FEED);
out_.push_back(data);
continue;
}
if (item.getChildrenCount()>0) {
parseLinkRecursive(out_, item);
}
} catch (xml2stl::NodeNotFoundException&) {
continue;
}
}
return true;
}
}//namespace mixi
<|endoftext|> |
<commit_before>#ifndef INCLUDE_UNITTESTS_DECIMATER_HH
#define INCLUDE_UNITTESTS_DECIMATER_HH
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <OpenMesh/Tools/Decimater/DecimaterT.hh>
#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>
#include <OpenMesh/Tools/Decimater/ModNormalFlippingT.hh>
class OpenMeshDecimater : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
// Do some initial stuff with the member data here...
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
*/
TEST_F(OpenMeshDecimater, DecimateMesh) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
typedef OpenMesh::Decimater::ModNormalFlippingT< Mesh >::Handle HModNormal;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to(5000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceVerticesLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
typedef OpenMesh::Decimater::ModNormalFlippingT< Mesh >::Handle HModNormal;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(5000, 8000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceFaceLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
typedef OpenMesh::Decimater::ModNormalFlippingT< Mesh >::Handle HModNormal;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(4500, 9996);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
#endif // INCLUDE GUARD
<commit_msg>Fixed several conversion warnings<commit_after>#ifndef INCLUDE_UNITTESTS_DECIMATER_HH
#define INCLUDE_UNITTESTS_DECIMATER_HH
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <OpenMesh/Tools/Decimater/DecimaterT.hh>
#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>
#include <OpenMesh/Tools/Decimater/ModNormalFlippingT.hh>
class OpenMeshDecimater : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
// Do some initial stuff with the member data here...
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
*/
TEST_F(OpenMeshDecimater, DecimateMesh) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
typedef OpenMesh::Decimater::ModNormalFlippingT< Mesh >::Handle HModNormal;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to(5000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceVerticesLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
typedef OpenMesh::Decimater::ModNormalFlippingT< Mesh >::Handle HModNormal;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(5000, 8000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceFaceLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
typedef OpenMesh::Decimater::ModNormalFlippingT< Mesh >::Handle HModNormal;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(4500, 9996);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
#endif // INCLUDE GUARD
<|endoftext|> |
<commit_before>//===- InstCombineAtomicRMW.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the visit functions for atomic rmw instructions.
//
//===----------------------------------------------------------------------===//
#include "InstCombineInternal.h"
#include "llvm/IR/Instructions.h"
using namespace llvm;
namespace {
/// Return true if and only if the given instruction does not modify the memory
/// location referenced. Note that an idemptent atomicrmw may still have
/// ordering effects on nearby instructions, or be volatile.
/// TODO: Common w/ the version in AtomicExpandPass, and change the term used.
/// Idemptotent is confusing in this context.
bool isIdempotentRMW(AtomicRMWInst& RMWI) {
auto C = dyn_cast<ConstantInt>(RMWI.getValOperand());
if(!C)
// TODO: Handle fadd, fsub?
return false;
AtomicRMWInst::BinOp Op = RMWI.getOperation();
switch(Op) {
case AtomicRMWInst::Add:
case AtomicRMWInst::Sub:
case AtomicRMWInst::Or:
case AtomicRMWInst::Xor:
return C->isZero();
case AtomicRMWInst::And:
return C->isMinusOne();
case AtomicRMWInst::Min:
return C->isMaxValue(true);
case AtomicRMWInst::Max:
return C->isMinValue(true);
case AtomicRMWInst::UMin:
return C->isMaxValue(false);
case AtomicRMWInst::UMax:
return C->isMinValue(false);
default:
return false;
}
}
}
Instruction *InstCombiner::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
if (!isIdempotentRMW(RMWI))
return nullptr;
// Volatile RMWs perform a load and a store, we cannot replace this by just a
// load. We chose not to canonicalize out of general paranoia about user
// expectations around volatile.
if (RMWI.isVolatile())
return nullptr;
// We chose to canonicalize all idempotent operations to an single
// operation code and constant. This makes it easier for the rest of the
// optimizer to match easily. The choice of or w/zero is arbitrary.
if (RMWI.getType()->isIntegerTy() &&
RMWI.getOperation() != AtomicRMWInst::Or) {
RMWI.setOperation(AtomicRMWInst::Or);
RMWI.setOperand(1, ConstantInt::get(RMWI.getType(), 0));
return &RMWI;
}
// Check if the required ordering is compatible with an atomic load.
AtomicOrdering Ordering = RMWI.getOrdering();
assert(Ordering != AtomicOrdering::NotAtomic &&
Ordering != AtomicOrdering::Unordered &&
"AtomicRMWs don't make sense with Unordered or NotAtomic");
if (Ordering != AtomicOrdering::Acquire &&
Ordering != AtomicOrdering::Monotonic)
return nullptr;
LoadInst *Load = new LoadInst(RMWI.getType(), RMWI.getPointerOperand());
Load->setAtomic(Ordering, RMWI.getSyncScopeID());
Load->setAlignment(DL.getABITypeAlignment(RMWI.getType()));
return Load;
}
<commit_msg>[InstCombine] Add todos for possible atomicrmw transforms<commit_after>//===- InstCombineAtomicRMW.cpp -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the visit functions for atomic rmw instructions.
//
//===----------------------------------------------------------------------===//
#include "InstCombineInternal.h"
#include "llvm/IR/Instructions.h"
using namespace llvm;
namespace {
/// Return true if and only if the given instruction does not modify the memory
/// location referenced. Note that an idemptent atomicrmw may still have
/// ordering effects on nearby instructions, or be volatile.
/// TODO: Common w/ the version in AtomicExpandPass, and change the term used.
/// Idemptotent is confusing in this context.
bool isIdempotentRMW(AtomicRMWInst& RMWI) {
auto C = dyn_cast<ConstantInt>(RMWI.getValOperand());
if(!C)
// TODO: Handle fadd, fsub?
return false;
AtomicRMWInst::BinOp Op = RMWI.getOperation();
switch(Op) {
case AtomicRMWInst::Add:
case AtomicRMWInst::Sub:
case AtomicRMWInst::Or:
case AtomicRMWInst::Xor:
return C->isZero();
case AtomicRMWInst::And:
return C->isMinusOne();
case AtomicRMWInst::Min:
return C->isMaxValue(true);
case AtomicRMWInst::Max:
return C->isMinValue(true);
case AtomicRMWInst::UMin:
return C->isMaxValue(false);
case AtomicRMWInst::UMax:
return C->isMinValue(false);
default:
return false;
}
}
}
Instruction *InstCombiner::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
// TODO: Any atomicrmw op which produces a known result in memory can be
// replaced w/an atomicrmw xchg. (see getBinOpAbsorber)
// TODO: Any atomicrmw xchg with no uses can be converted to a atomic store
// if the ordering is compatible.
if (!isIdempotentRMW(RMWI))
return nullptr;
// Volatile RMWs perform a load and a store, we cannot replace this by just a
// load. We chose not to canonicalize out of general paranoia about user
// expectations around volatile.
if (RMWI.isVolatile())
return nullptr;
// We chose to canonicalize all idempotent operations to an single
// operation code and constant. This makes it easier for the rest of the
// optimizer to match easily. The choice of or w/zero is arbitrary.
if (RMWI.getType()->isIntegerTy() &&
RMWI.getOperation() != AtomicRMWInst::Or) {
RMWI.setOperation(AtomicRMWInst::Or);
RMWI.setOperand(1, ConstantInt::get(RMWI.getType(), 0));
return &RMWI;
}
// Check if the required ordering is compatible with an atomic load.
AtomicOrdering Ordering = RMWI.getOrdering();
assert(Ordering != AtomicOrdering::NotAtomic &&
Ordering != AtomicOrdering::Unordered &&
"AtomicRMWs don't make sense with Unordered or NotAtomic");
if (Ordering != AtomicOrdering::Acquire &&
Ordering != AtomicOrdering::Monotonic)
return nullptr;
LoadInst *Load = new LoadInst(RMWI.getType(), RMWI.getPointerOperand());
Load->setAtomic(Ordering, RMWI.getSyncScopeID());
Load->setAlignment(DL.getABITypeAlignment(RMWI.getType()));
return Load;
}
<|endoftext|> |
<commit_before>///
/// @file ParallelSieve.cpp
/// @brief Multi-threaded prime sieve using std::async.
///
/// Copyright (C) 2017 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <chrono>
#include <future>
#include <mutex>
#include <vector>
using namespace std;
using namespace primesieve;
namespace {
counts_t& operator+=(counts_t& v1, const counts_t& v2)
{
for (size_t i = 0; i < v1.size(); i++)
v1[i] += v2[i];
return v1;
}
} // namespace
namespace primesieve {
ParallelSieve::ParallelSieve() :
shm_(nullptr),
numThreads_(getMaxThreads())
{ }
void ParallelSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelSieve::getMaxThreads()
{
return max<int>(1, thread::hardware_concurrency());
}
int ParallelSieve::getNumThreads() const
{
return numThreads_;
}
void ParallelSieve::setNumThreads(int threads)
{
numThreads_ = inBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for
/// the start_ and stop_ numbers
///
int ParallelSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = isqrt(stop_) / 5;
threshold = max(threshold, config::MIN_THREAD_DISTANCE);
uint64_t threads = getDistance() / threshold;
threads = inBetween(1, threads, numThreads_);
return (int) threads;
}
/// Get a thread distance which ensures a good load
/// balance when using multiple threads
///
uint64_t ParallelSieve::getThreadDistance(int threads) const
{
assert(threads > 0);
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t unbalanced = getDistance() / threads;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadDistance = max(config::MIN_THREAD_DISTANCE, fastest);
uint64_t iters = getDistance() / threadDistance;
if (iters < threads * 5u)
threadDistance = max(config::MIN_THREAD_DISTANCE, unbalanced);
threadDistance += 30 - threadDistance % 30;
return threadDistance;
}
/// Align n to modulo (30 + 2) to prevent prime k-tuplet
/// (twin primes, prime triplets) gaps
///
uint64_t ParallelSieve::align(uint64_t n) const
{
uint64_t n32 = checkedAdd(n, 32);
if (n32 >= stop_)
return stop_;
return n32 - n % 30;
}
/// Sieve the primes and prime k-tuplets in [start_, stop_]
/// in parallel using multi-threading
///
void ParallelSieve::sieve()
{
reset();
if (start_ > stop_)
return;
int threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
auto t1 = chrono::system_clock::now();
uint64_t threadDistance = getThreadDistance(threads);
uint64_t iters = ((getDistance() - 1) / threadDistance) + 1;
threads = inBetween(1, threads, iters);
atomic<uint64_t> i(0);
// each thread executes 1 task
auto task = [&]()
{
PrimeSieve ps(this);
uint64_t j;
counts_t counts;
counts.fill(0);
while ((j = i++) < iters)
{
uint64_t start = start_ + j * threadDistance;
uint64_t stop = checkedAdd(start, threadDistance);
stop = align(stop);
if (start > start_)
start = align(start) + 1;
// sieve the range [start, stop]
ps.sieve(start, stop);
counts += ps.getCounts();
}
return counts;
};
vector<future<counts_t>> futures;
futures.reserve(threads);
for (int t = 0; t < threads; t++)
futures.emplace_back(async(launch::async, task));
for (auto &f : futures)
counts_ += f.get();
auto t2 = chrono::system_clock::now();
chrono::duration<double> seconds = t2 - t1;
seconds_ = seconds.count();
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Print status in percent to stdout
/// @processed: Sum of recently processed segments
/// @tryLock: Do not block if tryLock = true
///
bool ParallelSieve::updateStatus(uint64_t processed, bool tryLock)
{
unique_lock<mutex> lock(lock_, defer_lock);
if (tryLock)
lock.try_lock();
else
lock.lock();
if (lock.owns_lock())
{
PrimeSieve::updateStatus(processed);
if (shm_)
shm_->status = getStatus();
return true;
}
return false;
}
} // namespace
<commit_msg>Refactor<commit_after>///
/// @file ParallelSieve.cpp
/// @brief Multi-threaded prime sieve using std::async.
///
/// Copyright (C) 2018 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <chrono>
#include <future>
#include <mutex>
#include <vector>
using namespace std;
using namespace primesieve;
namespace {
counts_t& operator+=(counts_t& v1, const counts_t& v2)
{
for (size_t i = 0; i < v1.size(); i++)
v1[i] += v2[i];
return v1;
}
} // namespace
namespace primesieve {
ParallelSieve::ParallelSieve() :
shm_(nullptr),
numThreads_(getMaxThreads())
{ }
void ParallelSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelSieve::getMaxThreads()
{
int maxThreads = thread::hardware_concurrency();
return max(1, maxThreads);
}
int ParallelSieve::getNumThreads() const
{
return numThreads_;
}
void ParallelSieve::setNumThreads(int threads)
{
numThreads_ = inBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for
/// the start_ and stop_ numbers
///
int ParallelSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = isqrt(stop_) / 5;
threshold = max(threshold, config::MIN_THREAD_DISTANCE);
uint64_t threads = getDistance() / threshold;
threads = inBetween(1, threads, numThreads_);
return (int) threads;
}
/// Get a thread distance which ensures a good load
/// balance when using multiple threads
///
uint64_t ParallelSieve::getThreadDistance(int threads) const
{
assert(threads > 0);
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t unbalanced = getDistance() / threads;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadDistance = max(config::MIN_THREAD_DISTANCE, fastest);
uint64_t iters = getDistance() / threadDistance;
if (iters < threads * 5u)
threadDistance = max(config::MIN_THREAD_DISTANCE, unbalanced);
threadDistance += 30 - threadDistance % 30;
return threadDistance;
}
/// Align n to modulo (30 + 2) to prevent prime k-tuplet
/// (twin primes, prime triplets) gaps
///
uint64_t ParallelSieve::align(uint64_t n) const
{
uint64_t n32 = checkedAdd(n, 32);
if (n32 >= stop_)
return stop_;
return n32 - n % 30;
}
/// Sieve the primes and prime k-tuplets in [start_, stop_]
/// in parallel using multi-threading
///
void ParallelSieve::sieve()
{
reset();
if (start_ > stop_)
return;
int threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
auto t1 = chrono::system_clock::now();
uint64_t threadDistance = getThreadDistance(threads);
uint64_t iters = ((getDistance() - 1) / threadDistance) + 1;
threads = inBetween(1, threads, iters);
atomic<uint64_t> i(0);
// each thread executes 1 task
auto task = [&]()
{
PrimeSieve ps(this);
uint64_t j;
counts_t counts;
counts.fill(0);
while ((j = i++) < iters)
{
uint64_t start = start_ + j * threadDistance;
uint64_t stop = checkedAdd(start, threadDistance);
stop = align(stop);
if (start > start_)
start = align(start) + 1;
// sieve the range [start, stop]
ps.sieve(start, stop);
counts += ps.getCounts();
}
return counts;
};
vector<future<counts_t>> futures;
futures.reserve(threads);
for (int t = 0; t < threads; t++)
futures.emplace_back(async(launch::async, task));
for (auto &f : futures)
counts_ += f.get();
auto t2 = chrono::system_clock::now();
chrono::duration<double> seconds = t2 - t1;
seconds_ = seconds.count();
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Print status in percent to stdout
/// @processed: Sum of recently processed segments
/// @tryLock: Do not block if tryLock = true
///
bool ParallelSieve::updateStatus(uint64_t processed, bool tryLock)
{
unique_lock<mutex> lock(lock_, defer_lock);
if (tryLock)
lock.try_lock();
else
lock.lock();
if (lock.owns_lock())
{
PrimeSieve::updateStatus(processed);
if (shm_)
shm_->status = getStatus();
return true;
}
return false;
}
} // namespace
<|endoftext|> |
<commit_before>/*
* PatternLayout.cpp
*
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "PortabilityImpl.hh"
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/NDC.hh>
#include <log4cpp/TimeStamp.hh>
#include <log4cpp/FactoryParams.hh>
#include <memory>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#else
#include <strstream>
#endif
#include <iomanip>
#include <ctime>
#include <cmath>
#include "Localtime.hh"
#ifdef LOG4CPP_HAVE_INT64_T
#ifdef LOG4CPP_HAVE_STDINT_H
#include <stdint.h>
#endif // LOG4CPP_HAVE_STDINT_H
#ifdef LOG4CPP_MISSING_INT64_OSTREAM_OP
/* workaround suggested at:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q168440
*/
#include <stdio.h>
std::ostream& operator<<(std::ostream& os, int64_t i) {
char buf[20];
::sprintf(buf,"%I64d", i);
return os << buf;
}
#endif // LOG4CPP_MISSING_INT64_OSTREAM_OP
#endif // LOG4CPP_HAVE_INT64_T
namespace log4cpp {
struct StringLiteralComponent : public PatternLayout::PatternComponent {
StringLiteralComponent(const std::string& literal) :
_literal(literal) {
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << _literal;
}
private:
std::string _literal;
};
struct CategoryNameComponent : public PatternLayout::PatternComponent {
CategoryNameComponent(std::string specifier) {
if (specifier == "") {
_precision = -1;
} else {
#ifdef LOG4CPP_HAVE_SSTREAM
std::istringstream s(specifier);
#else
std::istrstream s(specifier.c_str());
#endif
s >> _precision;
}
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
if (_precision == -1) {
out << event.categoryName;
} else {
std::string::size_type begin = std::string::npos;
for(int i = 0; i < _precision; i++) {
begin = event.categoryName.rfind('.', begin - 2);
if (begin == std::string::npos) {
begin = 0;
break;
}
begin++;
}
out << event.categoryName.substr(begin);
}
}
private:
int _precision;
};
struct MessageComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.message;
}
};
struct NDCComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.ndc;
}
};
struct PriorityComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << Priority::getPriorityName(event.priority);
}
};
struct ThreadNameComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.threadName;
}
};
struct ProcessorTimeComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << std::clock();
}
};
struct TimeStampComponent : public PatternLayout::PatternComponent {
static const char* const FORMAT_ISO8601;
static const char* const FORMAT_ABSOLUTE;
static const char* const FORMAT_DATE;
TimeStampComponent(std::string timeFormat) {
if ((timeFormat == "") || (timeFormat == "ISO8601")) {
timeFormat = FORMAT_ISO8601;
} else if (timeFormat == "ABSOLUTE") {
timeFormat = FORMAT_ABSOLUTE;
} else if (timeFormat == "DATE") {
timeFormat = FORMAT_DATE;
}
std::string::size_type pos = timeFormat.find("%l");
if (pos == std::string::npos) {
_printMillis = false;
_timeFormat1 = timeFormat;
} else {
_printMillis = true;
_timeFormat1 = timeFormat.substr(0, pos);
_timeFormat2 = timeFormat.substr(pos + 2);
}
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
struct std::tm currentTime;
std::time_t t = event.timeStamp.getSeconds();
localtime(&t, ¤tTime);
char formatted[100];
std::string timeFormat;
if (_printMillis) {
std::ostringstream formatStream;
formatStream << _timeFormat1
<< std::setw(3) << std::setfill('0')
<< event.timeStamp.getMilliSeconds()
<< _timeFormat2;
timeFormat = formatStream.str();
} else {
timeFormat = _timeFormat1;
}
std::strftime(formatted, sizeof(formatted), timeFormat.c_str(), ¤tTime);
out << formatted;
}
private:
std::string _timeFormat1;
std::string _timeFormat2;
bool _printMillis;
};
const char* const TimeStampComponent::FORMAT_ISO8601 = "%Y-%m-%d %H:%M:%S,%l";
const char* const TimeStampComponent::FORMAT_ABSOLUTE = "%H:%M:%S,%l";
const char* const TimeStampComponent::FORMAT_DATE = "%d %b %Y %H:%M:%S,%l";
struct SecondsSinceEpochComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.timeStamp.getSeconds();
}
};
struct MillisSinceEpochComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
#ifdef LOG4CPP_HAVE_INT64_T
int64_t t = event.timeStamp.getSeconds() -
TimeStamp::getStartTime().getSeconds();
t *= 1000;
t += event.timeStamp.getMilliSeconds() -
TimeStamp::getStartTime().getMilliSeconds();
out << t;
#else
double t = event.timeStamp.getSeconds() -
TimeStamp::getStartTime().getSeconds();
t *= 1000;
t += event.timeStamp.getMilliSeconds() -
TimeStamp::getStartTime().getMilliSeconds();
out << std::setiosflags(std::ios::fixed)
<< std::setprecision(0) << t;
#endif
}
};
struct FormatModifierComponent : public PatternLayout::PatternComponent {
FormatModifierComponent(PatternLayout::PatternComponent* component,
size_t minWidth, size_t maxWidth, bool alignLeft) :
_component(component) ,
_minWidth(minWidth),
_maxWidth(maxWidth),
_alignLeft(alignLeft) {
}
virtual ~FormatModifierComponent() {
delete _component;
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
std::ostringstream s;
_component->append(s, event);
std::string msg = s.str();
if (_maxWidth > 0 && _maxWidth < msg.length()) {
msg.erase(_maxWidth);
}
size_t fillCount = _minWidth - msg.length();
if (fillCount > 0) {
if (_alignLeft) {
out << msg << std::string(fillCount, ' ');
} else {
out << std::string(fillCount, ' ') << msg;
}
} else {
out << msg;
}
}
private:
PatternLayout::PatternComponent* _component;
size_t _minWidth;
size_t _maxWidth;
bool _alignLeft;
};
const char* PatternLayout::DEFAULT_CONVERSION_PATTERN = "%m%n";
const char* PatternLayout::SIMPLE_CONVERSION_PATTERN = "%p - %m%n";
const char* PatternLayout::BASIC_CONVERSION_PATTERN = "%R %p %c %x: %m%n";
const char* PatternLayout::TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n";
PatternLayout::PatternLayout() {
try {
setConversionPattern(DEFAULT_CONVERSION_PATTERN);
} catch(ConfigureFailure&) {
}
}
PatternLayout::~PatternLayout() {
clearConversionPattern();
}
void PatternLayout::clearConversionPattern() {
for(ComponentVector::const_iterator i = _components.begin();
i != _components.end(); ++i) {
delete (*i);
}
_components.clear();
_conversionPattern = "";
}
void PatternLayout::setConversionPattern(const std::string& conversionPattern) throw(ConfigureFailure) {
#ifdef LOG4CPP_HAVE_SSTREAM
std::istringstream conversionStream(conversionPattern);
#else
std::istrstream conversionStream(conversionPattern.c_str());
#endif
std::string literal;
char ch;
PatternLayout::PatternComponent* component = NULL;
int minWidth = 0;
size_t maxWidth = 0;
clearConversionPattern();
while (conversionStream.get(ch)) {
if (ch == '%') {
// readPrefix;
{
char ch2;
conversionStream.get(ch2);
if ((ch2 == '-') || ((ch2 >= '0') && (ch2 <= '9'))) {
conversionStream.putback(ch2);
conversionStream >> minWidth;
conversionStream.get(ch2);
}
if (ch2 == '.') {
conversionStream >> maxWidth;
} else {
conversionStream.putback(ch2);
}
}
if (!conversionStream.get(ch)) {
std::ostringstream msg;
msg << "unterminated conversion specifier in '" << conversionPattern << "' at index " << conversionStream.tellg();
throw ConfigureFailure(msg.str());
}
std::string specPostfix = "";
// read postfix
{
char ch2;
if (conversionStream.get(ch2)) {
if (ch2 == '{') {
while(conversionStream.get(ch2) && (ch2 != '}'))
specPostfix += ch2;
} else {
conversionStream.putback(ch2);
}
}
}
switch (ch) {
case '%':
literal += ch;
break;
case 'm':
component = new MessageComponent();
break;
case 'n':
{
std::ostringstream endline;
endline << std::endl;
literal += endline.str();
}
break;
case 'c':
component = new CategoryNameComponent(specPostfix);
break;
case 'd':
component = new TimeStampComponent(specPostfix);
break;
case 'p':
component = new PriorityComponent();
break;
case 'r':
component = new MillisSinceEpochComponent();
break;
case 'R':
component = new SecondsSinceEpochComponent();
break;
case 't':
component = new ThreadNameComponent();
break;
case 'u':
component = new ProcessorTimeComponent();
break;
case 'x':
component = new NDCComponent();
break;
default:
std::ostringstream msg;
msg << "unknown conversion specifier '" << ch << "' in '" << conversionPattern << "' at index " << conversionStream.tellg();
throw ConfigureFailure(msg.str());
}
if (component) {
if (!literal.empty()) {
_components.push_back(new StringLiteralComponent(literal));
literal = "";
}
if ((minWidth != 0) || (maxWidth != 0)) {
component = new FormatModifierComponent(component, std::abs(minWidth), maxWidth, minWidth < 0);
minWidth = maxWidth = 0;
}
_components.push_back(component);
component = NULL;
}
} else {
literal += ch;
}
}
if (!literal.empty()) {
_components.push_back(new StringLiteralComponent(literal));
}
_conversionPattern = conversionPattern;
}
std::string PatternLayout::getConversionPattern() const {
return _conversionPattern;
}
std::string PatternLayout::format(const LoggingEvent& event) {
std::ostringstream message;
for(ComponentVector::const_iterator i = _components.begin();
i != _components.end(); ++i) {
(*i)->append(message, event);
}
return message.str();
}
std::auto_ptr<Layout> create_pattern_layout(const FactoryParams& params)
{
std::string pattern;
params.get_for("pattern layout").optional("pattern", pattern);
std::auto_ptr<Layout> result(new PatternLayout);
PatternLayout* l = static_cast<PatternLayout*>(result.get());
if (pattern.empty() || pattern == "default")
return result;
if (pattern == "simple")
{
l->setConversionPattern(PatternLayout::SIMPLE_CONVERSION_PATTERN);
return result;
}
if (pattern == "basic")
{
l->setConversionPattern(PatternLayout::BASIC_CONVERSION_PATTERN);
return result;
}
if (pattern == "ttcc")
{
l->setConversionPattern(PatternLayout::TTCC_CONVERSION_PATTERN);
return result;
}
l->setConversionPattern(pattern);
return result;
}
}
<commit_msg>Fixed %m formater<commit_after>/*
* PatternLayout.cpp
*
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "PortabilityImpl.hh"
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/NDC.hh>
#include <log4cpp/TimeStamp.hh>
#include <log4cpp/FactoryParams.hh>
#include <memory>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#else
#include <strstream>
#endif
#include <iomanip>
#include <ctime>
#include <cmath>
#include "Localtime.hh"
#ifdef LOG4CPP_HAVE_INT64_T
#ifdef LOG4CPP_HAVE_STDINT_H
#include <stdint.h>
#endif // LOG4CPP_HAVE_STDINT_H
#ifdef LOG4CPP_MISSING_INT64_OSTREAM_OP
/* workaround suggested at:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q168440
*/
#include <stdio.h>
std::ostream& operator<<(std::ostream& os, int64_t i) {
char buf[20];
::sprintf(buf,"%I64d", i);
return os << buf;
}
#endif // LOG4CPP_MISSING_INT64_OSTREAM_OP
#endif // LOG4CPP_HAVE_INT64_T
namespace log4cpp {
struct StringLiteralComponent : public PatternLayout::PatternComponent {
StringLiteralComponent(const std::string& literal) :
_literal(literal) {
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << _literal;
}
private:
std::string _literal;
};
struct CategoryNameComponent : public PatternLayout::PatternComponent {
CategoryNameComponent(std::string specifier) {
if (specifier == "") {
_precision = -1;
} else {
#ifdef LOG4CPP_HAVE_SSTREAM
std::istringstream s(specifier);
#else
std::istrstream s(specifier.c_str());
#endif
s >> _precision;
}
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
if (_precision == -1) {
out << event.categoryName;
} else {
std::string::size_type begin = std::string::npos;
for(int i = 0; i < _precision; i++) {
begin = event.categoryName.rfind('.', begin - 2);
if (begin == std::string::npos) {
begin = 0;
break;
}
begin++;
}
out << event.categoryName.substr(begin);
}
}
private:
int _precision;
};
struct MessageComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.message;
}
};
struct NDCComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.ndc;
}
};
struct PriorityComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << Priority::getPriorityName(event.priority);
}
};
struct ThreadNameComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.threadName;
}
};
struct ProcessorTimeComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << std::clock();
}
};
struct TimeStampComponent : public PatternLayout::PatternComponent {
static const char* const FORMAT_ISO8601;
static const char* const FORMAT_ABSOLUTE;
static const char* const FORMAT_DATE;
TimeStampComponent(std::string timeFormat) {
if ((timeFormat == "") || (timeFormat == "ISO8601")) {
timeFormat = FORMAT_ISO8601;
} else if (timeFormat == "ABSOLUTE") {
timeFormat = FORMAT_ABSOLUTE;
} else if (timeFormat == "DATE") {
timeFormat = FORMAT_DATE;
}
std::string::size_type pos = timeFormat.find("%l");
if (pos == std::string::npos) {
_printMillis = false;
_timeFormat1 = timeFormat;
} else {
_printMillis = true;
_timeFormat1 = timeFormat.substr(0, pos);
_timeFormat2 = timeFormat.substr(pos + 2);
}
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
struct std::tm currentTime;
std::time_t t = event.timeStamp.getSeconds();
localtime(&t, ¤tTime);
char formatted[100];
std::string timeFormat;
if (_printMillis) {
std::ostringstream formatStream;
formatStream << _timeFormat1
<< std::setw(3) << std::setfill('0')
<< event.timeStamp.getMilliSeconds()
<< _timeFormat2;
timeFormat = formatStream.str();
} else {
timeFormat = _timeFormat1;
}
std::strftime(formatted, sizeof(formatted), timeFormat.c_str(), ¤tTime);
out << formatted;
}
private:
std::string _timeFormat1;
std::string _timeFormat2;
bool _printMillis;
};
const char* const TimeStampComponent::FORMAT_ISO8601 = "%Y-%m-%d %H:%M:%S,%l";
const char* const TimeStampComponent::FORMAT_ABSOLUTE = "%H:%M:%S,%l";
const char* const TimeStampComponent::FORMAT_DATE = "%d %b %Y %H:%M:%S,%l";
struct SecondsSinceEpochComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
out << event.timeStamp.getSeconds();
}
};
struct MillisSinceEpochComponent : public PatternLayout::PatternComponent {
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
#ifdef LOG4CPP_HAVE_INT64_T
int64_t t = event.timeStamp.getSeconds() -
TimeStamp::getStartTime().getSeconds();
t *= 1000;
t += event.timeStamp.getMilliSeconds() -
TimeStamp::getStartTime().getMilliSeconds();
out << t;
#else
double t = event.timeStamp.getSeconds() -
TimeStamp::getStartTime().getSeconds();
t *= 1000;
t += event.timeStamp.getMilliSeconds() -
TimeStamp::getStartTime().getMilliSeconds();
out << std::setiosflags(std::ios::fixed)
<< std::setprecision(0) << t;
#endif
}
};
struct FormatModifierComponent : public PatternLayout::PatternComponent {
FormatModifierComponent(PatternLayout::PatternComponent* component,
size_t minWidth, size_t maxWidth, bool alignLeft) :
_component(component) ,
_minWidth(minWidth),
_maxWidth(maxWidth),
_alignLeft(alignLeft) {
}
virtual ~FormatModifierComponent() {
delete _component;
}
virtual void append(std::ostringstream& out, const LoggingEvent& event) {
std::ostringstream s;
_component->append(s, event);
std::string msg = s.str();
if (_maxWidth > 0 && _maxWidth < msg.length()) {
msg.erase(_maxWidth);
}
size_t fillCount = _minWidth - msg.length();
if (_minWidth > msg.length()) {
if (_alignLeft) {
out << msg << std::string(fillCount, ' ');
} else {
out << std::string(fillCount, ' ') << msg;
}
} else {
out << msg;
}
}
private:
PatternLayout::PatternComponent* _component;
size_t _minWidth;
size_t _maxWidth;
bool _alignLeft;
};
const char* PatternLayout::DEFAULT_CONVERSION_PATTERN = "%m%n";
const char* PatternLayout::SIMPLE_CONVERSION_PATTERN = "%p - %m%n";
const char* PatternLayout::BASIC_CONVERSION_PATTERN = "%R %p %c %x: %m%n";
const char* PatternLayout::TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n";
PatternLayout::PatternLayout() {
try {
setConversionPattern(DEFAULT_CONVERSION_PATTERN);
} catch(ConfigureFailure&) {
}
}
PatternLayout::~PatternLayout() {
clearConversionPattern();
}
void PatternLayout::clearConversionPattern() {
for(ComponentVector::const_iterator i = _components.begin();
i != _components.end(); ++i) {
delete (*i);
}
_components.clear();
_conversionPattern = "";
}
void PatternLayout::setConversionPattern(const std::string& conversionPattern) throw(ConfigureFailure) {
#ifdef LOG4CPP_HAVE_SSTREAM
std::istringstream conversionStream(conversionPattern);
#else
std::istrstream conversionStream(conversionPattern.c_str());
#endif
std::string literal;
char ch;
PatternLayout::PatternComponent* component = NULL;
int minWidth = 0;
size_t maxWidth = 0;
clearConversionPattern();
while (conversionStream.get(ch)) {
if (ch == '%') {
// readPrefix;
{
char ch2;
conversionStream.get(ch2);
if ((ch2 == '-') || ((ch2 >= '0') && (ch2 <= '9'))) {
conversionStream.putback(ch2);
conversionStream >> minWidth;
conversionStream.get(ch2);
}
if (ch2 == '.') {
conversionStream >> maxWidth;
} else {
conversionStream.putback(ch2);
}
}
if (!conversionStream.get(ch)) {
std::ostringstream msg;
msg << "unterminated conversion specifier in '" << conversionPattern << "' at index " << conversionStream.tellg();
throw ConfigureFailure(msg.str());
}
std::string specPostfix = "";
// read postfix
{
char ch2;
if (conversionStream.get(ch2)) {
if (ch2 == '{') {
while(conversionStream.get(ch2) && (ch2 != '}'))
specPostfix += ch2;
} else {
conversionStream.putback(ch2);
}
}
}
switch (ch) {
case '%':
literal += ch;
break;
case 'm':
component = new MessageComponent();
break;
case 'n':
{
std::ostringstream endline;
endline << std::endl;
literal += endline.str();
}
break;
case 'c':
component = new CategoryNameComponent(specPostfix);
break;
case 'd':
component = new TimeStampComponent(specPostfix);
break;
case 'p':
component = new PriorityComponent();
break;
case 'r':
component = new MillisSinceEpochComponent();
break;
case 'R':
component = new SecondsSinceEpochComponent();
break;
case 't':
component = new ThreadNameComponent();
break;
case 'u':
component = new ProcessorTimeComponent();
break;
case 'x':
component = new NDCComponent();
break;
default:
std::ostringstream msg;
msg << "unknown conversion specifier '" << ch << "' in '" << conversionPattern << "' at index " << conversionStream.tellg();
throw ConfigureFailure(msg.str());
}
if (component) {
if (!literal.empty()) {
_components.push_back(new StringLiteralComponent(literal));
literal = "";
}
if ((minWidth != 0) || (maxWidth != 0)) {
component = new FormatModifierComponent(component, std::abs(minWidth), maxWidth, minWidth < 0);
minWidth = maxWidth = 0;
}
_components.push_back(component);
component = NULL;
}
} else {
literal += ch;
}
}
if (!literal.empty()) {
_components.push_back(new StringLiteralComponent(literal));
}
_conversionPattern = conversionPattern;
}
std::string PatternLayout::getConversionPattern() const {
return _conversionPattern;
}
std::string PatternLayout::format(const LoggingEvent& event) {
std::ostringstream message;
for(ComponentVector::const_iterator i = _components.begin();
i != _components.end(); ++i) {
(*i)->append(message, event);
}
return message.str();
}
std::auto_ptr<Layout> create_pattern_layout(const FactoryParams& params)
{
std::string pattern;
params.get_for("pattern layout").optional("pattern", pattern);
std::auto_ptr<Layout> result(new PatternLayout);
PatternLayout* l = static_cast<PatternLayout*>(result.get());
if (pattern.empty() || pattern == "default")
return result;
if (pattern == "simple")
{
l->setConversionPattern(PatternLayout::SIMPLE_CONVERSION_PATTERN);
return result;
}
if (pattern == "basic")
{
l->setConversionPattern(PatternLayout::BASIC_CONVERSION_PATTERN);
return result;
}
if (pattern == "ttcc")
{
l->setConversionPattern(PatternLayout::TTCC_CONVERSION_PATTERN);
return result;
}
l->setConversionPattern(pattern);
return result;
}
}
<|endoftext|> |
<commit_before>#ifndef SIMPLEOBJECTCONTROLLER_HPP_INCLUDED
#define SIMPLEOBJECTCONTROLLER_HPP_INCLUDED
template<typename T>
class SimpleObjectController: public tuio::CanDirectObjects <Graphic>
{
T Min, Max;
std::string Addr;
unsigned int f_id;
tuio::DirectObject * dobj;
T & value;
float angle;
bool todelete;
bool present;
float & fontResolution;
static ofTrueTypeFont & getFont()
{
static bool loaded = false;
static ofTrueTypeFont font;
if(!loaded)
{
std::string fontF = GlobalConfig::getRef<std::string>("SIMPLEOBJECTCONTROLLER:FONT:FILE","arial.ttf");
int & size = GlobalConfig::getRef("SIMPLEOBJECTCONTROLLER:FONT:RESOLUTION",20);
font.loadFont(fontF,size);
loaded = true;
}
return font;
}
void Create(tuio::DirectObject * d)
{
SimpleObjectController * i = new SimpleObjectController(value,f_id,Min,Max);
i->dobj = d;
i->angle = d->angle;
}
public:
SimpleObjectController(T & v,unsigned int F_id,T min,T max):
Min(min),
Max(max),
f_id(F_id),
dobj(NULL),
todelete(false),
angle(0),
value(v),
present(true),
fontResolution(GlobalConfig::getRef("SIMPLEOBJECTCONTROLLER:FONT:SIZE",0.001f))
{
this->Register(NULL);
}
void update()
{
if(todelete)
delete this;
}
void draw()
{
if(dobj && present)
{
float x = dobj->getX();
float y = dobj->getY();
float mangle = dobj->getAngle(DirectPoint(0.5,0.5)) + HALF_PI;
ofSetColor(255,255,255);
ofPushMatrix();
ofTranslate(x,y,0);
ofRotateZ(mangle*180.0f/M_PI);
ofScale(fontResolution,fontResolution,1);
getFont().drawString(ofToString(value),-60,-80);
ofPopMatrix();
}
}
void newObject(tuio::DirectObject * object)
{
if((!dobj) && object->f_id == f_id)
{
Create(object);
}
}
void removeObject(tuio::DirectObject * object)
{
if(object == dobj)
{
present = false;
todelete = true;
}
}
void updateObject(tuio::DirectObject * object)
{
if(object == dobj)
{
float diff = dobj->angle - angle;
while (diff > HALF_PI) diff -= M_PI;
while (diff < -HALF_PI) diff += M_PI;
angle = dobj->angle;
float ang = float(value-Min) / float(Max-Min) * TWO_PI;
ang += diff;
T nvalue = (ang / TWO_PI * (Max-Min)) + Min;
value = min(max(nvalue,Min),Max);
}
}
};
template<>
void SimpleObjectController<int>::updateObject(tuio::DirectObject * object)
{
static float accumulated_diff = 0.0f;
static float step = fabs(TWO_PI / (Max-Min));
if(object == dobj)
{
float diff = dobj->angle - angle;
while (diff > HALF_PI) diff -= M_PI;
while (diff < -HALF_PI) diff += M_PI;
accumulated_diff += diff;
int steps = accumulated_diff/ step;
angle = dobj->angle;
float ang = float(value-Min) / float(Max-Min) * TWO_PI;
int nvalue = ((ang / TWO_PI) * (Max-Min)) + Min;
ang += diff;
if(value==nvalue)
{
accumulated_diff = diff;
}
else
{
accumulated_diff = 0;
}
value = min(max(nvalue,Min),Max);
}
}
#endif // SIMPLEOBJECTCONTROLLER_HPP_INCLUDED
<commit_msg>Minor changes<commit_after>#ifndef SIMPLEOBJECTCONTROLLER_HPP_INCLUDED
#define SIMPLEOBJECTCONTROLLER_HPP_INCLUDED
template<typename T>
class SimpleObjectController: public tuio::CanDirectObjects <Graphic>
{
T Min, Max;
std::string Addr;
unsigned int f_id;
tuio::DirectObject * dobj;
T & value;
float angle;
bool todelete;
bool present;
float & fontResolution;
static ofTrueTypeFont & getFont()
{
static bool loaded = false;
static ofTrueTypeFont font;
if(!loaded)
{
std::string fontF = GlobalConfig::getRef<std::string>("SIMPLEOBJECTCONTROLLER:FONT:FILE","arial.ttf");
int & size = GlobalConfig::getRef("SIMPLEOBJECTCONTROLLER:FONT:RESOLUTION",20);
font.loadFont(fontF,size);
loaded = true;
}
return font;
}
void Create(tuio::DirectObject * d)
{
SimpleObjectController * i = new SimpleObjectController(value,f_id,Min,Max,d);
i->angle = d->angle;
}
public:
SimpleObjectController(T & v,unsigned int F_id,T min,T max,tuio::DirectObject * d=NULL):
Min(min),
Max(max),
f_id(F_id),
dobj(d),
todelete(false),
angle(0),
value(v),
present(true),
fontResolution(GlobalConfig::getRef("SIMPLEOBJECTCONTROLLER:FONT:SIZE",0.001f))
{
this->Register(NULL);
}
void update()
{
if(todelete)
delete this;
}
void draw()
{
if(dobj && present)
{
float x = dobj->getX();
float y = dobj->getY();
float mangle = dobj->getAngle(DirectPoint(0.5,0.5)) + HALF_PI;
ofSetColor(255,255,255);
ofPushMatrix();
ofTranslate(x,y,0);
ofRotateZ(mangle*180.0f/M_PI);
ofScale(fontResolution,fontResolution,1);
getFont().drawString(ofToString(value),-60,-80);
ofPopMatrix();
}
}
void newObject(tuio::DirectObject * object)
{
if((!dobj) && object->f_id == f_id)
{
Create(object);
}
}
void removeObject(tuio::DirectObject * object)
{
if(object == dobj)
{
present = false;
todelete = true;
}
}
void updateObject(tuio::DirectObject * object)
{
if(object == dobj)
{
float diff = dobj->angle - angle;
while (diff > HALF_PI) diff -= M_PI;
while (diff < -HALF_PI) diff += M_PI;
angle = dobj->angle;
float ang = float(value-Min) / float(Max-Min) * TWO_PI;
ang += diff;
T nvalue = (ang / TWO_PI * (Max-Min)) + Min;
value = min(max(nvalue,Min),Max);
}
}
};
template<>
void SimpleObjectController<int>::updateObject(tuio::DirectObject * object)
{
static float accumulated_diff = 0.0f;
static float step = fabs(TWO_PI / (Max-Min));
if(object == dobj)
{
float diff = dobj->angle - angle;
while (diff > HALF_PI) diff -= M_PI;
while (diff < -HALF_PI) diff += M_PI;
accumulated_diff += diff;
int steps = accumulated_diff/ step;
angle = dobj->angle;
float ang = float(value-Min) / float(Max-Min) * TWO_PI;
int nvalue = ((ang / TWO_PI) * (Max-Min)) + Min;
ang += diff;
if(value==nvalue)
{
accumulated_diff = diff;
}
else
{
accumulated_diff = 0;
}
value = min(max(nvalue,Min),Max);
}
}
#endif // SIMPLEOBJECTCONTROLLER_HPP_INCLUDED
<|endoftext|> |
<commit_before>#ifndef SHELL_HPP
#define SHELL_HPP
#include <string>
#include <iostream>
#include <vector>
class Shell
{
public:
/**
* Defines a command
*/
struct command
{
std::string command;
std::string name;
int argc;
std::vector<std::string> argv;
std::vector<const char *> argv_c;
bool background;
};
};
/**
* Construct the shell object
*/
Shell();
/**
* Continously display a input prompt for a user to execute commands
*
* @return The exit status of the shell object
*/
virtual int start();
/**
* Generate the command prompt text
*
* @return The command prompt text
*/
virtual std::string prompt();
/**
* Parse a input string into a command struct
*
* @param The command to parse
* @return The command
*/
virtual command parse_command(std::string);
/**
* Executes a command by passing a string
*
* @param The command string to execute
* @return The exit status of the command
*/
int execute(std::string);
/**
* Executes a command by passing a command struct
*
* @param The command to execute
* @return The exit status of the command
*/
int execute(command);
};
#endif
<commit_msg>Fix extra bracket<commit_after>#ifndef SHELL_HPP
#define SHELL_HPP
#include <string>
#include <iostream>
#include <vector>
class Shell
{
public:
/**
* Defines a command
*/
struct command
{
std::string command;
std::string name;
int argc;
std::vector<std::string> argv;
std::vector<const char *> argv_c;
bool background;
};
/**
* Construct the shell object
*/
Shell();
/**
* Continously display a input prompt for a user to execute commands
*
* @return The exit status of the shell object
*/
virtual int start();
/**
* Generate the command prompt text
*
* @return The command prompt text
*/
virtual std::string prompt();
/**
* Parse a input string into a command struct
*
* @param The command to parse
* @return The command
*/
virtual command parse_command(std::string);
/**
* Executes a command by passing a string
*
* @param The command string to execute
* @return The exit status of the command
*/
int execute(std::string);
/**
* Executes a command by passing a command struct
*
* @param The command to execute
* @return The exit status of the command
*/
int execute(command);
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#include <string>
#include "tpunit++.hpp"
#include "fakeit.hpp"
using namespace fakeit;
struct ArgumentMatchingTests: tpunit::TestFixture {
ArgumentMatchingTests()
: tpunit::TestFixture(
//
TEST(ArgumentMatchingTests::test_eq_matcher),
TEST(ArgumentMatchingTests::test_ge_matcher),
TEST(ArgumentMatchingTests::test_lt_matcher),
TEST(ArgumentMatchingTests::test_le_matcher),
TEST(ArgumentMatchingTests::test_ne_matcher),
TEST(ArgumentMatchingTests::test_gt_matcher),
TEST(ArgumentMatchingTests::test_any_matcher),
TEST(ArgumentMatchingTests::test_any_matcher2))//
{
}
struct SomeInterface {
virtual int func(int) = 0;
virtual int func2(int, std::string) = 0;
};
void test_eq_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Eq(1))).Return(1);
When(Method(mock, func).Using(Eq(2))).Return(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(1));
ASSERT_EQUAL(2, i.func(2));
Verify(Method(mock, func).Using(Eq(1))).Once();
Verify(Method(mock, func).Using(Eq(2))).Once();
}
void test_gt_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Gt(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Gt(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(2, i.func(3));
Verify(Method(mock, func).Using(Gt(2))).Once();
Verify(Method(mock, func).Using(Gt(3))).Never();
}
void test_ge_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func)).AlwaysReturn(-1);
When(Method(mock, func).Using(Ge(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Ge(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(-1, i.func(0));
ASSERT_EQUAL(1, i.func(1));
ASSERT_EQUAL(2, i.func(2));
Verify(Method(mock, func).Using(Ge(1))).Twice();
Verify(Method(mock, func).Using(Ge(2))).Once();
}
void test_lt_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Lt(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Lt(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(2, i.func(1));
ASSERT_EQUAL(2, i.func(0));
Verify(Method(mock, func).Using(Lt(2))).Twice();
Verify(Method(mock, func).Using(Lt(1))).Once();
}
void test_le_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func)).AlwaysReturn(-1);
When(Method(mock, func).Using(Le(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Le(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(2, i.func(2));
ASSERT_EQUAL(2, i.func(1));
ASSERT_EQUAL(-1, i.func(3));
Verify(Method(mock, func).Using(Le(2))).Twice();
Verify(Method(mock, func).Using(Le(1))).Once();
}
void test_ne_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func)).AlwaysReturn(-1);
When(Method(mock, func).Using(Ne(1))).AlwaysReturn(1);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(-1, i.func(1));
Verify(Method(mock, func).Using(Ne(1))).Once();
Verify(Method(mock, func).Using(Ne(10))).Twice();
}
void test_any_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Any)).AlwaysReturn(1);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(1, i.func(1));
Verify(Method(mock, func).Using(Any)).Twice();
}
void test_any_matcher2() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(_)).AlwaysReturn(1);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(1, i.func(1));
Verify(Method(mock, func).Using(_)).Twice();
}
} __ArgumentMatching;
<commit_msg>add tests<commit_after>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#include <string>
#include "tpunit++.hpp"
#include "fakeit.hpp"
using namespace fakeit;
struct ArgumentMatchingTests: tpunit::TestFixture {
ArgumentMatchingTests()
: tpunit::TestFixture(
//
TEST(ArgumentMatchingTests::test_eq_matcher), TEST(ArgumentMatchingTests::test_ge_matcher),
TEST(ArgumentMatchingTests::test_lt_matcher), TEST(ArgumentMatchingTests::test_le_matcher),
TEST(ArgumentMatchingTests::test_ne_matcher), TEST(ArgumentMatchingTests::test_gt_matcher),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::test_any_matcher2),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::format_Any),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::format_Eq),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::format_Gt),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::format_Ge),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::format_Lt),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::format_Le),
TEST(ArgumentMatchingTests::test_any_matcher), TEST(ArgumentMatchingTests::format_Ne)
) //
{
}
struct SomeInterface {
virtual int func(int) = 0;
virtual int func2(int, std::string) = 0;
};
void mixed_matchers() {
Mock<SomeInterface> mock;
When(Method(mock, func2).Using(_, _)).Return(0);
When(Method(mock, func2).Using(1, _)).Return(1);
When(Method(mock, func2).Using(2, _)).Return(2);
When(Method(mock, func2).Using(_, "3")).Return(3);
SomeInterface &i = mock.get();
ASSERT_EQUAL(0, i.func2(10, "2"));
ASSERT_EQUAL(1, i.func2(1, "2"));
ASSERT_EQUAL(2, i.func2(2, "2"));
ASSERT_EQUAL(3, i.func2(1, "3"));
}
void test_eq_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Eq(1))).Return(1);
When(Method(mock, func).Using(Eq(2))).Return(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(1));
ASSERT_EQUAL(2, i.func(2));
Verify(Method(mock, func).Using(Eq(1))).Once();
Verify(Method(mock, func).Using(Eq(2))).Once();
}
void test_gt_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Gt(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Gt(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(2, i.func(3));
Verify(Method(mock, func).Using(Gt(2))).Once();
Verify(Method(mock, func).Using(Gt(3))).Never();
}
void test_ge_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func)).AlwaysReturn(-1);
When(Method(mock, func).Using(Ge(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Ge(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(-1, i.func(0));
ASSERT_EQUAL(1, i.func(1));
ASSERT_EQUAL(2, i.func(2));
Verify(Method(mock, func).Using(Ge(1))).Twice();
Verify(Method(mock, func).Using(Ge(2))).Once();
}
void test_lt_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Lt(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Lt(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(2, i.func(1));
ASSERT_EQUAL(2, i.func(0));
Verify(Method(mock, func).Using(Lt(2))).Twice();
Verify(Method(mock, func).Using(Lt(1))).Once();
}
void test_le_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func)).AlwaysReturn(-1);
When(Method(mock, func).Using(Le(1))).AlwaysReturn(1);
When(Method(mock, func).Using(Le(2))).AlwaysReturn(2);
SomeInterface &i = mock.get();
ASSERT_EQUAL(2, i.func(2));
ASSERT_EQUAL(2, i.func(1));
ASSERT_EQUAL(-1, i.func(3));
Verify(Method(mock, func).Using(Le(2))).Twice();
Verify(Method(mock, func).Using(Le(1))).Once();
}
void test_ne_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func)).AlwaysReturn(-1);
When(Method(mock, func).Using(Ne(1))).AlwaysReturn(1);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(-1, i.func(1));
Verify(Method(mock, func).Using(Ne(1))).Once();
Verify(Method(mock, func).Using(Ne(10))).Twice();
}
void test_any_matcher() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(Any)).AlwaysReturn(1);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(1, i.func(1));
Verify(Method(mock, func).Using(Any)).Twice();
}
void test_any_matcher2() {
Mock<SomeInterface> mock;
When(Method(mock, func).Using(_)).AlwaysReturn(1);
SomeInterface &i = mock.get();
ASSERT_EQUAL(1, i.func(2));
ASSERT_EQUAL(1, i.func(1));
Verify(Method(mock, func).Using(_)).Twice();
}
void format_Any() {
Mock<SomeInterface> mock;
try {
fakeit::Verify(Method(mock, func).Using(_)).setFileInfo("test file", 1, "test method").Exactly(Once);
} catch (SequenceVerificationException& e) {
std::string expectedMsg;
expectedMsg += "test file:1: Verification error\n";
expectedMsg += "Expected pattern: mock.func( Any )\n";
expectedMsg += "Expected matches: exactly 1\n";
expectedMsg += "Actual matches : 0\n";
expectedMsg += "Actual sequence : total of 0 actual invocations.";
std::string actualMsg { to_string(e) };
ASSERT_EQUAL(expectedMsg, actualMsg);
}
}
void format_Eq() {
Mock<SomeInterface> mock;
try {
fakeit::Verify(Method(mock, func).Using(Eq(1))).setFileInfo("test file", 1, "test method").Exactly(Once);
} catch (SequenceVerificationException& e) {
std::string expectedMsg;
expectedMsg += "test file:1: Verification error\n";
expectedMsg += "Expected pattern: mock.func( 1 )\n";
expectedMsg += "Expected matches: exactly 1\n";
expectedMsg += "Actual matches : 0\n";
expectedMsg += "Actual sequence : total of 0 actual invocations.";
std::string actualMsg { to_string(e) };
ASSERT_EQUAL(expectedMsg, actualMsg);
}
}
void format_Gt() {
Mock<SomeInterface> mock;
try {
fakeit::Verify(Method(mock, func).Using(Gt(1))).setFileInfo("test file", 1, "test method").Exactly(Once);
} catch (SequenceVerificationException& e) {
std::string expectedMsg;
expectedMsg += "test file:1: Verification error\n";
expectedMsg += "Expected pattern: mock.func( >1 )\n";
expectedMsg += "Expected matches: exactly 1\n";
expectedMsg += "Actual matches : 0\n";
expectedMsg += "Actual sequence : total of 0 actual invocations.";
std::string actualMsg { to_string(e) };
ASSERT_EQUAL(expectedMsg, actualMsg);
}
}
void format_Ge() {
Mock<SomeInterface> mock;
try {
fakeit::Verify(Method(mock, func).Using(Ge(1))).setFileInfo("test file", 1, "test method").Exactly(Once);
} catch (SequenceVerificationException& e) {
std::string expectedMsg;
expectedMsg += "test file:1: Verification error\n";
expectedMsg += "Expected pattern: mock.func( >=1 )\n";
expectedMsg += "Expected matches: exactly 1\n";
expectedMsg += "Actual matches : 0\n";
expectedMsg += "Actual sequence : total of 0 actual invocations.";
std::string actualMsg { to_string(e) };
ASSERT_EQUAL(expectedMsg, actualMsg);
}
}
void format_Lt() {
Mock<SomeInterface> mock;
try {
fakeit::Verify(Method(mock, func).Using(Lt(1))).setFileInfo("test file", 1, "test method").Exactly(Once);
} catch (SequenceVerificationException& e) {
std::string expectedMsg;
expectedMsg += "test file:1: Verification error\n";
expectedMsg += "Expected pattern: mock.func( <1 )\n";
expectedMsg += "Expected matches: exactly 1\n";
expectedMsg += "Actual matches : 0\n";
expectedMsg += "Actual sequence : total of 0 actual invocations.";
std::string actualMsg { to_string(e) };
ASSERT_EQUAL(expectedMsg, actualMsg);
}
}
void format_Le() {
Mock<SomeInterface> mock;
try {
fakeit::Verify(Method(mock, func).Using(Le(1))).setFileInfo("test file", 1, "test method").Exactly(Once);
} catch (SequenceVerificationException& e) {
std::string expectedMsg;
expectedMsg += "test file:1: Verification error\n";
expectedMsg += "Expected pattern: mock.func( <=1 )\n";
expectedMsg += "Expected matches: exactly 1\n";
expectedMsg += "Actual matches : 0\n";
expectedMsg += "Actual sequence : total of 0 actual invocations.";
std::string actualMsg { to_string(e) };
ASSERT_EQUAL(expectedMsg, actualMsg);
}
}
void format_Ne() {
Mock<SomeInterface> mock;
try {
fakeit::Verify(Method(mock, func).Using(Ne(1))).setFileInfo("test file", 1, "test method").Exactly(Once);
} catch (SequenceVerificationException& e) {
std::string expectedMsg;
expectedMsg += "test file:1: Verification error\n";
expectedMsg += "Expected pattern: mock.func( !=1 )\n";
expectedMsg += "Expected matches: exactly 1\n";
expectedMsg += "Actual matches : 0\n";
expectedMsg += "Actual sequence : total of 0 actual invocations.";
std::string actualMsg { to_string(e) };
ASSERT_EQUAL(expectedMsg, actualMsg);
}
}
} __ArgumentMatching;
<|endoftext|> |
<commit_before><commit_msg>Fix missing return value in tracing test.<commit_after><|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 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 "DeclarativeItemBase.h"
#include "FormElement.h"
#include "shapes/Shape.h"
#include "shapes/ShapeStyle.h"
#include "GridLayoutFormElement.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS(DeclarativeItemBase, "item")
DeclarativeItemBase::DeclarativeItemBase(Item* parent, const StyleType* style) : Super(parent, style)
{}
DeclarativeItemBase::~DeclarativeItemBase()
{}
int DeclarativeItemBase::determineForm()
{
return 0;
}
void DeclarativeItemBase::determineChildren()
{
auto newFormIndex = determineForm();
Q_ASSERT(newFormIndex >=0 && newFormIndex < forms().size());
if (newFormIndex != currentFormIndex_)
{
if (currentFormIndex_ >= 0) currentForm()->destroyChildItems(this); // Do not destroy child items on the first run
currentFormIndex_ = newFormIndex;
}
currentForm()->synchronizeWithItem(this);
}
void DeclarativeItemBase::updateGeometry(int availableWidth, int availableHeight)
{
FormElement* form = this->currentForm();
if (hasShape())
{
getShape()->setOffset(0, 0);
if (currentShapeElements().isEmpty())
{
if ( sizeDependsOnParent() && (availableWidth > 0 || availableHeight > 0) )
{
QSize inner = getShape()->innerSize(availableWidth, availableHeight);
form->computeSize(this, inner.width(), inner.height());
if (form->width(this) > inner.width()) inner.setWidth(form->width(this));
if (form->height(this) > inner.height()) inner.setHeight(form->height(this));
getShape()->setInnerSize(inner.width(), inner.height());
}
else
{
form->computeSize(this, 0, 0);
getShape()->setInnerSize(form->width(this), form->height(this));
}
form->setPos(this, QPoint(getShape()->contentLeft(), getShape()->contentTop()));
}
else
{
auto currentShape = currentShapeElements().first();
if (sizeDependsOnParent() && (availableWidth > 0 || availableHeight > 0))
form->computeSize(this, availableWidth, availableHeight);
else form->computeSize(this, 0, 0);
getShape()->setOffset(currentShape->x(this), currentShape->y(this));
getShape()->setOutterSize(currentShape->width(this), currentShape->height(this));
form->setPos(this, QPoint(0, 0));
setSize(form->size(this));
}
form->setItemPositions(this);
}
else
{
if (sizeDependsOnParent() && (availableWidth > 0 || availableHeight > 0))
form->computeSize(this, availableWidth, availableHeight);
else form->computeSize(this, 0, 0);
form->setItemPositions(this);
setSize(form->size(this));
}
}
bool DeclarativeItemBase::sizeDependsOnParent() const
{
return currentForm()->sizeDependsOnParent(this);
}
bool DeclarativeItemBase::isEmpty() const
{
return currentForm()->isEmpty(this);
}
QList<ItemRegion> DeclarativeItemBase::regions()
{
return currentForm()->regions(this);
}
GridLayoutFormElement* DeclarativeItemBase::grid(QList<QList<Merge>> elements)
{
auto grid = new GridLayoutFormElement();
for(int y = 0; y < elements.size(); ++y)
{
auto& row = elements.at(y);
for(int x = 0; x < row.size(); ++x)
{
auto m = row.at(x);
if (m.element) grid->put(x, y, m.element);
Q_ASSERT(m.xSpan > 0);
Q_ASSERT(m.ySpan > 0);
if (m.xSpan > 1 || m.ySpan > 1) grid->setCellSpanning(m.xSpan, m.ySpan);
}
}
return grid;
}
}
<commit_msg>Fix an issue with changing forms in declarative items.<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 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 "DeclarativeItemBase.h"
#include "FormElement.h"
#include "shapes/Shape.h"
#include "shapes/ShapeStyle.h"
#include "GridLayoutFormElement.h"
#include "../cursor/Cursor.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS(DeclarativeItemBase, "item")
DeclarativeItemBase::DeclarativeItemBase(Item* parent, const StyleType* style) : Super(parent, style)
{}
DeclarativeItemBase::~DeclarativeItemBase()
{}
int DeclarativeItemBase::determineForm()
{
return 0;
}
void DeclarativeItemBase::determineChildren()
{
auto newFormIndex = determineForm();
Q_ASSERT(newFormIndex >=0 && newFormIndex < forms().size());
if (newFormIndex != currentFormIndex_)
{
if (currentFormIndex_ >= 0)
{
// Do not destroy child items on the first run
auto mc = scene()->mainCursor();
if (mc && isAncestorOf(mc->owner())) scene()->setMainCursor(nullptr);
currentForm()->destroyChildItems(this);
}
currentFormIndex_ = newFormIndex;
}
currentForm()->synchronizeWithItem(this);
}
void DeclarativeItemBase::updateGeometry(int availableWidth, int availableHeight)
{
FormElement* form = this->currentForm();
if (hasShape())
{
getShape()->setOffset(0, 0);
if (currentShapeElements().isEmpty())
{
if ( sizeDependsOnParent() && (availableWidth > 0 || availableHeight > 0) )
{
QSize inner = getShape()->innerSize(availableWidth, availableHeight);
form->computeSize(this, inner.width(), inner.height());
if (form->width(this) > inner.width()) inner.setWidth(form->width(this));
if (form->height(this) > inner.height()) inner.setHeight(form->height(this));
getShape()->setInnerSize(inner.width(), inner.height());
}
else
{
form->computeSize(this, 0, 0);
getShape()->setInnerSize(form->width(this), form->height(this));
}
form->setPos(this, QPoint(getShape()->contentLeft(), getShape()->contentTop()));
}
else
{
auto currentShape = currentShapeElements().first();
if (sizeDependsOnParent() && (availableWidth > 0 || availableHeight > 0))
form->computeSize(this, availableWidth, availableHeight);
else form->computeSize(this, 0, 0);
getShape()->setOffset(currentShape->x(this), currentShape->y(this));
getShape()->setOutterSize(currentShape->width(this), currentShape->height(this));
form->setPos(this, QPoint(0, 0));
setSize(form->size(this));
}
form->setItemPositions(this);
}
else
{
if (sizeDependsOnParent() && (availableWidth > 0 || availableHeight > 0))
form->computeSize(this, availableWidth, availableHeight);
else form->computeSize(this, 0, 0);
form->setItemPositions(this);
setSize(form->size(this));
}
}
bool DeclarativeItemBase::sizeDependsOnParent() const
{
return currentForm()->sizeDependsOnParent(this);
}
bool DeclarativeItemBase::isEmpty() const
{
return currentForm()->isEmpty(this);
}
QList<ItemRegion> DeclarativeItemBase::regions()
{
return currentForm()->regions(this);
}
GridLayoutFormElement* DeclarativeItemBase::grid(QList<QList<Merge>> elements)
{
auto grid = new GridLayoutFormElement();
for(int y = 0; y < elements.size(); ++y)
{
auto& row = elements.at(y);
for(int x = 0; x < row.size(); ++x)
{
auto m = row.at(x);
if (m.element) grid->put(x, y, m.element);
Q_ASSERT(m.xSpan > 0);
Q_ASSERT(m.ySpan > 0);
if (m.xSpan > 1 || m.ySpan > 1) grid->setCellSpanning(m.xSpan, m.ySpan);
}
}
return grid;
}
}
<|endoftext|> |
<commit_before>/**
* @file
* exercise_02_41_part_3.cpp
* @author
* Henrik Samuelsson, henrik.samuelsson(at)gmail.com
* @brief
* Part three of exercise 2.41 from the book C++ Primer (5th edition).
* @details
* A program that reads several transactions for the same ISBN. Will then
* write the sum of all transactions that were read.
*/
#include <iostream>
struct Sales_data {
std::string isbn;
unsigned units_sold = 0;
double revenue = 0.0;
};
int main() {
Sales_data sd_total, sd_temp;
// First read is a special case because we do not know the ISBN yet.
std::cin >> sd_total.isbn >> sd_total.units_sold >> sd_total.revenue;
// Read more transactions and update the total.
while(std::cin >> sd_temp.isbn >> sd_temp.units_sold >> sd_temp.revenue) {
if(sd_total.isbn == sd_temp.isbn) {
sd_total.units_sold += sd_temp.units_sold;
sd_total.revenue += sd_temp.revenue;
} else {
std::cout << "ERROR: ISBN number does not match.";
return 1;
}
}
// Present the result.
std::cout << "ISBN: " << sd_total.isbn << std::endl;
std::cout << "Total sold: " << sd_total.units_sold << std::endl;
std::cout << "Total revenue: " << sd_total.revenue << std::endl;
return 0;
}
<commit_msg>Added missing include directive.<commit_after>/**
* @file
* exercise_02_41_part_3.cpp
* @author
* Henrik Samuelsson, henrik.samuelsson(at)gmail.com
* @brief
* Part three of exercise 2.41 from the book C++ Primer (5th edition).
* @details
* A program that reads several transactions for the same ISBN. Will then
* write the sum of all transactions that were read.
*/
#include <iostream>
#include <string>
struct Sales_data {
std::string isbn;
unsigned units_sold = 0;
double revenue = 0.0;
};
int main() {
Sales_data sd_total, sd_temp;
// First read is a special case because we do not know the ISBN yet.
std::cin >> sd_total.isbn >> sd_total.units_sold >> sd_total.revenue;
// Read more transactions and update the total.
while(std::cin >> sd_temp.isbn >> sd_temp.units_sold >> sd_temp.revenue) {
if(sd_total.isbn == sd_temp.isbn) {
sd_total.units_sold += sd_temp.units_sold;
sd_total.revenue += sd_temp.revenue;
} else {
std::cout << "ERROR: ISBN number does not match.";
return 1;
}
}
// Present the result.
std::cout << "ISBN: " << sd_total.isbn << std::endl;
std::cout << "Total sold: " << sd_total.units_sold << std::endl;
std::cout << "Total revenue: " << sd_total.revenue << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2015, Bradley J Chambers ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
// The PluginManager was modeled very closely after the work of Gigi Sayfan in
// the Dr. Dobbs article:
// http://www.drdobbs.com/cpp/building-your-own-plugin-framework-part/206503957
// The original work was released under the Apache License v2.
#include <pdal/PluginManager.hpp>
#include <boost/filesystem.hpp>
#include <pdal/pdal_defines.h>
#include <pdal/util/FileUtils.hpp>
#include <pdal/util/Utils.hpp>
#include "DynamicLibrary.h"
#include <memory>
#include <sstream>
#include <string>
namespace pdal
{
namespace
{
#if defined(__APPLE__) && defined(__MACH__)
const std::string dynamicLibraryExtension(".dylib");
#elif defined __linux__
const std::string dynamicLibraryExtension(".so");
#elif defined _WIN32
const std::string dynamicLibraryExtension(".dll");
#endif
bool isValid(const PF_RegisterParams * params)
{
return (params && params->createFunc && params->destroyFunc);
}
bool pluginTypeValid(std::string pathname, PF_PluginType type)
{
bool valid(false);
if (Utils::startsWith(pathname, "libpdal_plugin_kernel"))
{
if (type == PF_PluginType_Kernel)
valid = true;
}
else if (Utils::startsWith(pathname, "libpdal_plugin_filter"))
{
if (type == PF_PluginType_Filter)
valid = true;
}
else if (Utils::startsWith(pathname, "libpdal_plugin_reader"))
{
if (type == PF_PluginType_Reader)
valid = true;
}
else if (Utils::startsWith(pathname, "libpdal_plugin_writer"))
{
if (type == PF_PluginType_Writer)
valid = true;
}
return valid;
}
}
bool PluginManager::registerObject(const std::string& objectType,
const PF_RegisterParams* params)
{
bool registered(false);
if (isValid(params))
{
PluginManager& pm = PluginManager::getInstance();
if (pm.m_version.major == params->version.major)
{
auto entry(std::make_pair(objectType, *params));
registered = pm.m_exactMatchMap.insert(entry).second;
}
}
return registered;
}
PluginManager& PluginManager::getInstance()
{
static PluginManager instance;
return instance;
}
void PluginManager::loadAll(PF_PluginType type)
{
std::string driver_path("PDAL_DRIVER_PATH");
std::string pluginDir = Utils::getenv(driver_path);
// If we don't have a driver path, defaults are set.
if (pluginDir.size() == 0)
{
std::ostringstream oss;
oss << PDAL_PLUGIN_INSTALL_PATH <<
":/usr/local/lib:./lib:../lib:../bin";
pluginDir = oss.str();
}
std::vector<std::string> pluginPathVec = Utils::split2(pluginDir, ':');
for (const auto& pluginPath : pluginPathVec)
{
loadAll(pluginPath, type);
}
}
void PluginManager::loadAll(const std::string& pluginDirectory,
PF_PluginType type)
{
const bool pluginDirectoryValid =
pluginDirectory.size() &&
(FileUtils::fileExists(pluginDirectory) ||
boost::filesystem::is_directory(pluginDirectory));
if (pluginDirectoryValid)
{
boost::filesystem::directory_iterator dir(pluginDirectory), it, end;
// Looks like directory_iterator doesn't support range-based for loop in
// Boost v1.55. It fails Travis anyway, so I reverted it.
for (it = dir; it != end; ++it)
{
boost::filesystem::path full_path = it->path();
if (boost::filesystem::is_directory(full_path))
continue;
std::string ext = full_path.extension().string();
if (ext != dynamicLibraryExtension)
continue;
loadByPath(full_path.string(), type);
}
}
}
bool PluginManager::initializePlugin(PF_InitFunc initFunc)
{
bool initialized(false);
PluginManager& pm = PluginManager::getInstance();
if (PF_ExitFunc exitFunc = initFunc())
{
initialized = true;
pm.m_exitFuncVec.push_back(exitFunc);
}
return initialized;
}
PluginManager::PluginManager()
{
m_version.major = 1;
m_version.minor = 0;
}
PluginManager::~PluginManager()
{
if (!shutdown())
{
std::cerr << "Error destructing PluginManager" << std::endl;
}
}
bool PluginManager::shutdown()
{
bool success(true);
for (auto const& func : m_exitFuncVec)
{
try
{
// Exit functions return 0 if successful.
if ((*func)() != 0)
{
success = false;
}
}
catch (...)
{
success = false;
}
}
m_dynamicLibraryMap.clear();
m_exactMatchMap.clear();
m_exitFuncVec.clear();
return success;
}
bool PluginManager::loadPlugin(const std::string& driverFileName)
{
std::vector<std::string> driverPathVec;
driverPathVec = Utils::split2(driverFileName, '.');
boost::filesystem::path full_path(driverFileName);
if (boost::filesystem::is_directory(full_path))
return false;
std::string ext = full_path.extension().string();
if (ext != dynamicLibraryExtension)
return false;
std::string stem = full_path.stem().string();
std::vector<std::string> driverNameVec;
driverNameVec = Utils::split2(driverPathVec[0], '_');
std::string ptype;
if (driverNameVec.size() >=3)
ptype = driverNameVec[2];
PF_PluginType type;
if (Utils::iequals(ptype, "reader"))
type = PF_PluginType_Reader;
else if (Utils::iequals(ptype,"kernel"))
type = PF_PluginType_Kernel;
else if (Utils::iequals(ptype, "filter"))
type = PF_PluginType_Filter;
else if (Utils::iequals(ptype, "writer"))
type = PF_PluginType_Writer;
else
throw pdal_error("Unknown plugin type '" + ptype +"'");
if (loadByPath(full_path.string(), type))
{
return true;
}
return false;
}
bool PluginManager::guessLoadByPath(const std::string& driverName)
{
// parse the driver name into an expected pluginName, e.g.,
// writers.las => libpdal_plugin_writer_las
std::vector<std::string> driverNameVec;
driverNameVec = Utils::split2(driverName, '.');
std::string pluginName = "libpdal_plugin_" + driverNameVec[0] + "_" +
driverNameVec[1];
std::string driver_path("PDAL_DRIVER_PATH");
std::string pluginDir = Utils::getenv(driver_path);
// Default path below if not set.
if (pluginDir.size() == 0)
{
std::ostringstream oss;
oss << PDAL_PLUGIN_INSTALL_PATH <<
":/usr/local/lib:./lib:../lib:../bin";
pluginDir = oss.str();
}
std::vector<std::string> pluginPathVec = Utils::split2(pluginDir, ':');
for (const auto& pluginPath : pluginPathVec)
{
boost::filesystem::path path(pluginPath);
if (!FileUtils::fileExists(path.string()) ||
!boost::filesystem::is_directory(path))
continue;
boost::filesystem::directory_iterator dir(path), it, end;
// Looks like directory_iterator doesn't support range-based for loop in
// Boost v1.55. It fails Travis anyway, so I reverted it.
for (it = dir; it != end; ++it)
{
boost::filesystem::path full_path = it->path();
if (boost::filesystem::is_directory(full_path))
continue;
std::string ext = full_path.extension().string();
if (ext != dynamicLibraryExtension)
continue;
std::string stem = full_path.stem().string();
std::string::size_type pos = stem.find_last_of('_');
if (pos == std::string::npos || pos == stem.size() - 1 ||
stem.substr(pos + 1) != driverNameVec[1])
continue;
PF_PluginType type;
if (driverNameVec[0] == "readers")
type = PF_PluginType_Reader;
else if (driverNameVec[0] == "kernels")
type = PF_PluginType_Kernel;
else if (driverNameVec[0] == "filters")
type = PF_PluginType_Filter;
else if (driverNameVec[0] == "writers")
type = PF_PluginType_Writer;
else
type = PF_PluginType_Reader;
if (loadByPath(full_path.string(), type))
{
return true;
}
}
}
return false;
}
bool PluginManager::loadByPath(const std::string& pluginPath,
PF_PluginType type)
{
// Only filenames that start with libpdal_plugin are candidates to be loaded
// at runtime. PDAL plugins are to be named in a specified form:
// libpdal_plugin_{stagetype}_{name}
// For example, libpdal_plugin_writer_text or libpdal_plugin_filter_color
bool loaded(false);
boost::filesystem::path path(pluginPath);
std::string pathname = Utils::tolower(path.filename().string());
// If we are a valid type, and we're not yet already
// loaded in the LibraryMap, load it.
std::string plugin_debug("PDAL_DEBUG");
std::string plugin_debug_path = Utils::getenv(plugin_debug);
if (pluginTypeValid(pathname, type) &&
m_dynamicLibraryMap.find(path.string()) == m_dynamicLibraryMap.end())
{
std::string errorString;
auto completePath(boost::filesystem::complete(path).string());
if (plugin_debug_path.size())
{
std::cerr << "PDAL: attempting to load plugin '" << completePath <<"'"<<std::endl;
}
if (DynamicLibrary *d = loadLibrary(completePath, errorString))
{
if (plugin_debug_path.size())
{
std::cerr << "PDAL: loaded plugin '" << completePath <<"'"<<std::endl;
}
if (PF_InitFunc initFunc =
(PF_InitFunc)(d->getSymbol("PF_initPlugin")))
{
loaded = initializePlugin(initFunc);
if (plugin_debug_path.size())
{
std::cerr << "PDAL: initialized plugin '" << completePath <<"'"<<std::endl;
}
} else
{
if (plugin_debug_path.size())
{
std::cerr << "PDAL: failed to initialize plugin '" << completePath <<"'"<<std::endl;
}
}
}
}
return loaded;
}
void *PluginManager::createObject(const std::string& objectType)
{
void* obj(0);
auto find([this, &objectType]()->bool
{
return m_exactMatchMap.count(objectType);
});
if (find() || (guessLoadByPath(objectType) && find()))
{
obj = m_exactMatchMap[objectType].createFunc();
}
return obj;
}
DynamicLibrary *PluginManager::loadLibrary(const std::string& path,
std::string & errorString)
{
DynamicLibrary *d = DynamicLibrary::load(path, errorString);
if (d)
{
m_dynamicLibraryMap[boost::filesystem::complete(path).string()] =
DynLibPtr(d);
}
return d;
}
const PluginManager::RegistrationMap& PluginManager::getRegistrationMap()
{
return m_exactMatchMap;
}
} // namespace pdal
<commit_msg>output the PDAL plugin search path to stderr when PDAL_DEBUG environment variable is set<commit_after>/******************************************************************************
* Copyright (c) 2015, Bradley J Chambers ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
// The PluginManager was modeled very closely after the work of Gigi Sayfan in
// the Dr. Dobbs article:
// http://www.drdobbs.com/cpp/building-your-own-plugin-framework-part/206503957
// The original work was released under the Apache License v2.
#include <pdal/PluginManager.hpp>
#include <boost/filesystem.hpp>
#include <pdal/pdal_defines.h>
#include <pdal/util/FileUtils.hpp>
#include <pdal/util/Utils.hpp>
#include "DynamicLibrary.h"
#include <memory>
#include <sstream>
#include <string>
namespace pdal
{
namespace
{
#if defined(__APPLE__) && defined(__MACH__)
const std::string dynamicLibraryExtension(".dylib");
#elif defined __linux__
const std::string dynamicLibraryExtension(".so");
#elif defined _WIN32
const std::string dynamicLibraryExtension(".dll");
#endif
bool isValid(const PF_RegisterParams * params)
{
return (params && params->createFunc && params->destroyFunc);
}
bool pluginTypeValid(std::string pathname, PF_PluginType type)
{
bool valid(false);
if (Utils::startsWith(pathname, "libpdal_plugin_kernel"))
{
if (type == PF_PluginType_Kernel)
valid = true;
}
else if (Utils::startsWith(pathname, "libpdal_plugin_filter"))
{
if (type == PF_PluginType_Filter)
valid = true;
}
else if (Utils::startsWith(pathname, "libpdal_plugin_reader"))
{
if (type == PF_PluginType_Reader)
valid = true;
}
else if (Utils::startsWith(pathname, "libpdal_plugin_writer"))
{
if (type == PF_PluginType_Writer)
valid = true;
}
return valid;
}
}
bool PluginManager::registerObject(const std::string& objectType,
const PF_RegisterParams* params)
{
bool registered(false);
if (isValid(params))
{
PluginManager& pm = PluginManager::getInstance();
if (pm.m_version.major == params->version.major)
{
auto entry(std::make_pair(objectType, *params));
registered = pm.m_exactMatchMap.insert(entry).second;
}
}
return registered;
}
PluginManager& PluginManager::getInstance()
{
static PluginManager instance;
return instance;
}
void PluginManager::loadAll(PF_PluginType type)
{
std::string driver_path("PDAL_DRIVER_PATH");
std::string pluginDir = Utils::getenv(driver_path);
// If we don't have a driver path, defaults are set.
if (pluginDir.size() == 0)
{
std::ostringstream oss;
oss << PDAL_PLUGIN_INSTALL_PATH <<
":/usr/local/lib:./lib:../lib:../bin";
pluginDir = oss.str();
}
std::vector<std::string> pluginPathVec = Utils::split2(pluginDir, ':');
for (const auto& pluginPath : pluginPathVec)
{
loadAll(pluginPath, type);
}
}
void PluginManager::loadAll(const std::string& pluginDirectory,
PF_PluginType type)
{
const bool pluginDirectoryValid =
pluginDirectory.size() &&
(FileUtils::fileExists(pluginDirectory) ||
boost::filesystem::is_directory(pluginDirectory));
if (pluginDirectoryValid)
{
boost::filesystem::directory_iterator dir(pluginDirectory), it, end;
// Looks like directory_iterator doesn't support range-based for loop in
// Boost v1.55. It fails Travis anyway, so I reverted it.
for (it = dir; it != end; ++it)
{
boost::filesystem::path full_path = it->path();
if (boost::filesystem::is_directory(full_path))
continue;
std::string ext = full_path.extension().string();
if (ext != dynamicLibraryExtension)
continue;
loadByPath(full_path.string(), type);
}
}
}
bool PluginManager::initializePlugin(PF_InitFunc initFunc)
{
bool initialized(false);
PluginManager& pm = PluginManager::getInstance();
if (PF_ExitFunc exitFunc = initFunc())
{
initialized = true;
pm.m_exitFuncVec.push_back(exitFunc);
}
return initialized;
}
PluginManager::PluginManager()
{
m_version.major = 1;
m_version.minor = 0;
}
PluginManager::~PluginManager()
{
if (!shutdown())
{
std::cerr << "Error destructing PluginManager" << std::endl;
}
}
bool PluginManager::shutdown()
{
bool success(true);
for (auto const& func : m_exitFuncVec)
{
try
{
// Exit functions return 0 if successful.
if ((*func)() != 0)
{
success = false;
}
}
catch (...)
{
success = false;
}
}
m_dynamicLibraryMap.clear();
m_exactMatchMap.clear();
m_exitFuncVec.clear();
return success;
}
bool PluginManager::loadPlugin(const std::string& driverFileName)
{
std::vector<std::string> driverPathVec;
driverPathVec = Utils::split2(driverFileName, '.');
boost::filesystem::path full_path(driverFileName);
if (boost::filesystem::is_directory(full_path))
return false;
std::string ext = full_path.extension().string();
if (ext != dynamicLibraryExtension)
return false;
std::string stem = full_path.stem().string();
std::vector<std::string> driverNameVec;
driverNameVec = Utils::split2(driverPathVec[0], '_');
std::string ptype;
if (driverNameVec.size() >=3)
ptype = driverNameVec[2];
PF_PluginType type;
if (Utils::iequals(ptype, "reader"))
type = PF_PluginType_Reader;
else if (Utils::iequals(ptype,"kernel"))
type = PF_PluginType_Kernel;
else if (Utils::iequals(ptype, "filter"))
type = PF_PluginType_Filter;
else if (Utils::iequals(ptype, "writer"))
type = PF_PluginType_Writer;
else
throw pdal_error("Unknown plugin type '" + ptype +"'");
if (loadByPath(full_path.string(), type))
{
return true;
}
return false;
}
bool PluginManager::guessLoadByPath(const std::string& driverName)
{
// parse the driver name into an expected pluginName, e.g.,
// writers.las => libpdal_plugin_writer_las
std::vector<std::string> driverNameVec;
driverNameVec = Utils::split2(driverName, '.');
std::string pluginName = "libpdal_plugin_" + driverNameVec[0] + "_" +
driverNameVec[1];
std::string driver_path("PDAL_DRIVER_PATH");
std::string pluginDir = Utils::getenv(driver_path);
// Default path below if not set.
if (pluginDir.size() == 0)
{
std::ostringstream oss;
oss << PDAL_PLUGIN_INSTALL_PATH <<
":/usr/local/lib:./lib:../lib:../bin";
pluginDir = oss.str();
}
std::string plugin_debug("PDAL_DEBUG");
std::string plugin_debug_path = Utils::getenv(plugin_debug);
if (plugin_debug_path.size())
{
std::cerr << "PDAL: plugin search path '" << pluginDir <<"'"<<std::endl;
}
std::vector<std::string> pluginPathVec = Utils::split2(pluginDir, ':');
for (const auto& pluginPath : pluginPathVec)
{
boost::filesystem::path path(pluginPath);
if (!FileUtils::fileExists(path.string()) ||
!boost::filesystem::is_directory(path))
continue;
boost::filesystem::directory_iterator dir(path), it, end;
// Looks like directory_iterator doesn't support range-based for loop in
// Boost v1.55. It fails Travis anyway, so I reverted it.
for (it = dir; it != end; ++it)
{
boost::filesystem::path full_path = it->path();
if (boost::filesystem::is_directory(full_path))
continue;
std::string ext = full_path.extension().string();
if (ext != dynamicLibraryExtension)
continue;
std::string stem = full_path.stem().string();
std::string::size_type pos = stem.find_last_of('_');
if (pos == std::string::npos || pos == stem.size() - 1 ||
stem.substr(pos + 1) != driverNameVec[1])
continue;
PF_PluginType type;
if (driverNameVec[0] == "readers")
type = PF_PluginType_Reader;
else if (driverNameVec[0] == "kernels")
type = PF_PluginType_Kernel;
else if (driverNameVec[0] == "filters")
type = PF_PluginType_Filter;
else if (driverNameVec[0] == "writers")
type = PF_PluginType_Writer;
else
type = PF_PluginType_Reader;
if (loadByPath(full_path.string(), type))
{
return true;
}
}
}
return false;
}
bool PluginManager::loadByPath(const std::string& pluginPath,
PF_PluginType type)
{
// Only filenames that start with libpdal_plugin are candidates to be loaded
// at runtime. PDAL plugins are to be named in a specified form:
// libpdal_plugin_{stagetype}_{name}
// For example, libpdal_plugin_writer_text or libpdal_plugin_filter_color
bool loaded(false);
boost::filesystem::path path(pluginPath);
std::string pathname = Utils::tolower(path.filename().string());
// If we are a valid type, and we're not yet already
// loaded in the LibraryMap, load it.
std::string plugin_debug("PDAL_DEBUG");
std::string plugin_debug_path = Utils::getenv(plugin_debug);
if (pluginTypeValid(pathname, type) &&
m_dynamicLibraryMap.find(path.string()) == m_dynamicLibraryMap.end())
{
std::string errorString;
auto completePath(boost::filesystem::complete(path).string());
if (plugin_debug_path.size())
{
std::cerr << "PDAL: attempting to load plugin '" << completePath <<"'"<<std::endl;
}
if (DynamicLibrary *d = loadLibrary(completePath, errorString))
{
if (plugin_debug_path.size())
{
std::cerr << "PDAL: loaded plugin '" << completePath <<"'"<<std::endl;
}
if (PF_InitFunc initFunc =
(PF_InitFunc)(d->getSymbol("PF_initPlugin")))
{
loaded = initializePlugin(initFunc);
if (plugin_debug_path.size())
{
std::cerr << "PDAL: initialized plugin '" << completePath <<"'"<<std::endl;
}
} else
{
if (plugin_debug_path.size())
{
std::cerr << "PDAL: failed to initialize plugin '" << completePath <<"'"<<std::endl;
}
}
}
}
return loaded;
}
void *PluginManager::createObject(const std::string& objectType)
{
void* obj(0);
auto find([this, &objectType]()->bool
{
return m_exactMatchMap.count(objectType);
});
if (find() || (guessLoadByPath(objectType) && find()))
{
obj = m_exactMatchMap[objectType].createFunc();
}
return obj;
}
DynamicLibrary *PluginManager::loadLibrary(const std::string& path,
std::string & errorString)
{
DynamicLibrary *d = DynamicLibrary::load(path, errorString);
if (d)
{
m_dynamicLibraryMap[boost::filesystem::complete(path).string()] =
DynLibPtr(d);
}
return d;
}
const PluginManager::RegistrationMap& PluginManager::getRegistrationMap()
{
return m_exactMatchMap;
}
} // namespace pdal
<|endoftext|> |
<commit_before>/* This is a fuzz test of the http parser */
#define WIN32_EXPORT
#include "helpers.h"
/* We test the websocket parser */
#include "../src/HttpParser.h"
/* And the router */
#include "../src/HttpRouter.h"
struct StaticData {
struct RouterData {
};
uWS::HttpRouter<RouterData> router;
StaticData() {
router.add({"get"}, "/:hello/:hi", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != 1 || !params[0].length() || !params[1].length()) {
exit(-1);
}
/* This route did handle it */
return true;
});
router.add({"post"}, "/:hello/:hi/*", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != 1 || !params[0].length() || !params[1].length()) {
exit(-1);
}
/* This route did handle it */
return true;
});
router.add({"get"}, "/*", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != -1) {
exit(-1);
}
/* This route did not handle it */
return false;
});
router.add({"get"}, "/hi", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != -1) {
exit(-1);
}
/* This route did handle it */
return true;
});
}
} staticData;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
/* Create parser */
uWS::HttpParser httpParser;
/* User data */
void *user = (void *) 13;
/* Iterate the padded fuzz as chunks */
makeChunked(makePadded(data, size), size, [&httpParser, user](const uint8_t *data, size_t size) {
/* We need at least 1 byte post padding */
if (size) {
size--;
} else {
/* We might be given zero length chunks */
return;
}
/* Parse it */
httpParser.consumePostPadded((char *) data, size, user, nullptr, [](void *s, uWS::HttpRequest *httpRequest) -> void * {
readBytes(httpRequest->getHeader(httpRequest->getUrl()));
readBytes(httpRequest->getMethod());
readBytes(httpRequest->getQuery());
/* Route the method and URL in two passes */
staticData.router.getUserData() = {};
if (!staticData.router.route(httpRequest->getMethod(), httpRequest->getUrl())) {
/* It was not handled */
return nullptr;
}
for (auto p : *httpRequest) {
}
/* Return ok */
return s;
}, [](void *user, std::string_view data, bool fin) -> void * {
/* Return ok */
return user;
}, [](void *user) {
/* Return break */
return nullptr;
});
});
return 0;
}
<commit_msg>Fix Http.cpp fuzzing as HttpWithProxy<commit_after>/* This is a fuzz test of the http parser */
#define WIN32_EXPORT
#include "helpers.h"
/* We test the websocket parser */
#include "../src/HttpParser.h"
/* And the router */
#include "../src/HttpRouter.h"
/* Also ProxyParser */
#include "../src/ProxyParser.h"
struct StaticData {
struct RouterData {
};
uWS::HttpRouter<RouterData> router;
StaticData() {
router.add({"get"}, "/:hello/:hi", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != 1 || !params[0].length() || !params[1].length()) {
exit(-1);
}
/* This route did handle it */
return true;
});
router.add({"post"}, "/:hello/:hi/*", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != 1 || !params[0].length() || !params[1].length()) {
exit(-1);
}
/* This route did handle it */
return true;
});
router.add({"get"}, "/*", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != -1) {
exit(-1);
}
/* This route did not handle it */
return false;
});
router.add({"get"}, "/hi", [](auto *h) mutable {
auto [paramsTop, params] = h->getParameters();
/* Something is horribly wrong */
if (paramsTop != -1) {
exit(-1);
}
/* This route did handle it */
return true;
});
}
} staticData;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
/* Create parser */
uWS::HttpParser httpParser;
/* User data */
void *user = (void *) 13;
/* If we are built with WITH_PROXY, pass a ProxyParser as reserved */
void *reserved = nullptr;
#ifdef UWS_WITH_PROXY
uWS::ProxyParser pp;
reserved = (void *) &pp;
#endif
/* Iterate the padded fuzz as chunks */
makeChunked(makePadded(data, size), size, [&httpParser, user, reserved](const uint8_t *data, size_t size) {
/* We need at least 1 byte post padding */
if (size) {
size--;
} else {
/* We might be given zero length chunks */
return;
}
/* Parse it */
httpParser.consumePostPadded((char *) data, size, user, reserved, [](void *s, uWS::HttpRequest *httpRequest) -> void * {
readBytes(httpRequest->getHeader(httpRequest->getUrl()));
readBytes(httpRequest->getMethod());
readBytes(httpRequest->getQuery());
/* Route the method and URL in two passes */
staticData.router.getUserData() = {};
if (!staticData.router.route(httpRequest->getMethod(), httpRequest->getUrl())) {
/* It was not handled */
return nullptr;
}
for (auto p : *httpRequest) {
}
/* Return ok */
return s;
}, [](void *user, std::string_view data, bool fin) -> void * {
/* Return ok */
return user;
}, [](void *user) {
/* Return break */
return nullptr;
});
});
return 0;
}
<|endoftext|> |
<commit_before>/*
* compile both driver code and kernel code with nvcc, as in:
* nvcc simple.c simple.cu
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
extern "C" void gpu_sobel(int *source_array, int *result_array,
int dest_row_size, int dest_column_size);
#pragma pack(1)
typedef struct {
char id[2];
int file_size;
int reserved;
int offset;
} header_type;
#pragma pack(1)
typedef struct {
int header_size;
int width;
int height;
unsigned short int color_planes;
unsigned short int color_depth;
unsigned int compression;
int image_size;
int xresolution;
int yresolution;
int num_colors;
int num_important_colors;
} information_type;
int main(int argc, char *argv[]) {
header_type header;
information_type information;
string imageFileName, newImageFileName;
unsigned char tempData[3];
int row, col, row_bytes, padding;
vector<vector<int>> data, newData;
// prepare files
cout << "Original imagefile? ";
cin >> imageFileName;
ifstream imageFile;
imageFile.open(imageFileName.c_str(), ios::binary);
if (!imageFile) {
cerr << "file not found" << endl;
exit(-1);
}
cout << "New imagefile name? ";
cin >> newImageFileName;
ofstream newImageFile;
newImageFile.open(newImageFileName.c_str(), ios::binary);
// read file header
imageFile.read((char *)&header, sizeof(header_type));
if (header.id[0] != 'B' || header.id[1] != 'M') {
cerr << "Does not appear to be a .bmp file. Goodbye." << endl;
exit(-1);
}
// read/compute image information
imageFile.read((char *)&information, sizeof(information_type));
row_bytes = information.width * 3;
padding = row_bytes % 4;
if (padding)
padding = 4 - padding;
int row_size = information.width + 2;
int column_size = information.height + 2;
// extract image data, initialize vectors
for (row = 0; row < information.height; row++) {
data.push_back(vector<int>());
// pad first column
data[row].push_back(0);
for (col = 0; col < information.width; col++) {
imageFile.read((char *)tempData, 3 * sizeof(unsigned char));
data[row].push_back((int)tempData[0]);
}
// pad last column
data[row].push_back(0);
if (padding)
imageFile.read((char *)tempData, padding * sizeof(unsigned char));
}
// pad first row
data.insert(data.begin(), vector<int>(information.width + 2));
// pad last row
data.push_back(vector<int>(information.width + 2));
cout << imageFileName << ": " << information.width << " x "
<< information.height << endl;
clock_t gpu_start = clock();
gpu_sobel(data, newData, information.width, information.height);
clock_t gpu_stop = clock();
double elapsed_gpu = double(gpu_stop - gpu_start) / (CLOCKS_PER_SEC / 1000);
std::cout << "GPU Time Taken (msec): " << elapsed_gpu << std::endl;
// write header to new image file
newImageFile.write((char *)&header, sizeof(header_type));
newImageFile.write((char *)&information, sizeof(information_type));
// write new image data to new image file
for (row = 0; row < information.height; row++) {
for (col = 0; col < information.width; col++) {
tempData[0] = (unsigned char)newData[row][col];
tempData[1] = (unsigned char)newData[row][col];
tempData[2] = (unsigned char)newData[row][col];
newImageFile.write((char *)tempData, 3 * sizeof(unsigned char));
}
if (padding) {
tempData[0] = 0;
tempData[1] = 0;
tempData[2] = 0;
newImageFile.write((char *)tempData, padding * sizeof(unsigned char));
}
}
cout << newImageFileName << " done." << endl;
imageFile.close();
newImageFile.close();
return 0;
}
<commit_msg>add std ns<commit_after>/*
* compile both driver code and kernel code with nvcc, as in:
* nvcc simple.c simple.cu
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
using namespace std;
extern "C" void gpu_sobel(int *source_array, int *result_array,
int dest_row_size, int dest_column_size);
#pragma pack(1)
typedef struct {
char id[2];
int file_size;
int reserved;
int offset;
} header_type;
#pragma pack(1)
typedef struct {
int header_size;
int width;
int height;
unsigned short int color_planes;
unsigned short int color_depth;
unsigned int compression;
int image_size;
int xresolution;
int yresolution;
int num_colors;
int num_important_colors;
} information_type;
int main(int argc, char *argv[]) {
header_type header;
information_type information;
string imageFileName, newImageFileName;
unsigned char tempData[3];
int row, col, row_bytes, padding;
vector<vector<int>> data, newData;
// prepare files
cout << "Original imagefile? ";
cin >> imageFileName;
ifstream imageFile;
imageFile.open(imageFileName.c_str(), ios::binary);
if (!imageFile) {
cerr << "file not found" << endl;
exit(-1);
}
cout << "New imagefile name? ";
cin >> newImageFileName;
ofstream newImageFile;
newImageFile.open(newImageFileName.c_str(), ios::binary);
// read file header
imageFile.read((char *)&header, sizeof(header_type));
if (header.id[0] != 'B' || header.id[1] != 'M') {
cerr << "Does not appear to be a .bmp file. Goodbye." << endl;
exit(-1);
}
// read/compute image information
imageFile.read((char *)&information, sizeof(information_type));
row_bytes = information.width * 3;
padding = row_bytes % 4;
if (padding)
padding = 4 - padding;
int row_size = information.width + 2;
int column_size = information.height + 2;
// extract image data, initialize vectors
for (row = 0; row < information.height; row++) {
data.push_back(vector<int>());
// pad first column
data[row].push_back(0);
for (col = 0; col < information.width; col++) {
imageFile.read((char *)tempData, 3 * sizeof(unsigned char));
data[row].push_back((int)tempData[0]);
}
// pad last column
data[row].push_back(0);
if (padding)
imageFile.read((char *)tempData, padding * sizeof(unsigned char));
}
// pad first row
data.insert(data.begin(), vector<int>(information.width + 2));
// pad last row
data.push_back(vector<int>(information.width + 2));
cout << imageFileName << ": " << information.width << " x "
<< information.height << endl;
clock_t gpu_start = clock();
gpu_sobel(data, newData, information.width, information.height);
clock_t gpu_stop = clock();
double elapsed_gpu = double(gpu_stop - gpu_start) / (CLOCKS_PER_SEC / 1000);
std::cout << "GPU Time Taken (msec): " << elapsed_gpu << std::endl;
// write header to new image file
newImageFile.write((char *)&header, sizeof(header_type));
newImageFile.write((char *)&information, sizeof(information_type));
// write new image data to new image file
for (row = 0; row < information.height; row++) {
for (col = 0; col < information.width; col++) {
tempData[0] = (unsigned char)newData[row][col];
tempData[1] = (unsigned char)newData[row][col];
tempData[2] = (unsigned char)newData[row][col];
newImageFile.write((char *)tempData, 3 * sizeof(unsigned char));
}
if (padding) {
tempData[0] = 0;
tempData[1] = 0;
tempData[2] = 0;
newImageFile.write((char *)tempData, padding * sizeof(unsigned char));
}
}
cout << newImageFileName << " done." << endl;
imageFile.close();
newImageFile.close();
return 0;
}
<|endoftext|> |
<commit_before>#include "setupwizard_register.h"
#include "warnings-disable.h"
WARNINGS_DISABLE
#include <QDateTime>
#include <QFileDialog>
// This is used for QHostInfo::localHostName(). It could be replaced with
// QSysInfo::machineHostName() to remove the dependency on the Qt network
// library, but only if we require Qt 5.6+.
#include <QHostInfo>
#include "ui_setupwizard_register.h"
WARNINGS_ENABLE
#include <TSettings.h>
#include <TWizardPage.h>
#include "taskstatus.h"
#include "utils.h"
RegisterPage::RegisterPage(QWidget *parent)
: TWizardPage(parent),
_ui(new Ui::RegisterPage),
_createKey(true),
_registering(No)
{
_ui->setupUi(this);
// Basic operations on this page.
connect(_ui->createKeyfileButton, &QPushButton::clicked, this,
&RegisterPage::createKeyfile);
connect(_ui->useExistingKeyfileButton, &QPushButton::clicked, this,
&RegisterPage::useExistingKeyfile);
// A config field changed.
connect(_ui->machineNameLineEdit, &QLineEdit::textChanged, this,
&RegisterPage::checkComplete);
connect(_ui->tarsnapUserLineEdit, &QLineEdit::textChanged, this,
&RegisterPage::checkComplete);
connect(_ui->tarsnapPasswordLineEdit, &QLineEdit::textChanged, this,
&RegisterPage::checkComplete);
connect(_ui->keyfilePathComboBrowse, &PathComboBrowse::textChanged, this,
&RegisterPage::checkComplete);
}
RegisterPage::~RegisterPage()
{
delete _ui;
}
void RegisterPage::initializePage()
{
TWizardPage::initializePage();
// Default machine name.
_ui->machineNameLineEdit->setText(QHostInfo::localHostName());
// Find any existing keys.
TSettings settings;
QString appDataDir = settings.value("app/app_data", "").toString();
for(const QFileInfo &file : Utils::findKeysInPath(appDataDir))
_ui->keyfilePathComboBrowse->addItem(file.canonicalFilePath());
// Auto-select "use existing" if we have any.
if(_ui->keyfilePathComboBrowse->count() > 0)
_ui->useExistingKeyfileButton->click();
// Enable keyboard focus if we're ready to go.
if(checkComplete())
_ui->nextButton->setFocus();
}
void RegisterPage::createKeyfile()
{
_createKey = true;
_ui->registerKeyStackedWidget->setCurrentWidget(_ui->createKeyfileSubpage);
_ui->statusLabel->clear();
checkComplete();
}
void RegisterPage::useExistingKeyfile()
{
_createKey = false;
_ui->registerKeyStackedWidget->setCurrentWidget(
_ui->useExistingKeyfileSubpage);
_ui->statusLabel->clear();
checkComplete();
}
bool RegisterPage::reportError(const QString &text)
{
_ui->statusLabel->messageError(text);
return false;
}
void RegisterPage::next()
{
if(_registering == Done)
{
emit nextPage();
return;
}
else
{
registerMachine();
}
}
bool RegisterPage::checkComplete()
{
// Check mandatory fields (depending on which tab we're on).
if(_createKey)
{
if(_ui->machineNameLineEdit->text().isEmpty())
return setProceedButton(false);
if(_ui->tarsnapUserLineEdit->text().isEmpty())
return setProceedButton(false);
if(_ui->tarsnapPasswordLineEdit->text().isEmpty())
return setProceedButton(false);
}
else
{
if(!checkKeyfile(_ui->keyfilePathComboBrowse->text()))
return setProceedButton(false);
}
// Disable the button if we're already registering.
if(_registering == Yes)
return setProceedButton(false);
else
return setProceedButton(true);
}
void RegisterPage::registerMachine()
{
TSettings settings;
QString tarsnapKeyFile;
QString appDataDir;
// Sanity check app data dir.
appDataDir = settings.value("app/app_data", "").toString();
if(appDataDir.isEmpty())
{
// We should never get here, but handle the error anyway
reportError("No app data dir set");
checkComplete();
return;
}
bool useExistingKeyfile = false;
_ui->statusLabel->clear();
if(_ui->useExistingKeyfileButton->isChecked())
{
useExistingKeyfile = true;
_ui->statusLabel->messageNormal("Verifying archive integrity...");
tarsnapKeyFile = _ui->keyfilePathComboBrowse->text();
}
else
{
_ui->statusLabel->messageNormal("Generating keyfile...");
tarsnapKeyFile =
appDataDir + QDir::separator() + _ui->machineNameLineEdit->text()
+ "-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")
+ ".key";
}
Q_ASSERT(!tarsnapKeyFile.isEmpty());
settings.setValue("tarsnap/key", tarsnapKeyFile);
settings.setValue("tarsnap/user", _ui->tarsnapUserLineEdit->text());
if(checkComplete())
{
_registering = Yes;
emit registerMachineRequested(_ui->tarsnapPasswordLineEdit->text(),
_ui->machineNameLineEdit->text(),
useExistingKeyfile);
}
}
void RegisterPage::registerMachineResponse(TaskStatus status, QString reason)
{
TSettings settings;
// Get keyfile and sanity check.
QString tarsnapKeyFile = settings.value("tarsnap/key", "").toString();
if((status == TaskStatus::Completed) && (tarsnapKeyFile.isEmpty()))
{
// This should never happen.
status = TaskStatus::Failed;
reason = "No keyfile set";
}
switch(status)
{
case TaskStatus::Completed:
_registering = Done;
_ui->statusLabel->clear();
emit next();
break;
case TaskStatus::Failed:
reportError(reason);
checkComplete();
break;
default:
// We shouldn't receive anything else, so ignore it.
break;
}
}
bool RegisterPage::checkKeyfile(const QString &filename)
{
if(filename.isEmpty())
return false;
QFileInfo machineKeyFile(filename);
if(machineKeyFile.exists() && machineKeyFile.isFile()
&& machineKeyFile.isReadable())
{
_ui->statusLabel->clear();
return true;
}
else
return reportError("Invalid machine key");
}
void RegisterPage::updateLoadingAnimation(bool idle)
{
_ui->busyWidget->animate(!idle);
}
<commit_msg>RegisterPage: simplify clearing the status label<commit_after>#include "setupwizard_register.h"
#include "warnings-disable.h"
WARNINGS_DISABLE
#include <QDateTime>
#include <QFileDialog>
// This is used for QHostInfo::localHostName(). It could be replaced with
// QSysInfo::machineHostName() to remove the dependency on the Qt network
// library, but only if we require Qt 5.6+.
#include <QHostInfo>
#include "ui_setupwizard_register.h"
WARNINGS_ENABLE
#include <TSettings.h>
#include <TWizardPage.h>
#include "taskstatus.h"
#include "utils.h"
RegisterPage::RegisterPage(QWidget *parent)
: TWizardPage(parent),
_ui(new Ui::RegisterPage),
_createKey(true),
_registering(No)
{
_ui->setupUi(this);
// Basic operations on this page.
connect(_ui->createKeyfileButton, &QPushButton::clicked, this,
&RegisterPage::createKeyfile);
connect(_ui->useExistingKeyfileButton, &QPushButton::clicked, this,
&RegisterPage::useExistingKeyfile);
// A config field changed.
connect(_ui->machineNameLineEdit, &QLineEdit::textChanged, this,
&RegisterPage::checkComplete);
connect(_ui->tarsnapUserLineEdit, &QLineEdit::textChanged, this,
&RegisterPage::checkComplete);
connect(_ui->tarsnapPasswordLineEdit, &QLineEdit::textChanged, this,
&RegisterPage::checkComplete);
connect(_ui->keyfilePathComboBrowse, &PathComboBrowse::textChanged, this,
&RegisterPage::checkComplete);
}
RegisterPage::~RegisterPage()
{
delete _ui;
}
void RegisterPage::initializePage()
{
TWizardPage::initializePage();
// Default machine name.
_ui->machineNameLineEdit->setText(QHostInfo::localHostName());
// Find any existing keys.
TSettings settings;
QString appDataDir = settings.value("app/app_data", "").toString();
for(const QFileInfo &file : Utils::findKeysInPath(appDataDir))
_ui->keyfilePathComboBrowse->addItem(file.canonicalFilePath());
// Auto-select "use existing" if we have any.
if(_ui->keyfilePathComboBrowse->count() > 0)
_ui->useExistingKeyfileButton->click();
// Enable keyboard focus if we're ready to go.
if(checkComplete())
_ui->nextButton->setFocus();
}
void RegisterPage::createKeyfile()
{
_createKey = true;
_ui->registerKeyStackedWidget->setCurrentWidget(_ui->createKeyfileSubpage);
checkComplete();
}
void RegisterPage::useExistingKeyfile()
{
_createKey = false;
_ui->registerKeyStackedWidget->setCurrentWidget(
_ui->useExistingKeyfileSubpage);
checkComplete();
}
bool RegisterPage::reportError(const QString &text)
{
_ui->statusLabel->messageError(text);
return false;
}
void RegisterPage::next()
{
if(_registering == Done)
{
emit nextPage();
return;
}
else
{
registerMachine();
}
}
bool RegisterPage::checkComplete()
{
_ui->statusLabel->clear();
// Check mandatory fields (depending on which tab we're on).
if(_createKey)
{
if(_ui->machineNameLineEdit->text().isEmpty())
return setProceedButton(false);
if(_ui->tarsnapUserLineEdit->text().isEmpty())
return setProceedButton(false);
if(_ui->tarsnapPasswordLineEdit->text().isEmpty())
return setProceedButton(false);
}
else
{
if(!checkKeyfile(_ui->keyfilePathComboBrowse->text()))
return setProceedButton(false);
}
// Disable the button if we're already registering.
if(_registering == Yes)
return setProceedButton(false);
else
return setProceedButton(true);
}
void RegisterPage::registerMachine()
{
TSettings settings;
QString tarsnapKeyFile;
QString appDataDir;
// Sanity check app data dir.
appDataDir = settings.value("app/app_data", "").toString();
if(appDataDir.isEmpty())
{
// We should never get here, but handle the error anyway
reportError("No app data dir set");
checkComplete();
return;
}
bool useExistingKeyfile = false;
if(_ui->useExistingKeyfileButton->isChecked())
{
useExistingKeyfile = true;
_ui->statusLabel->messageNormal("Verifying archive integrity...");
tarsnapKeyFile = _ui->keyfilePathComboBrowse->text();
}
else
{
_ui->statusLabel->messageNormal("Generating keyfile...");
tarsnapKeyFile =
appDataDir + QDir::separator() + _ui->machineNameLineEdit->text()
+ "-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")
+ ".key";
}
Q_ASSERT(!tarsnapKeyFile.isEmpty());
settings.setValue("tarsnap/key", tarsnapKeyFile);
settings.setValue("tarsnap/user", _ui->tarsnapUserLineEdit->text());
if(checkComplete())
{
_registering = Yes;
emit registerMachineRequested(_ui->tarsnapPasswordLineEdit->text(),
_ui->machineNameLineEdit->text(),
useExistingKeyfile);
}
}
void RegisterPage::registerMachineResponse(TaskStatus status, QString reason)
{
TSettings settings;
// Get keyfile and sanity check.
QString tarsnapKeyFile = settings.value("tarsnap/key", "").toString();
if((status == TaskStatus::Completed) && (tarsnapKeyFile.isEmpty()))
{
// This should never happen.
status = TaskStatus::Failed;
reason = "No keyfile set";
}
switch(status)
{
case TaskStatus::Completed:
_registering = Done;
_ui->statusLabel->clear();
emit next();
break;
case TaskStatus::Failed:
reportError(reason);
checkComplete();
break;
default:
// We shouldn't receive anything else, so ignore it.
break;
}
}
bool RegisterPage::checkKeyfile(const QString &filename)
{
if(filename.isEmpty())
return false;
QFileInfo machineKeyFile(filename);
if(machineKeyFile.exists() && machineKeyFile.isFile()
&& machineKeyFile.isReadable())
return true;
else
return reportError("Invalid machine key");
}
void RegisterPage::updateLoadingAnimation(bool idle)
{
_ui->busyWidget->animate(!idle);
}
<|endoftext|> |
<commit_before>#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
#include <cstring>
#include <string>
#include <set>
#include <algorithm>
#include <stdio.h>
#include <sys/stat.h>
#include <ctype.h>
#include "base/logging.h"
#include "base/basictypes.h"
#include "file/file_util.h"
#ifdef __FreeBSD__
#define stat64 stat
#endif
bool writeStringToFile(bool text_file, const std::string &str, const char *filename)
{
FILE *f = fopen(filename, text_file ? "w" : "wb");
if (!f)
return false;
size_t len = str.size();
if (len != fwrite(str.data(), 1, str.size(), f))
{
fclose(f);
return false;
}
fclose(f);
return true;
}
uint64_t GetSize(FILE *f)
{
// can't use off_t here because it can be 32-bit
uint64_t pos = ftell(f);
if (fseek(f, 0, SEEK_END) != 0) {
return 0;
}
uint64_t size = ftell(f);
// Reset the seek position to where it was when we started.
if ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) {
// Should error here
return 0;
}
return size;
}
bool ReadFileToString(bool text_file, const char *filename, std::string &str)
{
FILE *f = fopen(filename, text_file ? "r" : "rb");
if (!f)
return false;
size_t len = (size_t)GetSize(f);
char *buf = new char[len + 1];
buf[fread(buf, 1, len, f)] = 0;
str = std::string(buf, len);
fclose(f);
delete [] buf;
return true;
}
#define DIR_SEP "/"
#define DIR_SEP_CHR '\\'
#ifndef METRO
// Remove any ending forward slashes from directory paths
// Modifies argument.
static void stripTailDirSlashes(std::string &fname)
{
if (fname.length() > 1)
{
size_t i = fname.length() - 1;
while (fname[i] == DIR_SEP_CHR)
fname[i--] = '\0';
}
return;
}
// Returns true if file filename exists
bool exists(const std::string &filename)
{
#ifdef _WIN32
return GetFileAttributes(filename.c_str()) != 0xFFFFFFFF;
#else
struct stat64 file_info;
std::string copy(filename);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
return (result == 0);
#endif
}
// Returns true if filename is a directory
bool isDirectory(const std::string &filename)
{
#ifdef _WIN32
return (GetFileAttributes(filename.c_str()) & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
struct stat64 file_info;
std::string copy(filename);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
if (result < 0) {
WLOG("IsDirectory: stat failed on %s", filename.c_str());
return false;
}
return S_ISDIR(file_info.st_mode);
#endif
}
std::string getFileExtension(const std::string &fn) {
int pos = fn.rfind(".");
if (pos < 0) return "";
std::string ext = fn.substr(pos+1);
for (size_t i = 0; i < ext.size(); i++) {
ext[i] = tolower(ext[i]);
}
return ext;
}
size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) {
size_t foundEntries = 0;
std::set<std::string> filters;
std::string tmp;
if (filter) {
while (*filter) {
if (*filter == ':') {
filters.insert(tmp);
tmp = "";
} else {
tmp.push_back(*filter);
}
filter++;
}
}
#ifdef _WIN32
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
#ifdef UNICODE
HANDLE hFind = FindFirstFile((std::wstring(directory) + "\\*").c_str(), &ffd);
#else
HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd);
#endif
if (hFind == INVALID_HANDLE_VALUE) {
FindClose(hFind);
return 0;
}
// windows loop
do
{
const std::string virtualName(ffd.cFileName);
#else
struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; };
struct dirent_large diren;
struct dirent *result = NULL;
DIR *dirp = opendir(directory);
if (!dirp)
return 0;
// non windows loop
while (!readdir_r(dirp, (dirent*) &diren, &result) && result)
{
const std::string virtualName(result->d_name);
#endif
// check for "." and ".."
if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
((virtualName[0] == '.') && (virtualName[1] == '.') &&
(virtualName[2] == '\0')))
continue;
// Remove dotfiles (should be made optional?)
if (virtualName[0] == '.')
continue;
FileInfo info;
info.name = virtualName;
info.fullName = std::string(directory) + "/" + virtualName;
info.isDirectory = isDirectory(info.fullName);
if (!info.isDirectory) {
std::string ext = getFileExtension(info.fullName);
if (filter) {
if (filters.find(ext) == filters.end())
continue;
}
}
files->push_back(info);
#ifdef _WIN32
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
#else
}
closedir(dirp);
#endif
std::sort(files->begin(), files->end());
return foundEntries;
}
void deleteFile(const char *file)
{
#ifdef _WIN32
if (!DeleteFile(file)) {
ELOG("Error deleting %s: %i", file, GetLastError());
}
#else
int err = unlink(file);
if (err) {
ELOG("Error unlinking %s: %i", file, err);
}
#endif
}
#endif
std::string getDir(const std::string &path)
{
if (path == "/")
return path;
int n = path.size() - 1;
while (n >= 0 && path[n] != '\\' && path[n] != '/')
n--;
std::string cutpath = path.substr(0, n);
for (size_t i = 0; i < cutpath.size(); i++)
{
if (cutpath[i] == '\\') cutpath[i] = '/';
}
#ifndef _WIN32
if (!cutpath.size()) {
return "/";
}
#endif
return cutpath;
}
<commit_msg>MacOSX build fix<commit_after>#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
#include <cstring>
#include <string>
#include <set>
#include <algorithm>
#include <stdio.h>
#include <sys/stat.h>
#include <ctype.h>
#include "base/logging.h"
#include "base/basictypes.h"
#include "file/file_util.h"
#if defined(__FreeBSD__) || defined(__APPLE__)
#define stat64 stat
#endif
bool writeStringToFile(bool text_file, const std::string &str, const char *filename)
{
FILE *f = fopen(filename, text_file ? "w" : "wb");
if (!f)
return false;
size_t len = str.size();
if (len != fwrite(str.data(), 1, str.size(), f))
{
fclose(f);
return false;
}
fclose(f);
return true;
}
uint64_t GetSize(FILE *f)
{
// can't use off_t here because it can be 32-bit
uint64_t pos = ftell(f);
if (fseek(f, 0, SEEK_END) != 0) {
return 0;
}
uint64_t size = ftell(f);
// Reset the seek position to where it was when we started.
if ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) {
// Should error here
return 0;
}
return size;
}
bool ReadFileToString(bool text_file, const char *filename, std::string &str)
{
FILE *f = fopen(filename, text_file ? "r" : "rb");
if (!f)
return false;
size_t len = (size_t)GetSize(f);
char *buf = new char[len + 1];
buf[fread(buf, 1, len, f)] = 0;
str = std::string(buf, len);
fclose(f);
delete [] buf;
return true;
}
#define DIR_SEP "/"
#define DIR_SEP_CHR '\\'
#ifndef METRO
// Remove any ending forward slashes from directory paths
// Modifies argument.
static void stripTailDirSlashes(std::string &fname)
{
if (fname.length() > 1)
{
size_t i = fname.length() - 1;
while (fname[i] == DIR_SEP_CHR)
fname[i--] = '\0';
}
return;
}
// Returns true if file filename exists
bool exists(const std::string &filename)
{
#ifdef _WIN32
return GetFileAttributes(filename.c_str()) != 0xFFFFFFFF;
#else
struct stat64 file_info;
std::string copy(filename);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
return (result == 0);
#endif
}
// Returns true if filename is a directory
bool isDirectory(const std::string &filename)
{
#ifdef _WIN32
return (GetFileAttributes(filename.c_str()) & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
struct stat64 file_info;
std::string copy(filename);
stripTailDirSlashes(copy);
int result = stat64(copy.c_str(), &file_info);
if (result < 0) {
WLOG("IsDirectory: stat failed on %s", filename.c_str());
return false;
}
return S_ISDIR(file_info.st_mode);
#endif
}
std::string getFileExtension(const std::string &fn) {
int pos = fn.rfind(".");
if (pos < 0) return "";
std::string ext = fn.substr(pos+1);
for (size_t i = 0; i < ext.size(); i++) {
ext[i] = tolower(ext[i]);
}
return ext;
}
size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) {
size_t foundEntries = 0;
std::set<std::string> filters;
std::string tmp;
if (filter) {
while (*filter) {
if (*filter == ':') {
filters.insert(tmp);
tmp = "";
} else {
tmp.push_back(*filter);
}
filter++;
}
}
#ifdef _WIN32
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
#ifdef UNICODE
HANDLE hFind = FindFirstFile((std::wstring(directory) + "\\*").c_str(), &ffd);
#else
HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd);
#endif
if (hFind == INVALID_HANDLE_VALUE) {
FindClose(hFind);
return 0;
}
// windows loop
do
{
const std::string virtualName(ffd.cFileName);
#else
struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; };
struct dirent_large diren;
struct dirent *result = NULL;
DIR *dirp = opendir(directory);
if (!dirp)
return 0;
// non windows loop
while (!readdir_r(dirp, (dirent*) &diren, &result) && result)
{
const std::string virtualName(result->d_name);
#endif
// check for "." and ".."
if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
((virtualName[0] == '.') && (virtualName[1] == '.') &&
(virtualName[2] == '\0')))
continue;
// Remove dotfiles (should be made optional?)
if (virtualName[0] == '.')
continue;
FileInfo info;
info.name = virtualName;
info.fullName = std::string(directory) + "/" + virtualName;
info.isDirectory = isDirectory(info.fullName);
if (!info.isDirectory) {
std::string ext = getFileExtension(info.fullName);
if (filter) {
if (filters.find(ext) == filters.end())
continue;
}
}
files->push_back(info);
#ifdef _WIN32
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
#else
}
closedir(dirp);
#endif
std::sort(files->begin(), files->end());
return foundEntries;
}
void deleteFile(const char *file)
{
#ifdef _WIN32
if (!DeleteFile(file)) {
ELOG("Error deleting %s: %i", file, GetLastError());
}
#else
int err = unlink(file);
if (err) {
ELOG("Error unlinking %s: %i", file, err);
}
#endif
}
#endif
std::string getDir(const std::string &path)
{
if (path == "/")
return path;
int n = path.size() - 1;
while (n >= 0 && path[n] != '\\' && path[n] != '/')
n--;
std::string cutpath = path.substr(0, n);
for (size_t i = 0; i < cutpath.size(); i++)
{
if (cutpath[i] == '\\') cutpath[i] = '/';
}
#ifndef _WIN32
if (!cutpath.size()) {
return "/";
}
#endif
return cutpath;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <mailto:[email protected]>
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "credentialsaccessmanager.h"
#include "signond-common.h"
#include <QFile>
#include <QBuffer>
#define RETURN_IF_NOT_INITIALIZED(return_value) \
do { \
if (!m_isInitialized) { \
m_error = NotInitialized; \
TRACE() << "CredentialsAccessManager not initialized."; \
return return_value; \
} \
} while (0)
using namespace SignonDaemonNS;
/* ---------------------- CAMConfiguration ---------------------- */
CAMConfiguration::CAMConfiguration()
: m_dbName(QLatin1String(signonDefaultDbName)),
m_useEncryption(signonDefaultUseEncryption),
m_dbFileSystemPath(
QLatin1String(signonDefaultStoragePath)
+ QDir::separator()
+ QLatin1String(signonDefaultFileSystemName)),
m_fileSystemType(QLatin1String(signonDefaultFileSystemType)),
m_fileSystemSize(signonMinumumDbSize),
m_encryptionPassphrase(QByteArray())
{}
void CAMConfiguration::serialize(QIODevice *device)
{
if (device == NULL)
return;
if (!device->open(QIODevice::ReadWrite)) {
return;
}
QString buffer;
QTextStream stream(&buffer);
stream << "\n\n====== Credentials Access Manager Configuration ======\n\n";
stream << "File system mount name " << m_dbFileSystemPath << '\n';
stream << "File system format: " << m_fileSystemType << '\n';
stream << "File system size:" << m_fileSystemSize << "megabytes\n";
const char *usingEncryption = m_useEncryption ? "true" : "false";
stream << "Using encryption: " << usingEncryption << '\n';
stream << "Credentials database name: " << m_dbName << '\n';
stream << "======================================================\n\n";
device->write(buffer.toUtf8());
device->close();
}
/* ---------------------- CredentialsAccessManager ---------------------- */
CredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;
CredentialsAccessManager::CredentialsAccessManager(QObject *parent)
: QObject(parent),
m_isInitialized(false),
m_accessCodeFetched(false),
m_systemOpened(false),
m_error(NoError),
keyManagers(),
m_pCredentialsDB(NULL),
m_pCryptoFileSystemManager(NULL),
m_CAMConfiguration(CAMConfiguration())
{
}
CredentialsAccessManager::~CredentialsAccessManager()
{
closeCredentialsSystem();
m_pInstance = NULL;
}
CredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)
{
if (!m_pInstance)
m_pInstance = new CredentialsAccessManager(parent);
return m_pInstance;
}
void CredentialsAccessManager::finalize()
{
if (m_systemOpened)
closeCredentialsSystem();
if (m_pCryptoFileSystemManager)
delete m_pCryptoFileSystemManager;
m_accessCodeFetched = false;
m_isInitialized = false;
m_error = NoError;
}
bool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)
{
if (m_isInitialized) {
TRACE() << "CAM already initialized.";
m_error = AlreadyInitialized;
return false;
}
m_CAMConfiguration = camConfiguration;
QBuffer config;
m_CAMConfiguration.serialize(&config);
TRACE() << "\n\nInitualizing CredentialsAccessManager with configuration: " << config.data();
if (m_CAMConfiguration.m_useEncryption) {
//Initialize CryptoManager
m_pCryptoFileSystemManager = new CryptoManager(this);
m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);
m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);
m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);
// Initialize all key managers
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
connect(keyManager,
SIGNAL(keyInserted(const SignOn::Key)),
SLOT(onKeyInserted(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyDisabled(const SignOn::Key)),
SLOT(onKeyDisabled(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyRemoved(const SignOn::Key)),
SLOT(onKeyRemoved(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyAuthorized(const SignOn::Key, bool)),
SLOT(onKeyAuthorized(const SignOn::Key, bool)));
keyManager->setup();
}
}
m_isInitialized = true;
m_error = NoError;
TRACE() << "CredentialsAccessManager successfully initialized...";
return true;
}
void CredentialsAccessManager::addKeyManager(
SignOn::AbstractKeyManager *keyManager)
{
keyManagers.append(keyManager);
}
bool CredentialsAccessManager::openSecretsDB()
{
//todo remove this variable after LUKS implementation becomes stable.
QString dbPath;
if (m_CAMConfiguration.m_useEncryption) {
dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
if (!fileSystemDeployed()) {
if (!deployCredentialsSystem())
return false;
}
if (!m_pCryptoFileSystemManager->fileSystemMounted()) {
if (!m_pCryptoFileSystemManager->mountFileSystem()) {
m_error = CredentialsDbMountFailed;
return false;
}
}
} else {
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path()))
BLAME() << "Could not create storage directory!!!";
}
dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName
+ QLatin1String(".creds");
}
TRACE() << "Database name: [" << dbPath << "]";
if (!m_pCredentialsDB->openSecretsDB(dbPath))
return false;
m_error = NoError;
return true;
}
bool CredentialsAccessManager::isSecretsDBOpen()
{
return m_pCredentialsDB->isSecretsDBOpen();
}
bool CredentialsAccessManager::closeSecretsDB()
{
m_pCredentialsDB->closeSecretsDB();
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->unmountFileSystem()) {
m_error = CredentialsDbUnmountFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::openMetaDataDB()
{
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path()))
BLAME() << "Could not create storage directory!!!";
}
QString dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
m_pCredentialsDB = new CredentialsDB(dbPath);
if (!m_pCredentialsDB->init()) {
m_error = CredentialsDbConnectionError;
return false;
}
return true;
}
void CredentialsAccessManager::closeMetaDataDB()
{
if (m_pCredentialsDB) {
delete m_pCredentialsDB;
m_pCredentialsDB = NULL;
}
}
bool CredentialsAccessManager::openCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!openMetaDataDB()) {
BLAME() << "Couldn't open metadata DB!";
return false;
}
if (!openSecretsDB()) {
BLAME() << "Failed to open secrets DB.";
/* Even if the secrets DB couldn't be opened, signond is still usable:
* that's why we return "true" anyways. */
}
m_systemOpened = true;
return true;
}
bool CredentialsAccessManager::closeCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!closeSecretsDB())
return false;
closeMetaDataDB();
m_error = NoError;
m_systemOpened = false;
return true;
}
bool CredentialsAccessManager::deleteCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (m_systemOpened && !closeCredentialsSystem()) {
/* The close operation failed: we cannot proceed */
return false;
}
m_error = NoError;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->deleteFileSystem())
m_error = CredentialsDbDeletionFailed;
} else {
QFile dbFile(m_CAMConfiguration.m_dbName);
if (dbFile.exists()) {
if (!dbFile.remove())
m_error = CredentialsDbDeletionFailed;
}
}
return m_error == NoError;
}
bool CredentialsAccessManager::setMasterEncryptionKey(const QByteArray &newKey,
const QByteArray &existingKey)
{
if (!m_CAMConfiguration.m_useEncryption)
return false;
/* Clear this for security reasons - SIM data must not be stored
using an deprecated master key
*/
m_CAMConfiguration.m_encryptionPassphrase.clear();
if (!encryptionKeyCanMountFS(existingKey)) {
BLAME() << "Existing lock code check failed.";
return false;
}
if (!m_pCryptoFileSystemManager->addEncryptionKey(
newKey, existingKey)) {
BLAME() << "Failed to add new device lock code.";
return false;
}
if (!m_pCryptoFileSystemManager->removeEncryptionKey(existingKey, newKey)) {
BLAME() << "Failed to remove old device lock code.";
return false;
}
return true;
}
bool CredentialsAccessManager::lockSecureStorage(const QByteArray &lockData)
{
// TODO - implement this, research how to.
Q_UNUSED(lockData)
return false;
}
CredentialsDB *CredentialsAccessManager::credentialsDB() const
{
RETURN_IF_NOT_INITIALIZED(NULL);
return m_pCredentialsDB;
}
bool CredentialsAccessManager::deployCredentialsSystem()
{
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->setupFileSystem()) {
m_error = CredentialsDbSetupFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::fileSystemDeployed()
{
return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());
}
bool CredentialsAccessManager::encryptionKeyCanMountFS(const QByteArray &key)
{
if (!fileSystemDeployed()) {
TRACE() << "Secure FS not deployed";
return false;
}
if (m_pCryptoFileSystemManager->encryptionKeyInUse(key)) {
TRACE() << "SIM data already in use.";
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
m_pCryptoFileSystemManager->setEncryptionKey(key);
if (!credentialsSystemOpened()) {
if (openSecretsDB()) {
TRACE() << "Credentials system opened.";
} else {
BLAME() << "Failed to open credentials system.";
}
} else {
TRACE() << "Credentials system already opened.";
}
}
return true;
} else {
return false;
}
}
void CredentialsAccessManager::onKeyInserted(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (key.isEmpty()) return;
/* The `key in use` check will attempt to mount using the new key if
the file system is not already mounted
*/
if (encryptionKeyCanMountFS(key)) {
TRACE() << "SIM data already in use.";
authorizedKeys << key;
return;
}
/* We got here because the inserted key is totally new to the CAM.
* Let's see if any key manager wants to authorize it: we call
* authorizeKey() on each of them, and continue processing the key when
* the keyAuthorized() signal comes.
*/
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->authorizeKey(key);
}
}
void CredentialsAccessManager::onKeyDisabled(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (authorizedKeys.removeAll(key) == 0) {
TRACE() << "Key was already disabled";
return;
}
if (authorizedKeys.isEmpty()) {
TRACE() << "All keys removed, closing secure storage.";
if (isSecretsDBOpen())
if (!closeSecretsDB())
BLAME() << "Error occurred while closing secure storage.";
TRACE() << "Querying for keys.";
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->queryKeys();
}
}
}
void CredentialsAccessManager::onKeyRemoved(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
// Make sure the key is disabled:
onKeyDisabled(key);
if (!encryptionKeyCanMountFS(key)) {
TRACE() << "Key is not known to the CryptoManager.";
return;
}
if (authorizedKeys.isEmpty()) {
BLAME() << "Cannot remove key: no authorized keys";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (!m_pCryptoFileSystemManager->removeEncryptionKey(key, authorizedKey)) {
BLAME() << "Failed to remove key.";
} else {
TRACE() << "Key successfully removed.";
}
}
void CredentialsAccessManager::onKeyAuthorized(const SignOn::Key key,
bool authorized)
{
TRACE() << "Key:" << key.toHex() << "Authorized:" << authorized;
if (!authorized) return;
if (encryptionKeyCanMountFS(key)) {
TRACE() << "Encryption key already in use.";
authorizedKeys << key;
return;
}
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
/* if the secure FS is already mounted, add the new key to it */
if (authorizedKeys.isEmpty()) {
BLAME() << "No authorized keys: cannot add new key";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (m_pCryptoFileSystemManager->addEncryptionKey(key, authorizedKey)) {
TRACE() << "Encryption key successfullyadded into the CryptoManager.";
m_pCryptoFileSystemManager->setEncryptionKey(key);
authorizedKeys << key;
} else {
BLAME() << "Could not store encryption key.";
}
} else if (!fileSystemDeployed()) {
/* if the secure FS does not exist, create it and use this new key to
* initialize it */
m_pCryptoFileSystemManager->setEncryptionKey(key);
m_accessCodeFetched = true;
if (openSecretsDB()) {
authorizedKeys << key;
} else {
BLAME() << "Couldn't create the secure FS";
}
} else {
BLAME() << "Secure FS already created with another set of keys";
}
}
<commit_msg>Fix reopening of the secrets DB<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <mailto:[email protected]>
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "credentialsaccessmanager.h"
#include "signond-common.h"
#include <QFile>
#include <QBuffer>
#define RETURN_IF_NOT_INITIALIZED(return_value) \
do { \
if (!m_isInitialized) { \
m_error = NotInitialized; \
TRACE() << "CredentialsAccessManager not initialized."; \
return return_value; \
} \
} while (0)
using namespace SignonDaemonNS;
/* ---------------------- CAMConfiguration ---------------------- */
CAMConfiguration::CAMConfiguration()
: m_dbName(QLatin1String(signonDefaultDbName)),
m_useEncryption(signonDefaultUseEncryption),
m_dbFileSystemPath(
QLatin1String(signonDefaultStoragePath)
+ QDir::separator()
+ QLatin1String(signonDefaultFileSystemName)),
m_fileSystemType(QLatin1String(signonDefaultFileSystemType)),
m_fileSystemSize(signonMinumumDbSize),
m_encryptionPassphrase(QByteArray())
{}
void CAMConfiguration::serialize(QIODevice *device)
{
if (device == NULL)
return;
if (!device->open(QIODevice::ReadWrite)) {
return;
}
QString buffer;
QTextStream stream(&buffer);
stream << "\n\n====== Credentials Access Manager Configuration ======\n\n";
stream << "File system mount name " << m_dbFileSystemPath << '\n';
stream << "File system format: " << m_fileSystemType << '\n';
stream << "File system size:" << m_fileSystemSize << "megabytes\n";
const char *usingEncryption = m_useEncryption ? "true" : "false";
stream << "Using encryption: " << usingEncryption << '\n';
stream << "Credentials database name: " << m_dbName << '\n';
stream << "======================================================\n\n";
device->write(buffer.toUtf8());
device->close();
}
/* ---------------------- CredentialsAccessManager ---------------------- */
CredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;
CredentialsAccessManager::CredentialsAccessManager(QObject *parent)
: QObject(parent),
m_isInitialized(false),
m_accessCodeFetched(false),
m_systemOpened(false),
m_error(NoError),
keyManagers(),
m_pCredentialsDB(NULL),
m_pCryptoFileSystemManager(NULL),
m_CAMConfiguration(CAMConfiguration())
{
}
CredentialsAccessManager::~CredentialsAccessManager()
{
closeCredentialsSystem();
m_pInstance = NULL;
}
CredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)
{
if (!m_pInstance)
m_pInstance = new CredentialsAccessManager(parent);
return m_pInstance;
}
void CredentialsAccessManager::finalize()
{
if (m_systemOpened)
closeCredentialsSystem();
if (m_pCryptoFileSystemManager)
delete m_pCryptoFileSystemManager;
m_accessCodeFetched = false;
m_isInitialized = false;
m_error = NoError;
}
bool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)
{
if (m_isInitialized) {
TRACE() << "CAM already initialized.";
m_error = AlreadyInitialized;
return false;
}
m_CAMConfiguration = camConfiguration;
QBuffer config;
m_CAMConfiguration.serialize(&config);
TRACE() << "\n\nInitualizing CredentialsAccessManager with configuration: " << config.data();
if (m_CAMConfiguration.m_useEncryption) {
//Initialize CryptoManager
m_pCryptoFileSystemManager = new CryptoManager(this);
m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);
m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);
m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);
// Initialize all key managers
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
connect(keyManager,
SIGNAL(keyInserted(const SignOn::Key)),
SLOT(onKeyInserted(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyDisabled(const SignOn::Key)),
SLOT(onKeyDisabled(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyRemoved(const SignOn::Key)),
SLOT(onKeyRemoved(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyAuthorized(const SignOn::Key, bool)),
SLOT(onKeyAuthorized(const SignOn::Key, bool)));
keyManager->setup();
}
}
m_isInitialized = true;
m_error = NoError;
TRACE() << "CredentialsAccessManager successfully initialized...";
return true;
}
void CredentialsAccessManager::addKeyManager(
SignOn::AbstractKeyManager *keyManager)
{
keyManagers.append(keyManager);
}
bool CredentialsAccessManager::openSecretsDB()
{
//todo remove this variable after LUKS implementation becomes stable.
QString dbPath;
if (m_CAMConfiguration.m_useEncryption) {
dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
if (!fileSystemDeployed()) {
if (!deployCredentialsSystem())
return false;
}
if (!m_pCryptoFileSystemManager->fileSystemMounted()) {
if (!m_pCryptoFileSystemManager->mountFileSystem()) {
m_error = CredentialsDbMountFailed;
return false;
}
}
} else {
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path()))
BLAME() << "Could not create storage directory!!!";
}
dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName
+ QLatin1String(".creds");
}
TRACE() << "Database name: [" << dbPath << "]";
if (!m_pCredentialsDB->openSecretsDB(dbPath))
return false;
m_error = NoError;
return true;
}
bool CredentialsAccessManager::isSecretsDBOpen()
{
return m_pCredentialsDB->isSecretsDBOpen();
}
bool CredentialsAccessManager::closeSecretsDB()
{
m_pCredentialsDB->closeSecretsDB();
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->unmountFileSystem()) {
m_error = CredentialsDbUnmountFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::openMetaDataDB()
{
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path()))
BLAME() << "Could not create storage directory!!!";
}
QString dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
m_pCredentialsDB = new CredentialsDB(dbPath);
if (!m_pCredentialsDB->init()) {
m_error = CredentialsDbConnectionError;
return false;
}
return true;
}
void CredentialsAccessManager::closeMetaDataDB()
{
if (m_pCredentialsDB) {
delete m_pCredentialsDB;
m_pCredentialsDB = NULL;
}
}
bool CredentialsAccessManager::openCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!openMetaDataDB()) {
BLAME() << "Couldn't open metadata DB!";
return false;
}
if (!openSecretsDB()) {
BLAME() << "Failed to open secrets DB.";
/* Even if the secrets DB couldn't be opened, signond is still usable:
* that's why we return "true" anyways. */
}
m_systemOpened = true;
return true;
}
bool CredentialsAccessManager::closeCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!closeSecretsDB())
return false;
closeMetaDataDB();
m_error = NoError;
m_systemOpened = false;
return true;
}
bool CredentialsAccessManager::deleteCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (m_systemOpened && !closeCredentialsSystem()) {
/* The close operation failed: we cannot proceed */
return false;
}
m_error = NoError;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->deleteFileSystem())
m_error = CredentialsDbDeletionFailed;
} else {
QFile dbFile(m_CAMConfiguration.m_dbName);
if (dbFile.exists()) {
if (!dbFile.remove())
m_error = CredentialsDbDeletionFailed;
}
}
return m_error == NoError;
}
bool CredentialsAccessManager::setMasterEncryptionKey(const QByteArray &newKey,
const QByteArray &existingKey)
{
if (!m_CAMConfiguration.m_useEncryption)
return false;
/* Clear this for security reasons - SIM data must not be stored
using an deprecated master key
*/
m_CAMConfiguration.m_encryptionPassphrase.clear();
if (!encryptionKeyCanMountFS(existingKey)) {
BLAME() << "Existing lock code check failed.";
return false;
}
if (!m_pCryptoFileSystemManager->addEncryptionKey(
newKey, existingKey)) {
BLAME() << "Failed to add new device lock code.";
return false;
}
if (!m_pCryptoFileSystemManager->removeEncryptionKey(existingKey, newKey)) {
BLAME() << "Failed to remove old device lock code.";
return false;
}
return true;
}
bool CredentialsAccessManager::lockSecureStorage(const QByteArray &lockData)
{
// TODO - implement this, research how to.
Q_UNUSED(lockData)
return false;
}
CredentialsDB *CredentialsAccessManager::credentialsDB() const
{
RETURN_IF_NOT_INITIALIZED(NULL);
return m_pCredentialsDB;
}
bool CredentialsAccessManager::deployCredentialsSystem()
{
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->setupFileSystem()) {
m_error = CredentialsDbSetupFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::fileSystemDeployed()
{
return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());
}
bool CredentialsAccessManager::encryptionKeyCanMountFS(const QByteArray &key)
{
if (!fileSystemDeployed()) {
TRACE() << "Secure FS not deployed";
return false;
}
if (m_pCryptoFileSystemManager->encryptionKeyInUse(key)) {
TRACE() << "SIM data already in use.";
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
m_pCryptoFileSystemManager->setEncryptionKey(key);
if (!isSecretsDBOpen()) {
if (openSecretsDB()) {
TRACE() << "Credentials system opened.";
} else {
BLAME() << "Failed to open credentials system.";
}
} else {
TRACE() << "Credentials system already opened.";
}
}
return true;
} else {
return false;
}
}
void CredentialsAccessManager::onKeyInserted(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (key.isEmpty()) return;
/* The `key in use` check will attempt to mount using the new key if
the file system is not already mounted
*/
if (encryptionKeyCanMountFS(key)) {
TRACE() << "SIM data already in use.";
authorizedKeys << key;
return;
}
/* We got here because the inserted key is totally new to the CAM.
* Let's see if any key manager wants to authorize it: we call
* authorizeKey() on each of them, and continue processing the key when
* the keyAuthorized() signal comes.
*/
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->authorizeKey(key);
}
}
void CredentialsAccessManager::onKeyDisabled(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (authorizedKeys.removeAll(key) == 0) {
TRACE() << "Key was already disabled";
return;
}
if (authorizedKeys.isEmpty()) {
TRACE() << "All keys removed, closing secure storage.";
if (isSecretsDBOpen())
if (!closeSecretsDB())
BLAME() << "Error occurred while closing secure storage.";
TRACE() << "Querying for keys.";
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->queryKeys();
}
}
}
void CredentialsAccessManager::onKeyRemoved(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
// Make sure the key is disabled:
onKeyDisabled(key);
if (!encryptionKeyCanMountFS(key)) {
TRACE() << "Key is not known to the CryptoManager.";
return;
}
if (authorizedKeys.isEmpty()) {
BLAME() << "Cannot remove key: no authorized keys";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (!m_pCryptoFileSystemManager->removeEncryptionKey(key, authorizedKey)) {
BLAME() << "Failed to remove key.";
} else {
TRACE() << "Key successfully removed.";
}
}
void CredentialsAccessManager::onKeyAuthorized(const SignOn::Key key,
bool authorized)
{
TRACE() << "Key:" << key.toHex() << "Authorized:" << authorized;
if (!authorized) return;
if (encryptionKeyCanMountFS(key)) {
TRACE() << "Encryption key already in use.";
authorizedKeys << key;
return;
}
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
/* if the secure FS is already mounted, add the new key to it */
if (authorizedKeys.isEmpty()) {
BLAME() << "No authorized keys: cannot add new key";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (m_pCryptoFileSystemManager->addEncryptionKey(key, authorizedKey)) {
TRACE() << "Encryption key successfullyadded into the CryptoManager.";
m_pCryptoFileSystemManager->setEncryptionKey(key);
authorizedKeys << key;
} else {
BLAME() << "Could not store encryption key.";
}
} else if (!fileSystemDeployed()) {
/* if the secure FS does not exist, create it and use this new key to
* initialize it */
m_pCryptoFileSystemManager->setEncryptionKey(key);
m_accessCodeFetched = true;
if (openSecretsDB()) {
authorizedKeys << key;
} else {
BLAME() << "Couldn't create the secure FS";
}
} else {
BLAME() << "Secure FS already created with another set of keys";
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <mailto:[email protected]>
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "credentialsaccessmanager.h"
#include "signond-common.h"
#include <QFile>
#include <QBuffer>
#define RETURN_IF_NOT_INITIALIZED(return_value) \
do { \
if (!m_isInitialized) { \
m_error = NotInitialized; \
TRACE() << "CredentialsAccessManager not initialized."; \
return return_value; \
} \
} while (0)
using namespace SignonDaemonNS;
/* ---------------------- CAMConfiguration ---------------------- */
CAMConfiguration::CAMConfiguration()
: m_dbName(QLatin1String(signonDefaultDbName)),
m_useEncryption(signonDefaultUseEncryption),
m_dbFileSystemPath(
QLatin1String(signonDefaultStoragePath)
+ QDir::separator()
+ QLatin1String(signonDefaultFileSystemName)),
m_fileSystemType(QLatin1String(signonDefaultFileSystemType)),
m_fileSystemSize(signonMinumumDbSize),
m_encryptionPassphrase(QByteArray())
{}
void CAMConfiguration::serialize(QIODevice *device)
{
if (device == NULL)
return;
if (!device->open(QIODevice::ReadWrite)) {
return;
}
QString buffer;
QTextStream stream(&buffer);
stream << "\n\n====== Credentials Access Manager Configuration ======\n\n";
stream << "File system mount name " << m_dbFileSystemPath << '\n';
stream << "File system format: " << m_fileSystemType << '\n';
stream << "File system size:" << m_fileSystemSize << "megabytes\n";
const char *usingEncryption = m_useEncryption ? "true" : "false";
stream << "Using encryption: " << usingEncryption << '\n';
stream << "Credentials database name: " << m_dbName << '\n';
stream << "======================================================\n\n";
device->write(buffer.toUtf8());
device->close();
}
/* ---------------------- CredentialsAccessManager ---------------------- */
CredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;
CredentialsAccessManager::CredentialsAccessManager(QObject *parent)
: QObject(parent),
m_isInitialized(false),
m_accessCodeFetched(false),
m_systemOpened(false),
m_error(NoError),
keyManagers(),
m_pCredentialsDB(NULL),
m_pCryptoFileSystemManager(NULL),
m_CAMConfiguration(CAMConfiguration())
{
}
CredentialsAccessManager::~CredentialsAccessManager()
{
closeCredentialsSystem();
m_pInstance = NULL;
}
CredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)
{
if (!m_pInstance)
m_pInstance = new CredentialsAccessManager(parent);
return m_pInstance;
}
void CredentialsAccessManager::finalize()
{
if (m_systemOpened)
closeCredentialsSystem();
if (m_pCryptoFileSystemManager)
delete m_pCryptoFileSystemManager;
m_accessCodeFetched = false;
m_isInitialized = false;
m_error = NoError;
}
bool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)
{
if (m_isInitialized) {
TRACE() << "CAM already initialized.";
m_error = AlreadyInitialized;
return false;
}
m_CAMConfiguration = camConfiguration;
QBuffer config;
m_CAMConfiguration.serialize(&config);
TRACE() << "\n\nInitualizing CredentialsAccessManager with configuration: " << config.data();
if (m_CAMConfiguration.m_useEncryption) {
//Initialize CryptoManager
m_pCryptoFileSystemManager = new CryptoManager(this);
m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);
m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);
m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);
// Initialize all key managers
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
connect(keyManager,
SIGNAL(keyInserted(const SignOn::Key)),
SLOT(onKeyInserted(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyDisabled(const SignOn::Key)),
SLOT(onKeyDisabled(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyRemoved(const SignOn::Key)),
SLOT(onKeyRemoved(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyAuthorized(const SignOn::Key, bool)),
SLOT(onKeyAuthorized(const SignOn::Key, bool)));
keyManager->setup();
}
}
m_isInitialized = true;
m_error = NoError;
TRACE() << "CredentialsAccessManager successfully initialized...";
return true;
}
void CredentialsAccessManager::addKeyManager(
SignOn::AbstractKeyManager *keyManager)
{
keyManagers.append(keyManager);
}
bool CredentialsAccessManager::openSecretsDB()
{
//todo remove this variable after LUKS implementation becomes stable.
QString dbPath;
if (m_CAMConfiguration.m_useEncryption) {
dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
if (!fileSystemDeployed()) {
if (!deployCredentialsSystem())
return false;
}
if (!m_pCryptoFileSystemManager->fileSystemMounted()) {
if (!m_pCryptoFileSystemManager->mountFileSystem()) {
m_error = CredentialsDbMountFailed;
return false;
}
}
} else {
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path()))
BLAME() << "Could not create storage directory!!!";
}
dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName
+ QLatin1String(".creds");
}
TRACE() << "Database name: [" << dbPath << "]";
if (!m_pCredentialsDB->openSecretsDB(dbPath))
return false;
m_error = NoError;
return true;
}
bool CredentialsAccessManager::isSecretsDBOpen()
{
return m_pCredentialsDB->isSecretsDBOpen();
}
bool CredentialsAccessManager::closeSecretsDB()
{
m_pCredentialsDB->closeSecretsDB();
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->unmountFileSystem()) {
m_error = CredentialsDbUnmountFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::openMetaDataDB()
{
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path())) {
BLAME() << "Could not create storage directory:" <<
storageDir.path();
m_error = CredentialsDbSetupFailed;
return false;
}
}
QString dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
m_pCredentialsDB = new CredentialsDB(dbPath);
if (!m_pCredentialsDB->init()) {
m_error = CredentialsDbConnectionError;
return false;
}
return true;
}
void CredentialsAccessManager::closeMetaDataDB()
{
if (m_pCredentialsDB) {
delete m_pCredentialsDB;
m_pCredentialsDB = NULL;
}
}
bool CredentialsAccessManager::openCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!openMetaDataDB()) {
BLAME() << "Couldn't open metadata DB!";
return false;
}
if (!openSecretsDB()) {
BLAME() << "Failed to open secrets DB.";
/* Even if the secrets DB couldn't be opened, signond is still usable:
* that's why we return "true" anyways. */
}
m_systemOpened = true;
return true;
}
bool CredentialsAccessManager::closeCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!closeSecretsDB())
return false;
closeMetaDataDB();
m_error = NoError;
m_systemOpened = false;
return true;
}
bool CredentialsAccessManager::deleteCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (m_systemOpened && !closeCredentialsSystem()) {
/* The close operation failed: we cannot proceed */
return false;
}
m_error = NoError;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->deleteFileSystem())
m_error = CredentialsDbDeletionFailed;
} else {
QFile dbFile(m_CAMConfiguration.m_dbName);
if (dbFile.exists()) {
if (!dbFile.remove())
m_error = CredentialsDbDeletionFailed;
}
}
return m_error == NoError;
}
bool CredentialsAccessManager::setMasterEncryptionKey(const QByteArray &newKey,
const QByteArray &existingKey)
{
if (!m_CAMConfiguration.m_useEncryption)
return false;
/* Clear this for security reasons - SIM data must not be stored
using an deprecated master key
*/
m_CAMConfiguration.m_encryptionPassphrase.clear();
if (!encryptionKeyCanMountFS(existingKey)) {
BLAME() << "Existing lock code check failed.";
return false;
}
if (!m_pCryptoFileSystemManager->addEncryptionKey(
newKey, existingKey)) {
BLAME() << "Failed to add new device lock code.";
return false;
}
if (!m_pCryptoFileSystemManager->removeEncryptionKey(existingKey, newKey)) {
BLAME() << "Failed to remove old device lock code.";
return false;
}
return true;
}
bool CredentialsAccessManager::lockSecureStorage(const QByteArray &lockData)
{
// TODO - implement this, research how to.
Q_UNUSED(lockData)
return false;
}
CredentialsDB *CredentialsAccessManager::credentialsDB() const
{
RETURN_IF_NOT_INITIALIZED(NULL);
return m_pCredentialsDB;
}
bool CredentialsAccessManager::deployCredentialsSystem()
{
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->setupFileSystem()) {
m_error = CredentialsDbSetupFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::fileSystemDeployed()
{
return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());
}
bool CredentialsAccessManager::encryptionKeyCanMountFS(const QByteArray &key)
{
if (!fileSystemDeployed()) {
TRACE() << "Secure FS not deployed";
return false;
}
if (m_pCryptoFileSystemManager->encryptionKeyInUse(key)) {
TRACE() << "SIM data already in use.";
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
m_pCryptoFileSystemManager->setEncryptionKey(key);
if (!isSecretsDBOpen()) {
if (openSecretsDB()) {
TRACE() << "Credentials system opened.";
} else {
BLAME() << "Failed to open credentials system.";
}
} else {
TRACE() << "Credentials system already opened.";
}
}
return true;
} else {
return false;
}
}
void CredentialsAccessManager::onKeyInserted(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (key.isEmpty()) return;
/* The `key in use` check will attempt to mount using the new key if
the file system is not already mounted
*/
if (encryptionKeyCanMountFS(key)) {
TRACE() << "SIM data already in use.";
authorizedKeys << key;
return;
}
/* We got here because the inserted key is totally new to the CAM.
* Let's see if any key manager wants to authorize it: we call
* authorizeKey() on each of them, and continue processing the key when
* the keyAuthorized() signal comes.
*/
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->authorizeKey(key);
}
}
void CredentialsAccessManager::onKeyDisabled(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (authorizedKeys.removeAll(key) == 0) {
TRACE() << "Key was already disabled";
return;
}
if (authorizedKeys.isEmpty()) {
TRACE() << "All keys removed, closing secure storage.";
if (isSecretsDBOpen())
if (!closeSecretsDB())
BLAME() << "Error occurred while closing secure storage.";
TRACE() << "Querying for keys.";
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->queryKeys();
}
}
}
void CredentialsAccessManager::onKeyRemoved(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
// Make sure the key is disabled:
onKeyDisabled(key);
if (!encryptionKeyCanMountFS(key)) {
TRACE() << "Key is not known to the CryptoManager.";
return;
}
if (authorizedKeys.isEmpty()) {
BLAME() << "Cannot remove key: no authorized keys";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (!m_pCryptoFileSystemManager->removeEncryptionKey(key, authorizedKey)) {
BLAME() << "Failed to remove key.";
} else {
TRACE() << "Key successfully removed.";
}
}
void CredentialsAccessManager::onKeyAuthorized(const SignOn::Key key,
bool authorized)
{
TRACE() << "Key:" << key.toHex() << "Authorized:" << authorized;
if (!authorized) return;
if (encryptionKeyCanMountFS(key)) {
TRACE() << "Encryption key already in use.";
authorizedKeys << key;
return;
}
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
/* if the secure FS is already mounted, add the new key to it */
if (authorizedKeys.isEmpty()) {
BLAME() << "No authorized keys: cannot add new key";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (m_pCryptoFileSystemManager->addEncryptionKey(key, authorizedKey)) {
TRACE() << "Encryption key successfullyadded into the CryptoManager.";
m_pCryptoFileSystemManager->setEncryptionKey(key);
authorizedKeys << key;
} else {
BLAME() << "Could not store encryption key.";
}
} else if (!fileSystemDeployed()) {
/* if the secure FS does not exist, create it and use this new key to
* initialize it */
m_pCryptoFileSystemManager->setEncryptionKey(key);
m_accessCodeFetched = true;
if (openSecretsDB()) {
authorizedKeys << key;
} else {
BLAME() << "Couldn't create the secure FS";
}
} else {
BLAME() << "Secure FS already created with another set of keys";
}
}
<commit_msg>Don't crash if credentials system is closed twice.<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <mailto:[email protected]>
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "credentialsaccessmanager.h"
#include "signond-common.h"
#include <QFile>
#include <QBuffer>
#define RETURN_IF_NOT_INITIALIZED(return_value) \
do { \
if (!m_isInitialized) { \
m_error = NotInitialized; \
TRACE() << "CredentialsAccessManager not initialized."; \
return return_value; \
} \
} while (0)
using namespace SignonDaemonNS;
/* ---------------------- CAMConfiguration ---------------------- */
CAMConfiguration::CAMConfiguration()
: m_dbName(QLatin1String(signonDefaultDbName)),
m_useEncryption(signonDefaultUseEncryption),
m_dbFileSystemPath(
QLatin1String(signonDefaultStoragePath)
+ QDir::separator()
+ QLatin1String(signonDefaultFileSystemName)),
m_fileSystemType(QLatin1String(signonDefaultFileSystemType)),
m_fileSystemSize(signonMinumumDbSize),
m_encryptionPassphrase(QByteArray())
{}
void CAMConfiguration::serialize(QIODevice *device)
{
if (device == NULL)
return;
if (!device->open(QIODevice::ReadWrite)) {
return;
}
QString buffer;
QTextStream stream(&buffer);
stream << "\n\n====== Credentials Access Manager Configuration ======\n\n";
stream << "File system mount name " << m_dbFileSystemPath << '\n';
stream << "File system format: " << m_fileSystemType << '\n';
stream << "File system size:" << m_fileSystemSize << "megabytes\n";
const char *usingEncryption = m_useEncryption ? "true" : "false";
stream << "Using encryption: " << usingEncryption << '\n';
stream << "Credentials database name: " << m_dbName << '\n';
stream << "======================================================\n\n";
device->write(buffer.toUtf8());
device->close();
}
/* ---------------------- CredentialsAccessManager ---------------------- */
CredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;
CredentialsAccessManager::CredentialsAccessManager(QObject *parent)
: QObject(parent),
m_isInitialized(false),
m_accessCodeFetched(false),
m_systemOpened(false),
m_error(NoError),
keyManagers(),
m_pCredentialsDB(NULL),
m_pCryptoFileSystemManager(NULL),
m_CAMConfiguration(CAMConfiguration())
{
}
CredentialsAccessManager::~CredentialsAccessManager()
{
closeCredentialsSystem();
m_pInstance = NULL;
}
CredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)
{
if (!m_pInstance)
m_pInstance = new CredentialsAccessManager(parent);
return m_pInstance;
}
void CredentialsAccessManager::finalize()
{
if (m_systemOpened)
closeCredentialsSystem();
if (m_pCryptoFileSystemManager)
delete m_pCryptoFileSystemManager;
m_accessCodeFetched = false;
m_isInitialized = false;
m_error = NoError;
}
bool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)
{
if (m_isInitialized) {
TRACE() << "CAM already initialized.";
m_error = AlreadyInitialized;
return false;
}
m_CAMConfiguration = camConfiguration;
QBuffer config;
m_CAMConfiguration.serialize(&config);
TRACE() << "\n\nInitualizing CredentialsAccessManager with configuration: " << config.data();
if (m_CAMConfiguration.m_useEncryption) {
//Initialize CryptoManager
m_pCryptoFileSystemManager = new CryptoManager(this);
m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);
m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);
m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);
// Initialize all key managers
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
connect(keyManager,
SIGNAL(keyInserted(const SignOn::Key)),
SLOT(onKeyInserted(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyDisabled(const SignOn::Key)),
SLOT(onKeyDisabled(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyRemoved(const SignOn::Key)),
SLOT(onKeyRemoved(const SignOn::Key)));
connect(keyManager,
SIGNAL(keyAuthorized(const SignOn::Key, bool)),
SLOT(onKeyAuthorized(const SignOn::Key, bool)));
keyManager->setup();
}
}
m_isInitialized = true;
m_error = NoError;
TRACE() << "CredentialsAccessManager successfully initialized...";
return true;
}
void CredentialsAccessManager::addKeyManager(
SignOn::AbstractKeyManager *keyManager)
{
keyManagers.append(keyManager);
}
bool CredentialsAccessManager::openSecretsDB()
{
//todo remove this variable after LUKS implementation becomes stable.
QString dbPath;
if (m_CAMConfiguration.m_useEncryption) {
dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
if (!fileSystemDeployed()) {
if (!deployCredentialsSystem())
return false;
}
if (!m_pCryptoFileSystemManager->fileSystemMounted()) {
if (!m_pCryptoFileSystemManager->mountFileSystem()) {
m_error = CredentialsDbMountFailed;
return false;
}
}
} else {
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path()))
BLAME() << "Could not create storage directory!!!";
}
dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName
+ QLatin1String(".creds");
}
TRACE() << "Database name: [" << dbPath << "]";
if (!m_pCredentialsDB->openSecretsDB(dbPath))
return false;
m_error = NoError;
return true;
}
bool CredentialsAccessManager::isSecretsDBOpen()
{
return m_pCredentialsDB->isSecretsDBOpen();
}
bool CredentialsAccessManager::closeSecretsDB()
{
m_pCredentialsDB->closeSecretsDB();
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->unmountFileSystem()) {
m_error = CredentialsDbUnmountFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::openMetaDataDB()
{
QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);
QDir storageDir = fInfo.dir();
if (!storageDir.exists()) {
if (!storageDir.mkpath(storageDir.path())) {
BLAME() << "Could not create storage directory:" <<
storageDir.path();
m_error = CredentialsDbSetupFailed;
return false;
}
}
QString dbPath = storageDir.path()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
m_pCredentialsDB = new CredentialsDB(dbPath);
if (!m_pCredentialsDB->init()) {
m_error = CredentialsDbConnectionError;
return false;
}
return true;
}
void CredentialsAccessManager::closeMetaDataDB()
{
if (m_pCredentialsDB) {
delete m_pCredentialsDB;
m_pCredentialsDB = NULL;
}
}
bool CredentialsAccessManager::openCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!openMetaDataDB()) {
BLAME() << "Couldn't open metadata DB!";
return false;
}
if (!openSecretsDB()) {
BLAME() << "Failed to open secrets DB.";
/* Even if the secrets DB couldn't be opened, signond is still usable:
* that's why we return "true" anyways. */
}
m_systemOpened = true;
return true;
}
bool CredentialsAccessManager::closeCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!credentialsSystemOpened())
return true;
if (!closeSecretsDB())
return false;
closeMetaDataDB();
m_error = NoError;
m_systemOpened = false;
return true;
}
bool CredentialsAccessManager::deleteCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (m_systemOpened && !closeCredentialsSystem()) {
/* The close operation failed: we cannot proceed */
return false;
}
m_error = NoError;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->deleteFileSystem())
m_error = CredentialsDbDeletionFailed;
} else {
QFile dbFile(m_CAMConfiguration.m_dbName);
if (dbFile.exists()) {
if (!dbFile.remove())
m_error = CredentialsDbDeletionFailed;
}
}
return m_error == NoError;
}
bool CredentialsAccessManager::setMasterEncryptionKey(const QByteArray &newKey,
const QByteArray &existingKey)
{
if (!m_CAMConfiguration.m_useEncryption)
return false;
/* Clear this for security reasons - SIM data must not be stored
using an deprecated master key
*/
m_CAMConfiguration.m_encryptionPassphrase.clear();
if (!encryptionKeyCanMountFS(existingKey)) {
BLAME() << "Existing lock code check failed.";
return false;
}
if (!m_pCryptoFileSystemManager->addEncryptionKey(
newKey, existingKey)) {
BLAME() << "Failed to add new device lock code.";
return false;
}
if (!m_pCryptoFileSystemManager->removeEncryptionKey(existingKey, newKey)) {
BLAME() << "Failed to remove old device lock code.";
return false;
}
return true;
}
bool CredentialsAccessManager::lockSecureStorage(const QByteArray &lockData)
{
// TODO - implement this, research how to.
Q_UNUSED(lockData)
return false;
}
CredentialsDB *CredentialsAccessManager::credentialsDB() const
{
RETURN_IF_NOT_INITIALIZED(NULL);
return m_pCredentialsDB;
}
bool CredentialsAccessManager::deployCredentialsSystem()
{
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->setupFileSystem()) {
m_error = CredentialsDbSetupFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::fileSystemDeployed()
{
return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());
}
bool CredentialsAccessManager::encryptionKeyCanMountFS(const QByteArray &key)
{
if (!fileSystemDeployed()) {
TRACE() << "Secure FS not deployed";
return false;
}
if (m_pCryptoFileSystemManager->encryptionKeyInUse(key)) {
TRACE() << "SIM data already in use.";
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
m_pCryptoFileSystemManager->setEncryptionKey(key);
if (!isSecretsDBOpen()) {
if (openSecretsDB()) {
TRACE() << "Credentials system opened.";
} else {
BLAME() << "Failed to open credentials system.";
}
} else {
TRACE() << "Credentials system already opened.";
}
}
return true;
} else {
return false;
}
}
void CredentialsAccessManager::onKeyInserted(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (key.isEmpty()) return;
/* The `key in use` check will attempt to mount using the new key if
the file system is not already mounted
*/
if (encryptionKeyCanMountFS(key)) {
TRACE() << "SIM data already in use.";
authorizedKeys << key;
return;
}
/* We got here because the inserted key is totally new to the CAM.
* Let's see if any key manager wants to authorize it: we call
* authorizeKey() on each of them, and continue processing the key when
* the keyAuthorized() signal comes.
*/
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->authorizeKey(key);
}
}
void CredentialsAccessManager::onKeyDisabled(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
if (authorizedKeys.removeAll(key) == 0) {
TRACE() << "Key was already disabled";
return;
}
if (authorizedKeys.isEmpty()) {
TRACE() << "All keys removed, closing secure storage.";
if (isSecretsDBOpen())
if (!closeSecretsDB())
BLAME() << "Error occurred while closing secure storage.";
TRACE() << "Querying for keys.";
foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {
keyManager->queryKeys();
}
}
}
void CredentialsAccessManager::onKeyRemoved(const SignOn::Key key)
{
TRACE() << "Key:" << key.toHex();
// Make sure the key is disabled:
onKeyDisabled(key);
if (!encryptionKeyCanMountFS(key)) {
TRACE() << "Key is not known to the CryptoManager.";
return;
}
if (authorizedKeys.isEmpty()) {
BLAME() << "Cannot remove key: no authorized keys";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (!m_pCryptoFileSystemManager->removeEncryptionKey(key, authorizedKey)) {
BLAME() << "Failed to remove key.";
} else {
TRACE() << "Key successfully removed.";
}
}
void CredentialsAccessManager::onKeyAuthorized(const SignOn::Key key,
bool authorized)
{
TRACE() << "Key:" << key.toHex() << "Authorized:" << authorized;
if (!authorized) return;
if (encryptionKeyCanMountFS(key)) {
TRACE() << "Encryption key already in use.";
authorizedKeys << key;
return;
}
if (m_pCryptoFileSystemManager->fileSystemMounted()) {
/* if the secure FS is already mounted, add the new key to it */
if (authorizedKeys.isEmpty()) {
BLAME() << "No authorized keys: cannot add new key";
return;
}
SignOn::Key authorizedKey = authorizedKeys.first();
if (m_pCryptoFileSystemManager->addEncryptionKey(key, authorizedKey)) {
TRACE() << "Encryption key successfullyadded into the CryptoManager.";
m_pCryptoFileSystemManager->setEncryptionKey(key);
authorizedKeys << key;
} else {
BLAME() << "Could not store encryption key.";
}
} else if (!fileSystemDeployed()) {
/* if the secure FS does not exist, create it and use this new key to
* initialize it */
m_pCryptoFileSystemManager->setEncryptionKey(key);
m_accessCodeFetched = true;
if (openSecretsDB()) {
authorizedKeys << key;
} else {
BLAME() << "Couldn't create the secure FS";
}
} else {
BLAME() << "Secure FS already created with another set of keys";
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <mailto:[email protected]>
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "credentialsaccessmanager.h"
#include "accesscodehandler.h"
#include "signond-common.h"
#include <QThreadPool>
#include <QCoreApplication>
#include <QFile>
#include <QBuffer>
#define RETURN_IF_NOT_INITIALIZED(return_value) \
do { \
if (!m_isInitialized) { \
m_error = NotInitialized; \
TRACE() << "CredentialsAccessManager not initialized."; \
return return_value; \
} \
} while (0)
using namespace SignonDaemonNS;
/* ---------------------- CAMConfiguration ---------------------- */
CAMConfiguration::CAMConfiguration()
: m_dbName(QLatin1String("signon.db")),
m_useEncryption(true),
m_dbFileSystemPath(QLatin1String("/home/user/signonfs")),
m_fileSystemType(QLatin1String("ext3")),
m_fileSystemSize(4)
{}
void CAMConfiguration::serialize(QIODevice *device)
{
if (device == NULL)
return;
if (!device->open(QIODevice::ReadWrite)) {
return;
}
QString buffer;
QTextStream stream(&buffer);
stream << "\n\n====== Credentials Access Manager Configuration ======\n\n";
stream << "File system mount name " << m_dbFileSystemPath << '\n';
stream << "File system format: " << m_fileSystemType << '\n';
stream << "File system size:" << m_fileSystemSize << "megabytes\n";
const char *usingEncryption = m_useEncryption ? "true" : "false";
stream << "Using encryption: " << usingEncryption << '\n';
stream << "Credentials database name: " << m_dbName << '\n';
stream << "======================================================\n\n";
device->write(buffer.toUtf8());
device->close();
}
/* ---------------------- CredentialsAccessManager ---------------------- */
CredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;
CredentialsAccessManager::CredentialsAccessManager(QObject *parent)
: QObject(parent),
m_isInitialized(false),
m_systemOpened(false),
m_error(NoError),
m_pCredentialsDB(NULL),
m_pCryptoFileSystemManager(NULL),
m_pAccessCodeHandler(NULL),
m_CAMConfiguration(CAMConfiguration())
{
}
CredentialsAccessManager::~CredentialsAccessManager()
{
closeCredentialsSystem();
m_pInstance = NULL;
}
CredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)
{
if (!m_pInstance)
m_pInstance = new CredentialsAccessManager(parent);
return m_pInstance;
}
bool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)
{
if (m_isInitialized) {
m_error = AlreadyInitialized;
return false;
}
m_CAMConfiguration = camConfiguration;
QBuffer config;
m_CAMConfiguration.serialize(&config);
TRACE() << "\n\nInitualizing CredentialsAccessManager with configuration: " << config.data();
if (m_CAMConfiguration.m_useEncryption) {
//TODO initialize the AccessCodeHandler here for the SIM data usage
m_pCryptoFileSystemManager = new CryptoManager(this);
m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);
m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);
m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);
}
m_isInitialized = true;
m_error = NoError;
TRACE() << "CredentialsAccessManager successfully initialized...";
return true;
}
bool CredentialsAccessManager::openCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
//todo remove this variable after LUKS implementation becomes stable.
QString dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
if (m_CAMConfiguration.m_useEncryption) {
if (!fileSystemDeployed()) {
if (deployCredentialsSystem()) {
if (openDB(dbPath))
m_systemOpened = true;
}
return m_systemOpened;
}
if (fileSystemLoaded()) {
m_error = CredentialsDbAlreadyDeployed;
return false;
}
if (!fetchAccessCode()) {
m_error = FailedToFetchAccessCode;
return false;
}
if (!m_pCryptoFileSystemManager->mountFileSystem()) {
m_error = CredentialsDbMountFailed;
return false;
}
} else {
/*
* TODO - change this so that openDB takes only the CAM configuration db name
* after the LUKS system is enabled; practically remove this 'else' branch
*/
dbPath = QDir::homePath() + QDir::separator() + m_CAMConfiguration.m_dbName;
}
TRACE() << "Database name: [" << dbPath << "]";
if (openDB(dbPath)) {
m_systemOpened = true;
m_error = NoError;
}
return m_systemOpened;
}
bool CredentialsAccessManager::closeCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!closeDB())
return false;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->unmountFileSystem()) {
m_error = CredentialsDbUnmountFailed;
return false;
}
}
m_error = NoError;
m_systemOpened = false;
return true;
}
bool CredentialsAccessManager::deleteCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (m_systemOpened && !closeCredentialsSystem()) {
/* The close operation failed: we cannot proceed */
return false;
}
m_error = NoError;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->deleteFileSystem())
m_error = CredentialsDbDeletionFailed;
} else {
QFile dbFile(m_CAMConfiguration.m_dbName);
if (dbFile.exists()) {
if (!dbFile.remove())
m_error = CredentialsDbDeletionFailed;
}
}
return m_error == NoError;
}
CredentialsDB *CredentialsAccessManager::credentialsDB() const
{
RETURN_IF_NOT_INITIALIZED(NULL);
return m_pCredentialsDB;
}
bool CredentialsAccessManager::deployCredentialsSystem()
{
if (m_CAMConfiguration.m_useEncryption) {
if (!fetchAccessCode()) {
m_error = FailedToFetchAccessCode;
return false;
}
if (!m_pCryptoFileSystemManager->setupFileSystem()) {
m_error = CredentialsDbSetupFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::fileSystemLoaded(bool checkForDatabase)
{
if (!m_pCryptoFileSystemManager->fileSystemMounted())
return false;
if (checkForDatabase
&& !m_pCryptoFileSystemManager->fileSystemContainsFile(m_CAMConfiguration.m_dbName))
return false;
return true;
}
bool CredentialsAccessManager::fileSystemDeployed()
{
return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());
}
bool CredentialsAccessManager::openDB(const QString &databaseName)
{
m_pCredentialsDB = new CredentialsDB(databaseName);
if (!m_pCredentialsDB->connect()) {
TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error(false));
m_error = CredentialsDbConnectionError;
return false;
}
TRACE() << "Database connection succeeded.";
if (!m_pCredentialsDB->hasTableStructure()) {
TRACE() << "Creating SQL table structure...";
if (!m_pCredentialsDB->createTableStructure()) {
TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error());
m_error = CredentialsDbSqlError;
return false;
}
} else {
TRACE() << "SQL table structure already created...";
}
TRACE() << m_pCredentialsDB->sqlDBConfiguration();
return true;
}
bool CredentialsAccessManager::closeDB()
{
if (m_pCredentialsDB) {
m_pCredentialsDB->disconnect();
delete m_pCredentialsDB;
m_pCredentialsDB = NULL;
}
return true;
}
bool CredentialsAccessManager::fetchAccessCode(uint timeout)
{
Q_UNUSED(timeout)
//TODO use device lock code here and remove hardcoded joke 'passphrase'
m_pCryptoFileSystemManager->setAccessCode("1234");
return true;
}
bool CredentialsAccessManager::addEncryptionKey(const QByteArray &key, const QByteArray &existingKey)
{
return m_pCryptoFileSystemManager->addEncryptionKey(key, existingKey);
}
bool CredentialsAccessManager::removeEncryptionKey(const QByteArray &key, const QByteArray &remainingKey)
{
return m_pCryptoFileSystemManager->removeEncryptionKey(key, remainingKey);
}
<commit_msg>Don't use the m_pCryptoFileSystemManager encryption is disabled<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <mailto:[email protected]>
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "credentialsaccessmanager.h"
#include "accesscodehandler.h"
#include "signond-common.h"
#include <QThreadPool>
#include <QCoreApplication>
#include <QFile>
#include <QBuffer>
#define RETURN_IF_NOT_INITIALIZED(return_value) \
do { \
if (!m_isInitialized) { \
m_error = NotInitialized; \
TRACE() << "CredentialsAccessManager not initialized."; \
return return_value; \
} \
} while (0)
using namespace SignonDaemonNS;
/* ---------------------- CAMConfiguration ---------------------- */
CAMConfiguration::CAMConfiguration()
: m_dbName(QLatin1String("signon.db")),
m_useEncryption(true),
m_dbFileSystemPath(QLatin1String("/home/user/signonfs")),
m_fileSystemType(QLatin1String("ext3")),
m_fileSystemSize(4)
{}
void CAMConfiguration::serialize(QIODevice *device)
{
if (device == NULL)
return;
if (!device->open(QIODevice::ReadWrite)) {
return;
}
QString buffer;
QTextStream stream(&buffer);
stream << "\n\n====== Credentials Access Manager Configuration ======\n\n";
stream << "File system mount name " << m_dbFileSystemPath << '\n';
stream << "File system format: " << m_fileSystemType << '\n';
stream << "File system size:" << m_fileSystemSize << "megabytes\n";
const char *usingEncryption = m_useEncryption ? "true" : "false";
stream << "Using encryption: " << usingEncryption << '\n';
stream << "Credentials database name: " << m_dbName << '\n';
stream << "======================================================\n\n";
device->write(buffer.toUtf8());
device->close();
}
/* ---------------------- CredentialsAccessManager ---------------------- */
CredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;
CredentialsAccessManager::CredentialsAccessManager(QObject *parent)
: QObject(parent),
m_isInitialized(false),
m_systemOpened(false),
m_error(NoError),
m_pCredentialsDB(NULL),
m_pCryptoFileSystemManager(NULL),
m_pAccessCodeHandler(NULL),
m_CAMConfiguration(CAMConfiguration())
{
}
CredentialsAccessManager::~CredentialsAccessManager()
{
closeCredentialsSystem();
m_pInstance = NULL;
}
CredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)
{
if (!m_pInstance)
m_pInstance = new CredentialsAccessManager(parent);
return m_pInstance;
}
bool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)
{
if (m_isInitialized) {
m_error = AlreadyInitialized;
return false;
}
m_CAMConfiguration = camConfiguration;
QBuffer config;
m_CAMConfiguration.serialize(&config);
TRACE() << "\n\nInitualizing CredentialsAccessManager with configuration: " << config.data();
if (m_CAMConfiguration.m_useEncryption) {
//TODO initialize the AccessCodeHandler here for the SIM data usage
m_pCryptoFileSystemManager = new CryptoManager(this);
m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);
m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);
m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);
}
m_isInitialized = true;
m_error = NoError;
TRACE() << "CredentialsAccessManager successfully initialized...";
return true;
}
bool CredentialsAccessManager::openCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
//todo remove this variable after LUKS implementation becomes stable.
QString dbPath;
if (m_CAMConfiguration.m_useEncryption) {
dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()
+ QDir::separator()
+ m_CAMConfiguration.m_dbName;
if (!fileSystemDeployed()) {
if (deployCredentialsSystem()) {
if (openDB(dbPath))
m_systemOpened = true;
}
return m_systemOpened;
}
if (fileSystemLoaded()) {
m_error = CredentialsDbAlreadyDeployed;
return false;
}
if (!fetchAccessCode()) {
m_error = FailedToFetchAccessCode;
return false;
}
if (!m_pCryptoFileSystemManager->mountFileSystem()) {
m_error = CredentialsDbMountFailed;
return false;
}
} else {
/*
* TODO - change this so that openDB takes only the CAM configuration db name
* after the LUKS system is enabled; practically remove this 'else' branch
*/
dbPath = QDir::homePath() + QDir::separator() + m_CAMConfiguration.m_dbName;
}
TRACE() << "Database name: [" << dbPath << "]";
if (openDB(dbPath)) {
m_systemOpened = true;
m_error = NoError;
}
return m_systemOpened;
}
bool CredentialsAccessManager::closeCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (!closeDB())
return false;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->unmountFileSystem()) {
m_error = CredentialsDbUnmountFailed;
return false;
}
}
m_error = NoError;
m_systemOpened = false;
return true;
}
bool CredentialsAccessManager::deleteCredentialsSystem()
{
RETURN_IF_NOT_INITIALIZED(false);
if (m_systemOpened && !closeCredentialsSystem()) {
/* The close operation failed: we cannot proceed */
return false;
}
m_error = NoError;
if (m_CAMConfiguration.m_useEncryption) {
if (!m_pCryptoFileSystemManager->deleteFileSystem())
m_error = CredentialsDbDeletionFailed;
} else {
QFile dbFile(m_CAMConfiguration.m_dbName);
if (dbFile.exists()) {
if (!dbFile.remove())
m_error = CredentialsDbDeletionFailed;
}
}
return m_error == NoError;
}
CredentialsDB *CredentialsAccessManager::credentialsDB() const
{
RETURN_IF_NOT_INITIALIZED(NULL);
return m_pCredentialsDB;
}
bool CredentialsAccessManager::deployCredentialsSystem()
{
if (m_CAMConfiguration.m_useEncryption) {
if (!fetchAccessCode()) {
m_error = FailedToFetchAccessCode;
return false;
}
if (!m_pCryptoFileSystemManager->setupFileSystem()) {
m_error = CredentialsDbSetupFailed;
return false;
}
}
return true;
}
bool CredentialsAccessManager::fileSystemLoaded(bool checkForDatabase)
{
if (!m_pCryptoFileSystemManager->fileSystemMounted())
return false;
if (checkForDatabase
&& !m_pCryptoFileSystemManager->fileSystemContainsFile(m_CAMConfiguration.m_dbName))
return false;
return true;
}
bool CredentialsAccessManager::fileSystemDeployed()
{
return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());
}
bool CredentialsAccessManager::openDB(const QString &databaseName)
{
m_pCredentialsDB = new CredentialsDB(databaseName);
if (!m_pCredentialsDB->connect()) {
TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error(false));
m_error = CredentialsDbConnectionError;
return false;
}
TRACE() << "Database connection succeeded.";
if (!m_pCredentialsDB->hasTableStructure()) {
TRACE() << "Creating SQL table structure...";
if (!m_pCredentialsDB->createTableStructure()) {
TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error());
m_error = CredentialsDbSqlError;
return false;
}
} else {
TRACE() << "SQL table structure already created...";
}
TRACE() << m_pCredentialsDB->sqlDBConfiguration();
return true;
}
bool CredentialsAccessManager::closeDB()
{
if (m_pCredentialsDB) {
m_pCredentialsDB->disconnect();
delete m_pCredentialsDB;
m_pCredentialsDB = NULL;
}
return true;
}
bool CredentialsAccessManager::fetchAccessCode(uint timeout)
{
Q_UNUSED(timeout)
//TODO use device lock code here and remove hardcoded joke 'passphrase'
m_pCryptoFileSystemManager->setAccessCode("1234");
return true;
}
bool CredentialsAccessManager::addEncryptionKey(const QByteArray &key, const QByteArray &existingKey)
{
return m_pCryptoFileSystemManager->addEncryptionKey(key, existingKey);
}
bool CredentialsAccessManager::removeEncryptionKey(const QByteArray &key, const QByteArray &remainingKey)
{
return m_pCryptoFileSystemManager->removeEncryptionKey(key, remainingKey);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestXMLDisplayOutputWindow.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.
=========================================================================*/
#include "vtkXMLFileOutputWindow.h"
#include "vtkSmartPointer.h"
#include <string>
int TestXMLFileOutputWindow(int argc,char *argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " outputFilename" << std::endl;
return EXIT_FAILURE;
}
std::string sample("Test string: &\"'<>");
{
vtkSmartPointer<vtkXMLFileOutputWindow> ofw =
vtkSmartPointer<vtkXMLFileOutputWindow>::New();
ofw->SetInstance(ofw);
ofw->FlushOn();
// Use the default filename
ofw->DisplayTag(sample.c_str());
ofw->DisplayText(sample.c_str());
ofw->DisplayErrorText(sample.c_str());
ofw->DisplayWarningText(sample.c_str());
ofw->DisplayGenericWarningText(sample.c_str());
ofw->DisplayDebugText(sample.c_str());
// Check NULL strings
ofw->DisplayTag(NULL);
ofw->DisplayText(NULL);
ofw->DisplayErrorText(NULL);
ofw->DisplayWarningText(NULL);
ofw->DisplayGenericWarningText(NULL);
ofw->DisplayDebugText(NULL);
}
// Append to default
{
vtkSmartPointer<vtkXMLFileOutputWindow> ofw2 =
vtkSmartPointer<vtkXMLFileOutputWindow>::New();
ofw2->SetInstance(ofw2);
ofw2->AppendOn();
ofw2->DisplayText("Appended");
}
// Change the file name
{
vtkSmartPointer<vtkXMLFileOutputWindow> ofw3 =
vtkSmartPointer<vtkXMLFileOutputWindow>::New();
ofw3->SetInstance(ofw3);
ofw3->SetFileName(argv[1]);
ofw3->DisplayTag(sample.c_str());
ofw3->DisplayText(sample.c_str());
ofw3->DisplayErrorText(sample.c_str());
ofw3->DisplayWarningText(sample.c_str());
ofw3->DisplayGenericWarningText(sample.c_str());
ofw3->DisplayDebugText(sample.c_str());
ofw3->AppendOn();
ofw3->DisplayText("Appended");
}
// Now, compare the default and specified files
// Read the default XML file
std::ifstream dfin("vtkMessageLog.xml", std::ios::in);
if (dfin.fail())
{
std::cout << argv[0] << ": Cannot open " << "vtkMessageLog.xml" << std::endl;
return EXIT_FAILURE;
}
// Get the length of the file
dfin.seekg (0, std::ios::end);
const size_t dlen = dfin.tellg();
dfin.seekg (0, std::ios::beg);
char * defXML = new char[dlen+1];
dfin.read (defXML, dlen);
defXML[dlen] = '\0';
// Read the specified XML file
std::ifstream sfin(argv[1], std::ios::in);
if (sfin.fail())
{
std::cout << argv[0] << ": Cannot open " << argv[1] << std::endl;
return EXIT_FAILURE;
}
// Get the length of the file
sfin.seekg (0, std::ios::end);
const size_t slen = dfin.tellg();
sfin.seekg (0, std::ios::beg);
char * specifiedXML = new char[slen+1];
sfin.read (specifiedXML, slen);
specifiedXML[slen] = '\0';
std::string def(defXML);
std::string specified(specifiedXML);
if (def != specified)
{
std::cout << "The string in the default file ***********" << std::endl
<< def << std::endl
<< "does not match the string in the specified file ***********" << std::endl
<< specified << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>BUG: Memory leak in TestXMLFileOutputWindow.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestXMLDisplayOutputWindow.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.
=========================================================================*/
#include "vtkXMLFileOutputWindow.h"
#include "vtkSmartPointer.h"
#include <string>
int TestXMLFileOutputWindow(int argc,char *argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " outputFilename" << std::endl;
return EXIT_FAILURE;
}
std::string sample("Test string: &\"'<>");
{
vtkSmartPointer<vtkXMLFileOutputWindow> ofw =
vtkSmartPointer<vtkXMLFileOutputWindow>::New();
ofw->SetInstance(ofw);
ofw->FlushOn();
// Use the default filename
ofw->DisplayTag(sample.c_str());
ofw->DisplayText(sample.c_str());
ofw->DisplayErrorText(sample.c_str());
ofw->DisplayWarningText(sample.c_str());
ofw->DisplayGenericWarningText(sample.c_str());
ofw->DisplayDebugText(sample.c_str());
// Check NULL strings
ofw->DisplayTag(NULL);
ofw->DisplayText(NULL);
ofw->DisplayErrorText(NULL);
ofw->DisplayWarningText(NULL);
ofw->DisplayGenericWarningText(NULL);
ofw->DisplayDebugText(NULL);
}
// Append to default
{
vtkSmartPointer<vtkXMLFileOutputWindow> ofw2 =
vtkSmartPointer<vtkXMLFileOutputWindow>::New();
ofw2->SetInstance(ofw2);
ofw2->AppendOn();
ofw2->DisplayText("Appended");
}
// Change the file name
{
vtkSmartPointer<vtkXMLFileOutputWindow> ofw3 =
vtkSmartPointer<vtkXMLFileOutputWindow>::New();
ofw3->SetInstance(ofw3);
ofw3->SetFileName(argv[1]);
ofw3->DisplayTag(sample.c_str());
ofw3->DisplayText(sample.c_str());
ofw3->DisplayErrorText(sample.c_str());
ofw3->DisplayWarningText(sample.c_str());
ofw3->DisplayGenericWarningText(sample.c_str());
ofw3->DisplayDebugText(sample.c_str());
ofw3->AppendOn();
ofw3->DisplayText("Appended");
}
// Now, compare the default and specified files
// Read the default XML file
std::ifstream dfin("vtkMessageLog.xml", std::ios::in);
if (dfin.fail())
{
std::cout << argv[0] << ": Cannot open " << "vtkMessageLog.xml" << std::endl;
return EXIT_FAILURE;
}
// Get the length of the file
dfin.seekg (0, std::ios::end);
const size_t dlen = dfin.tellg();
dfin.seekg (0, std::ios::beg);
char * defXML = new char[dlen+1];
dfin.read (defXML, dlen);
defXML[dlen] = '\0';
// Read the specified XML file
std::ifstream sfin(argv[1], std::ios::in);
if (sfin.fail())
{
std::cout << argv[0] << ": Cannot open " << argv[1] << std::endl;
return EXIT_FAILURE;
}
// Get the length of the file
sfin.seekg (0, std::ios::end);
const size_t slen = dfin.tellg();
sfin.seekg (0, std::ios::beg);
char * specifiedXML = new char[slen+1];
sfin.read (specifiedXML, slen);
specifiedXML[slen] = '\0';
std::string def(defXML);
delete [] defXML;
std::string specified(specifiedXML);
delete [] specifiedXML;
if (def != specified)
{
std::cout << "The string in the default file ***********" << std::endl
<< def << std::endl
<< "does not match the string in the specified file ***********" << std::endl
<< specified << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkLevelWindowManager.h"
#include <itkCommand.h>
#include "mitkDataStorage.h"
#include "mitkNodePredicateBase.h"
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateDataType.h"
#include "mitkNodePredicateAnd.h"
#include "mitkNodePredicateOr.h"
#include "mitkNodePredicateNot.h"
#include "mitkProperties.h"
#include "mitkMessage.h"
mitk::LevelWindowManager::LevelWindowManager()
: m_DataStorage(NULL)
, m_LevelWindowProperty(NULL)
, m_AutoTopMost(true)
, m_IsObserverTagSet(false)
, m_CurrentImage(NULL)
, m_IsPropertyModifiedTagSet(false)
{
}
mitk::LevelWindowManager::~LevelWindowManager()
{
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageChanged ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
m_DataStorage = NULL;
}
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
for( std::map<unsigned long, mitk::BaseProperty::Pointer>::iterator iter = m_PropObserverToNode.begin();
iter != m_PropObserverToNode.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first);
}
for( std::map<unsigned long, mitk::BaseProperty::Pointer>::iterator iter = m_PropObserverToNode2.begin();
iter != m_PropObserverToNode2.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first);
}
}
void mitk::LevelWindowManager::SetDataStorage( mitk::DataStorage* ds )
{
if (ds == NULL) return;
/* remove listeners of old DataStorage */
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageChanged ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
}
/* register listener for new DataStorage */
m_DataStorage = ds; // register
m_DataStorage->AddNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageChanged ));
m_DataStorage->RemoveNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
this->DataStorageChanged(); // update us with new DataStorage
}
void mitk::LevelWindowManager::OnPropertyModified(const itk::EventObject& )
{
Modified();
}
void mitk::LevelWindowManager::SetAutoTopMostImage(bool autoTopMost, const mitk::DataNode* removedNode)
{
m_AutoTopMost = autoTopMost;
if (m_AutoTopMost == false)
return;
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
/* search topmost image */
if (m_DataStorage.IsNull())
{
itkExceptionMacro("DataStorage not set");
}
int maxLayer = itk::NumericTraits<int>::min();
m_LevelWindowProperty = NULL;
mitk::DataNode::Pointer topLevelNode;
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin(); it != all->End(); ++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull() || (removedNode != NULL && node == removedNode))
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
int layer = 0;
node->GetIntProperty("layer", layer);
if ( layer < maxLayer )
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
topLevelNode = node;
maxLayer = layer;
}
if (topLevelNode.IsNotNull())
{
topLevelNode->SetBoolProperty( "imageForLevelWindow", true );
}
this->SetLevelWindowProperty( m_LevelWindowProperty );
if ( m_LevelWindowProperty.IsNull() )
{
Modified();
}
// else SetLevelWindowProperty will call Modified();
}
// sets an specific LevelWindowProperty, all changes will affect the image belonging to this property.
void mitk::LevelWindowManager::SetLevelWindowProperty(LevelWindowProperty::Pointer levelWindowProperty)
{
if (levelWindowProperty.IsNull())
return;
if (m_IsPropertyModifiedTagSet) // remove listener for old property
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
m_LevelWindowProperty = levelWindowProperty;
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New(); // register listener for new property
command->SetCallbackFunction(this, &LevelWindowManager::OnPropertyModified);
m_PropertyModifiedTag = m_LevelWindowProperty->AddObserver( itk::ModifiedEvent(), command );
m_IsPropertyModifiedTagSet = true;
/* search image than belongs to the property */
mitk::NodePredicateProperty::Pointer p = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p);
if (n == NULL)
{
mitkThrow() << "No Image in DataStorage that belongs to LevelWindow property";// << m_LevelWindowProperty->GetValueAsString();
}
m_CurrentImage = dynamic_cast<mitk::Image*>(n->GetData());
n->SetBoolProperty( "imageForLevelWindow", true );
this->Modified();
}
// returns the current mitkLevelWindowProperty object from the image that is affected by changes
mitk::LevelWindowProperty::Pointer mitk::LevelWindowManager::GetLevelWindowProperty()
{
return m_LevelWindowProperty;
}
// returns Level/Window values for the current image
const mitk::LevelWindow& mitk::LevelWindowManager::GetLevelWindow()
{
if (m_LevelWindowProperty.IsNotNull())
{
return m_LevelWindowProperty->GetLevelWindow();
}
else
{
itkExceptionMacro("No LevelWindow available!");
}
}
// sets new Level/Window values and informs all listeners about changes
void mitk::LevelWindowManager::SetLevelWindow(const mitk::LevelWindow& levelWindow)
{
if (m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->SetLevelWindow(levelWindow);
}
this->Modified();
}
void mitk::LevelWindowManager::DataStorageChanged( const mitk::DataNode* )
{
this->DataStorageRemovedNode();
}
void mitk::LevelWindowManager::DataStorageRemovedNode( const mitk::DataNode* removedNode )
{
/* remove old observers */
for (ObserverToPropertyMap::iterator iter = m_PropObserverToNode.begin();
iter != m_PropObserverToNode.end();
++iter)
{
(*iter).second->RemoveObserver((*iter).first);
}
m_PropObserverToNode.clear();
for (ObserverToPropertyMap::iterator iter = m_PropObserverToNode2.begin();
iter != m_PropObserverToNode2.end();
++iter)
{
(*iter).second->RemoveObserver((*iter).first);
}
m_PropObserverToNode2.clear();
if (m_DataStorage.IsNull())
{
itkExceptionMacro("DataStorage not set");
}
/* listen to changes in visible property of all images */
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if (it->Value().IsNull())
continue;
/* register listener for changes in visible property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command->SetCallbackFunction(this, &LevelWindowManager::Update);
m_PropObserverToNode[it->Value()->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command )] = it->Value()->GetProperty("visible");
}
/* listen to changes in layer property of all images */
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if (it->Value().IsNull())
continue;
/* register listener for changes in layer property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command2 = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command2->SetCallbackFunction(this, &LevelWindowManager::Update);
m_PropObserverToNode2[it->Value()->GetProperty("layer")->AddObserver( itk::ModifiedEvent(), command2 )] = it->Value()->GetProperty("layer");
}
/* search image than belongs to the property */
if (m_LevelWindowProperty.IsNull())
{
SetAutoTopMostImage(true, removedNode);
}
else
{
mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p2);
if (n == NULL || m_AutoTopMost) // if node was deleted, change our behaviour to AutoTopMost, if AutoTopMost is true change level window to topmost node
SetAutoTopMostImage(true, removedNode);
}
}
mitk::DataStorage* mitk::LevelWindowManager::GetDataStorage()
{
return m_DataStorage.GetPointer();
}
// true if changes on slider or line-edits will affect always the topmost layer image
bool mitk::LevelWindowManager::isAutoTopMost()
{
return m_AutoTopMost;
}
void mitk::LevelWindowManager::Update(const itk::EventObject&) // visible property of a image has changed
{
if (m_AutoTopMost)
{
SetAutoTopMostImage(true);
return;
}
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull())
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
node->SetBoolProperty( "imageForLevelWindow", true );
if (m_LevelWindowProperty.IsNull() && m_LevelWindowProperty.GetPointer() == levelWindowProperty) // we found our m_LevelWindowProperty
{
return;
}
}
Modified();
}
mitk::DataStorage::SetOfObjects::ConstPointer mitk::LevelWindowManager::GetRelevantNodes()
{
if (m_DataStorage.IsNull())
return mitk::DataStorage::SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); // return empty set
mitk::BoolProperty::Pointer trueProp = mitk::BoolProperty::New(true);
mitk::NodePredicateProperty::Pointer notBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(false));
mitk::NodePredicateProperty::Pointer hasLevelWindow = mitk::NodePredicateProperty::New("levelwindow", NULL);
mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image");
mitk::NodePredicateDataType::Pointer isDImage = mitk::NodePredicateDataType::New("DiffusionImage");
mitk::NodePredicateDataType::Pointer isTImage = mitk::NodePredicateDataType::New("TensorImage");
mitk::NodePredicateDataType::Pointer isQImage = mitk::NodePredicateDataType::New("QBallImage");
mitk::NodePredicateOr::Pointer predicateTypes = mitk::NodePredicateOr::New();
predicateTypes->AddPredicate(isImage);
predicateTypes->AddPredicate(isDImage);
predicateTypes->AddPredicate(isTImage);
predicateTypes->AddPredicate(isQImage);
mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New();
predicate->AddPredicate(notBinary);
predicate->AddPredicate(hasLevelWindow);
predicate->AddPredicate(predicateTypes);
mitk::DataStorage::SetOfObjects::ConstPointer relevantNodes = m_DataStorage->GetSubset( predicate );
return relevantNodes;
}
mitk::Image* mitk::LevelWindowManager::GetCurrentImage()
{
return m_CurrentImage;
}
<commit_msg>comment code in again<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkLevelWindowManager.h"
#include <itkCommand.h>
#include "mitkDataStorage.h"
#include "mitkNodePredicateBase.h"
#include "mitkNodePredicateProperty.h"
#include "mitkNodePredicateDataType.h"
#include "mitkNodePredicateAnd.h"
#include "mitkNodePredicateOr.h"
#include "mitkNodePredicateNot.h"
#include "mitkProperties.h"
#include "mitkMessage.h"
mitk::LevelWindowManager::LevelWindowManager()
: m_DataStorage(NULL)
, m_LevelWindowProperty(NULL)
, m_AutoTopMost(true)
, m_IsObserverTagSet(false)
, m_CurrentImage(NULL)
, m_IsPropertyModifiedTagSet(false)
{
}
mitk::LevelWindowManager::~LevelWindowManager()
{
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageChanged ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
m_DataStorage = NULL;
}
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
for( std::map<unsigned long, mitk::BaseProperty::Pointer>::iterator iter = m_PropObserverToNode.begin();
iter != m_PropObserverToNode.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first);
}
for( std::map<unsigned long, mitk::BaseProperty::Pointer>::iterator iter = m_PropObserverToNode2.begin();
iter != m_PropObserverToNode2.end();
++iter )
{
(*iter).second->RemoveObserver((*iter).first);
}
}
void mitk::LevelWindowManager::SetDataStorage( mitk::DataStorage* ds )
{
if (ds == NULL) return;
/* remove listeners of old DataStorage */
if (m_DataStorage.IsNotNull())
{
m_DataStorage->AddNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageChanged ));
m_DataStorage->RemoveNodeEvent.RemoveListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
}
/* register listener for new DataStorage */
m_DataStorage = ds; // register
m_DataStorage->AddNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageChanged ));
m_DataStorage->RemoveNodeEvent.AddListener(
MessageDelegate1<LevelWindowManager, const mitk::DataNode*>( this, &LevelWindowManager::DataStorageRemovedNode ));
this->DataStorageChanged(); // update us with new DataStorage
}
void mitk::LevelWindowManager::OnPropertyModified(const itk::EventObject& )
{
Modified();
}
void mitk::LevelWindowManager::SetAutoTopMostImage(bool autoTopMost, const mitk::DataNode* removedNode)
{
m_AutoTopMost = autoTopMost;
if (m_AutoTopMost == false)
return;
if (m_IsPropertyModifiedTagSet && m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
/* search topmost image */
if (m_DataStorage.IsNull())
{
itkExceptionMacro("DataStorage not set");
}
int maxLayer = itk::NumericTraits<int>::min();
m_LevelWindowProperty = NULL;
mitk::DataNode::Pointer topLevelNode;
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin(); it != all->End(); ++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull() || (removedNode != NULL && node == removedNode))
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
int layer = 0;
node->GetIntProperty("layer", layer);
if ( layer < maxLayer )
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
topLevelNode = node;
maxLayer = layer;
}
if (topLevelNode.IsNotNull())
{
topLevelNode->SetBoolProperty( "imageForLevelWindow", true );
}
this->SetLevelWindowProperty( m_LevelWindowProperty );
if ( m_LevelWindowProperty.IsNull() )
{
Modified();
}
// else SetLevelWindowProperty will call Modified();
}
// sets an specific LevelWindowProperty, all changes will affect the image belonging to this property.
void mitk::LevelWindowManager::SetLevelWindowProperty(LevelWindowProperty::Pointer levelWindowProperty)
{
if (levelWindowProperty.IsNull())
return;
if (m_IsPropertyModifiedTagSet) // remove listener for old property
{
m_LevelWindowProperty->RemoveObserver(m_PropertyModifiedTag);
m_IsPropertyModifiedTagSet = false;
}
m_LevelWindowProperty = levelWindowProperty;
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New(); // register listener for new property
command->SetCallbackFunction(this, &LevelWindowManager::OnPropertyModified);
m_PropertyModifiedTag = m_LevelWindowProperty->AddObserver( itk::ModifiedEvent(), command );
m_IsPropertyModifiedTagSet = true;
/* search image than belongs to the property */
mitk::NodePredicateProperty::Pointer p = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p);
if (n == NULL)
{
mitkThrow() << "No Image in DataStorage that belongs to LevelWindow property" << m_LevelWindowProperty;
}
m_CurrentImage = dynamic_cast<mitk::Image*>(n->GetData());
n->SetBoolProperty( "imageForLevelWindow", true );
this->Modified();
}
// returns the current mitkLevelWindowProperty object from the image that is affected by changes
mitk::LevelWindowProperty::Pointer mitk::LevelWindowManager::GetLevelWindowProperty()
{
return m_LevelWindowProperty;
}
// returns Level/Window values for the current image
const mitk::LevelWindow& mitk::LevelWindowManager::GetLevelWindow()
{
if (m_LevelWindowProperty.IsNotNull())
{
return m_LevelWindowProperty->GetLevelWindow();
}
else
{
itkExceptionMacro("No LevelWindow available!");
}
}
// sets new Level/Window values and informs all listeners about changes
void mitk::LevelWindowManager::SetLevelWindow(const mitk::LevelWindow& levelWindow)
{
if (m_LevelWindowProperty.IsNotNull())
{
m_LevelWindowProperty->SetLevelWindow(levelWindow);
}
this->Modified();
}
void mitk::LevelWindowManager::DataStorageChanged( const mitk::DataNode* )
{
this->DataStorageRemovedNode();
}
void mitk::LevelWindowManager::DataStorageRemovedNode( const mitk::DataNode* removedNode )
{
/* remove old observers */
for (ObserverToPropertyMap::iterator iter = m_PropObserverToNode.begin();
iter != m_PropObserverToNode.end();
++iter)
{
(*iter).second->RemoveObserver((*iter).first);
}
m_PropObserverToNode.clear();
for (ObserverToPropertyMap::iterator iter = m_PropObserverToNode2.begin();
iter != m_PropObserverToNode2.end();
++iter)
{
(*iter).second->RemoveObserver((*iter).first);
}
m_PropObserverToNode2.clear();
if (m_DataStorage.IsNull())
{
itkExceptionMacro("DataStorage not set");
}
/* listen to changes in visible property of all images */
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if (it->Value().IsNull())
continue;
/* register listener for changes in visible property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command->SetCallbackFunction(this, &LevelWindowManager::Update);
m_PropObserverToNode[it->Value()->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command )] = it->Value()->GetProperty("visible");
}
/* listen to changes in layer property of all images */
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
if (it->Value().IsNull())
continue;
/* register listener for changes in layer property */
itk::ReceptorMemberCommand<LevelWindowManager>::Pointer command2 = itk::ReceptorMemberCommand<LevelWindowManager>::New();
command2->SetCallbackFunction(this, &LevelWindowManager::Update);
m_PropObserverToNode2[it->Value()->GetProperty("layer")->AddObserver( itk::ModifiedEvent(), command2 )] = it->Value()->GetProperty("layer");
}
/* search image than belongs to the property */
if (m_LevelWindowProperty.IsNull())
{
SetAutoTopMostImage(true, removedNode);
}
else
{
mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("levelwindow", m_LevelWindowProperty);
mitk::DataNode* n = m_DataStorage->GetNode(p2);
if (n == NULL || m_AutoTopMost) // if node was deleted, change our behaviour to AutoTopMost, if AutoTopMost is true change level window to topmost node
SetAutoTopMostImage(true, removedNode);
}
}
mitk::DataStorage* mitk::LevelWindowManager::GetDataStorage()
{
return m_DataStorage.GetPointer();
}
// true if changes on slider or line-edits will affect always the topmost layer image
bool mitk::LevelWindowManager::isAutoTopMost()
{
return m_AutoTopMost;
}
void mitk::LevelWindowManager::Update(const itk::EventObject&) // visible property of a image has changed
{
if (m_AutoTopMost)
{
SetAutoTopMostImage(true);
return;
}
mitk::DataStorage::SetOfObjects::ConstPointer all = this->GetRelevantNodes();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin();
it != all->End();
++it)
{
mitk::DataNode::Pointer node = it->Value();
if (node.IsNull())
continue;
node->SetBoolProperty( "imageForLevelWindow", false );
if (node->IsVisible(NULL) == false)
continue;
mitk::LevelWindowProperty::Pointer levelWindowProperty = dynamic_cast<mitk::LevelWindowProperty*>(node->GetProperty("levelwindow"));
if (levelWindowProperty.IsNull())
continue;
m_LevelWindowProperty = levelWindowProperty;
m_CurrentImage = dynamic_cast<mitk::Image*>(node->GetData());
node->SetBoolProperty( "imageForLevelWindow", true );
if (m_LevelWindowProperty.IsNull() && m_LevelWindowProperty.GetPointer() == levelWindowProperty) // we found our m_LevelWindowProperty
{
return;
}
}
Modified();
}
mitk::DataStorage::SetOfObjects::ConstPointer mitk::LevelWindowManager::GetRelevantNodes()
{
if (m_DataStorage.IsNull())
return mitk::DataStorage::SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); // return empty set
mitk::BoolProperty::Pointer trueProp = mitk::BoolProperty::New(true);
mitk::NodePredicateProperty::Pointer notBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(false));
mitk::NodePredicateProperty::Pointer hasLevelWindow = mitk::NodePredicateProperty::New("levelwindow", NULL);
mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image");
mitk::NodePredicateDataType::Pointer isDImage = mitk::NodePredicateDataType::New("DiffusionImage");
mitk::NodePredicateDataType::Pointer isTImage = mitk::NodePredicateDataType::New("TensorImage");
mitk::NodePredicateDataType::Pointer isQImage = mitk::NodePredicateDataType::New("QBallImage");
mitk::NodePredicateOr::Pointer predicateTypes = mitk::NodePredicateOr::New();
predicateTypes->AddPredicate(isImage);
predicateTypes->AddPredicate(isDImage);
predicateTypes->AddPredicate(isTImage);
predicateTypes->AddPredicate(isQImage);
mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New();
predicate->AddPredicate(notBinary);
predicate->AddPredicate(hasLevelWindow);
predicate->AddPredicate(predicateTypes);
mitk::DataStorage::SetOfObjects::ConstPointer relevantNodes = m_DataStorage->GetSubset( predicate );
return relevantNodes;
}
mitk::Image* mitk::LevelWindowManager::GetCurrentImage()
{
return m_CurrentImage;
}
<|endoftext|> |
<commit_before>#include <iostream>
//The following is needed if we don't want to link a Pizza & Chili index.
#define SEQAN_DEBUG_PIZZACHILI
#include <seqan/index.h>
using namespace std;
using namespace seqan;
int main() {
///The following code creates a Pizza & Chili index and assigns it the text
///$"tobeornottobe"$.
typedef Index<String<char>, PizzaChili<PizzaChili_SA> > index_t;
index_t index_pc;
indexText(index_pc) = "tobeornottobe";
///Now we may create a default finder and search for a substring. The index
///is only now created because its evaluation is lazy. Immediately after
///the index has been created, the $indexText$ is discarded to save memory.
Finder<index_t> finder(index_pc);
while (find(finder, "be"))
cout << "Hit at " << position(finder) << endl;
///We may query the text of the index. Notice that this returns a string
///without any real content. The string is lazily evaluated in order to
///save memory. Only the substring we are actually displaying will be
///loaded into memory.
/// $indexText(..)$ is a shortcut for $getFibre(.., PizzaChili_Text())$.
Fibre<index_t, PizzaChili_Text>::Type text = indexText(index_pc);
cout << "infix(text, 2, 7): " << infix(text, 2, 7) << endl;
///We can save the index structure in disc and load it again.
save(index_pc, "pizzachili");
index_t index2;
open(index2, "pizzachili");
cout << indexText(index2) << endl;
return 0;
}
<commit_msg>Pizza & Chili demo removed. Must be placed somewhere else<commit_after><|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// See docs in ../ops/nn_ops.cc.
#define EIGEN_USE_THREADS
#include "tensorflow/core/kernels/sparse_xent_op.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
template <typename Index>
Status CheckInvalidLabelIndex(const Tensor& labels, int64 max_index) {
if (labels.NumElements() == 0) return Status::OK();
const auto label_values = labels.vec<Index>();
int64 bad_index;
auto min_max_dim_value = std::minmax_element(
label_values.data(), label_values.data() + label_values.size());
if (*min_max_dim_value.first < 0 || *min_max_dim_value.second >= max_index) {
bad_index = (*min_max_dim_value.first < 0) ? *min_max_dim_value.first
: *min_max_dim_value.second;
return errors::InvalidArgument(
"Received a label value of ", bad_index,
" which is outside the valid range of [0, ", max_index,
"). Label values: ", labels.SummarizeValue(labels.NumElements()));
}
return Status::OK();
}
template <typename Device, typename T, typename Index>
class SparseSoftmaxXentWithLogitsOp : public OpKernel {
public:
explicit SparseSoftmaxXentWithLogitsOp(OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& logits = context->input(0);
const Tensor& labels = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(logits.shape()),
errors::InvalidArgument("logits must be 2-D, but got shape ",
logits.shape().DebugString()));
OP_REQUIRES(context, TensorShapeUtils::IsVector(labels.shape()),
errors::InvalidArgument("labels must be 1-D, but got shape ",
labels.shape().DebugString()));
OP_REQUIRES(context, logits.dim_size(0) == labels.dim_size(0),
errors::InvalidArgument(
"logits and labels must have the same first dimension, "
"got logits shape ",
logits.shape().DebugString(), " and labels shape ",
labels.shape().DebugString()));
OP_REQUIRES(context, logits.dim_size(1) > 0,
errors::InvalidArgument(
"Must have at least one class, but got logits shape ",
logits.shape().DebugString()));
Tensor scratch;
OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::value,
labels.shape(), &scratch));
Tensor* loss_out = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{1}, 0, labels.shape(), &loss_out));
Tensor* back_out = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 1, logits.shape(), &back_out));
if (logits.dim_size(0) > 0) {
if (std::is_same<Device, CPUDevice>::value) {
OP_REQUIRES_OK(
context, CheckInvalidLabelIndex<Index>(labels, logits.dim_size(1)));
}
functor::SparseXentFunctor<Device, T, Index> functor;
functor(context, logits.matrix<T>(), labels.vec<Index>(),
scratch.vec<T>(), loss_out->vec<T>(), back_out->matrix<T>());
}
}
};
// Partial specialization for a CPUDevice, that uses the Eigen implementation
// from XentEigenImpl.
namespace functor {
template <typename T, typename Index>
struct SparseXentFunctor<CPUDevice, T, Index> {
void operator()(OpKernelContext* ctx, typename TTypes<T>::ConstMatrix logits,
typename TTypes<Index>::ConstVec labels,
typename TTypes<T>::Vec scratch, typename TTypes<T>::Vec loss,
typename TTypes<T>::Matrix backprop) {
SparseXentEigenImpl<CPUDevice, T, Index>::Compute(ctx, logits, labels,
scratch, loss, backprop);
}
};
} // namespace functor
#define REGISTER(Dev, T, Index) \
REGISTER_KERNEL_BUILDER( \
Name("SparseSoftmaxCrossEntropyWithLogits") \
.Device(DEVICE_##Dev) \
.TypeConstraint<T>("T") \
.TypeConstraint<Index>("Tlabels"), \
SparseSoftmaxXentWithLogitsOp<Dev##Device, T, Index>);
REGISTER(CPU, float, int32)
REGISTER(CPU, float, int64)
REGISTER(CPU, double, int32)
REGISTER(CPU, double, int64)
REGISTER(CPU, Eigen::bfloat16, int32)
REGISTER(CPU, Eigen::bfloat16, int64)
REGISTER(CPU, Eigen::half, int32)
REGISTER(CPU, Eigen::half, int64)
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
REGISTER(GPU, float, int32)
REGISTER(GPU, float, int64)
REGISTER(GPU, Eigen::half, int32)
REGISTER(GPU, Eigen::half, int64)
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#undef REGISTER
} // namespace tensorflow
<commit_msg>removed Eigen:: from datatype<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// See docs in ../ops/nn_ops.cc.
#define EIGEN_USE_THREADS
#include "tensorflow/core/kernels/sparse_xent_op.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
template <typename Index>
Status CheckInvalidLabelIndex(const Tensor& labels, int64 max_index) {
if (labels.NumElements() == 0) return Status::OK();
const auto label_values = labels.vec<Index>();
int64 bad_index;
auto min_max_dim_value = std::minmax_element(
label_values.data(), label_values.data() + label_values.size());
if (*min_max_dim_value.first < 0 || *min_max_dim_value.second >= max_index) {
bad_index = (*min_max_dim_value.first < 0) ? *min_max_dim_value.first
: *min_max_dim_value.second;
return errors::InvalidArgument(
"Received a label value of ", bad_index,
" which is outside the valid range of [0, ", max_index,
"). Label values: ", labels.SummarizeValue(labels.NumElements()));
}
return Status::OK();
}
template <typename Device, typename T, typename Index>
class SparseSoftmaxXentWithLogitsOp : public OpKernel {
public:
explicit SparseSoftmaxXentWithLogitsOp(OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& logits = context->input(0);
const Tensor& labels = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(logits.shape()),
errors::InvalidArgument("logits must be 2-D, but got shape ",
logits.shape().DebugString()));
OP_REQUIRES(context, TensorShapeUtils::IsVector(labels.shape()),
errors::InvalidArgument("labels must be 1-D, but got shape ",
labels.shape().DebugString()));
OP_REQUIRES(context, logits.dim_size(0) == labels.dim_size(0),
errors::InvalidArgument(
"logits and labels must have the same first dimension, "
"got logits shape ",
logits.shape().DebugString(), " and labels shape ",
labels.shape().DebugString()));
OP_REQUIRES(context, logits.dim_size(1) > 0,
errors::InvalidArgument(
"Must have at least one class, but got logits shape ",
logits.shape().DebugString()));
Tensor scratch;
OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::value,
labels.shape(), &scratch));
Tensor* loss_out = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{1}, 0, labels.shape(), &loss_out));
Tensor* back_out = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 1, logits.shape(), &back_out));
if (logits.dim_size(0) > 0) {
if (std::is_same<Device, CPUDevice>::value) {
OP_REQUIRES_OK(
context, CheckInvalidLabelIndex<Index>(labels, logits.dim_size(1)));
}
functor::SparseXentFunctor<Device, T, Index> functor;
functor(context, logits.matrix<T>(), labels.vec<Index>(),
scratch.vec<T>(), loss_out->vec<T>(), back_out->matrix<T>());
}
}
};
// Partial specialization for a CPUDevice, that uses the Eigen implementation
// from XentEigenImpl.
namespace functor {
template <typename T, typename Index>
struct SparseXentFunctor<CPUDevice, T, Index> {
void operator()(OpKernelContext* ctx, typename TTypes<T>::ConstMatrix logits,
typename TTypes<Index>::ConstVec labels,
typename TTypes<T>::Vec scratch, typename TTypes<T>::Vec loss,
typename TTypes<T>::Matrix backprop) {
SparseXentEigenImpl<CPUDevice, T, Index>::Compute(ctx, logits, labels,
scratch, loss, backprop);
}
};
} // namespace functor
#define REGISTER(Dev, T, Index) \
REGISTER_KERNEL_BUILDER( \
Name("SparseSoftmaxCrossEntropyWithLogits") \
.Device(DEVICE_##Dev) \
.TypeConstraint<T>("T") \
.TypeConstraint<Index>("Tlabels"), \
SparseSoftmaxXentWithLogitsOp<Dev##Device, T, Index>);
REGISTER(CPU, float, int32)
REGISTER(CPU, float, int64)
REGISTER(CPU, double, int32)
REGISTER(CPU, double, int64)
REGISTER(CPU, bfloat16, int32)
REGISTER(CPU, bfloat16, int64)
REGISTER(CPU, Eigen::half, int32)
REGISTER(CPU, Eigen::half, int64)
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
REGISTER(GPU, float, int32)
REGISTER(GPU, float, int64)
REGISTER(GPU, Eigen::half, int32)
REGISTER(GPU, Eigen::half, int64)
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#undef REGISTER
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Setup.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Setup.h"
#include "FxHelper.h"
#include "UpdateRunner.h"
#include "MachineInstaller.h"
#include <cstdio>
#include <string>
CAppModule* _Module;
typedef BOOL(WINAPI *SetDefaultDllDirectoriesFunction)(DWORD DirectoryFlags);
// Some libraries are still loaded from the current directories.
// If we pre-load them with an absolute path then we are good.
void PreloadLibs()
{
wchar_t sys32Folder[MAX_PATH];
GetSystemDirectory(sys32Folder, MAX_PATH);
std::wstring version = (std::wstring(sys32Folder) + L"\\version.dll");
std::wstring logoncli = (std::wstring(sys32Folder) + L"\\logoncli.dll");
std::wstring sspicli = (std::wstring(sys32Folder) + L"\\sspicli.dll");
std::wstring urlmon = (std::wstring(sys32Folder) + L"\\urlmon.dll");
LoadLibrary(version.c_str());
LoadLibrary(logoncli.c_str());
LoadLibrary(sspicli.c_str());
LoadLibrary(urlmon.c_str());
}
void MitigateDllHijacking()
{
// Set the default DLL lookup directory to System32 for ourselves and kernel32.dll
HMODULE hKernel32 = LoadLibrary(L"kernel32.dll");
if (hKernel32)
{
SetDefaultDllDirectoriesFunction pfn = (SetDefaultDllDirectoriesFunction)GetProcAddress(hKernel32, "SetDefaultDllDirectories");
if (pfn)
{
(*pfn)(LOAD_LIBRARY_SEARCH_SYSTEM32);
}
}
PreloadLibs();
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
MitigateDllHijacking();
int exitCode = -1;
CString cmdLine(lpCmdLine);
if (cmdLine.Find(L"--checkInstall") >= 0) {
// If we're already installed, exit as fast as possible
if (!MachineInstaller::ShouldSilentInstall()) {
return 0;
}
// Make sure update.exe gets silent
wcscat(lpCmdLine, L" --silent");
}
HRESULT hr = ::CoInitialize(NULL);
ATLASSERT(SUCCEEDED(hr));
AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES);
_Module = new CAppModule();
hr = _Module->Init(NULL, hInstance);
bool isQuiet = (cmdLine.Find(L"-s") >= 0);
bool weAreUACElevated = CUpdateRunner::AreWeUACElevated() == S_OK;
bool attemptingToRerun = (cmdLine.Find(L"--rerunningWithoutUAC") >= 0);
if (weAreUACElevated && attemptingToRerun) {
CUpdateRunner::DisplayErrorMessage(CString(L"Please re-run this installer as a normal user instead of \"Run as Administrator\"."), NULL);
exitCode = E_FAIL;
goto out;
}
if (!CFxHelper::CanInstallDotNet4_5()) {
// Explain this as nicely as possible and give up.
MessageBox(0L, L"This program cannot run on Windows XP or before; it requires a later version of Windows.", L"Incompatible Operating System", 0);
exitCode = E_FAIL;
goto out;
}
NetVersion requiredVersion = CFxHelper::GetRequiredDotNetVersion();
if (!CFxHelper::IsDotNetInstalled(requiredVersion)) {
hr = CFxHelper::InstallDotNetFramework(requiredVersion, isQuiet);
if (FAILED(hr)) {
exitCode = hr; // #yolo
CUpdateRunner::DisplayErrorMessage(CString(L"Failed to install the .NET Framework, try installing the latest version manually"), NULL);
goto out;
}
// S_FALSE isn't failure, but we still shouldn't try to install
if (hr != S_OK) {
exitCode = 0;
goto out;
}
}
// If we're UAC-elevated, we shouldn't be because it will give us permissions
// problems later. Just silently rerun ourselves.
if (weAreUACElevated) {
wchar_t buf[4096];
HMODULE hMod = GetModuleHandle(NULL);
GetModuleFileNameW(hMod, buf, 4096);
wcscat(lpCmdLine, L" --rerunningWithoutUAC");
CUpdateRunner::ShellExecuteFromExplorer(buf, lpCmdLine);
exitCode = 0;
goto out;
}
exitCode = CUpdateRunner::ExtractUpdaterAndRun(lpCmdLine, false);
out:
_Module->Term();
return exitCode;
}
<commit_msg>Minor code cleanup<commit_after>// Setup.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Setup.h"
#include "FxHelper.h"
#include "UpdateRunner.h"
#include "MachineInstaller.h"
#include <cstdio>
#include <string>
CAppModule* _Module;
typedef BOOL(WINAPI *SetDefaultDllDirectoriesFunction)(DWORD DirectoryFlags);
// Some libraries are still loaded from the current directories.
// If we pre-load them with an absolute path then we are good.
static void PreloadLibs()
{
wchar_t sys32Folder[MAX_PATH];
GetSystemDirectory(sys32Folder, MAX_PATH);
std::wstring version = (std::wstring(sys32Folder) + L"\\version.dll");
std::wstring logoncli = (std::wstring(sys32Folder) + L"\\logoncli.dll");
std::wstring sspicli = (std::wstring(sys32Folder) + L"\\sspicli.dll");
std::wstring urlmon = (std::wstring(sys32Folder) + L"\\urlmon.dll");
LoadLibrary(version.c_str());
LoadLibrary(logoncli.c_str());
LoadLibrary(sspicli.c_str());
LoadLibrary(urlmon.c_str());
}
static void MitigateDllHijacking()
{
// Set the default DLL lookup directory to System32 for ourselves and kernel32.dll
HMODULE hKernel32 = LoadLibrary(L"kernel32.dll");
if (hKernel32)
{
SetDefaultDllDirectoriesFunction pfn = (SetDefaultDllDirectoriesFunction)GetProcAddress(hKernel32, "SetDefaultDllDirectories");
if (pfn)
{
(*pfn)(LOAD_LIBRARY_SEARCH_SYSTEM32);
}
}
PreloadLibs();
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
MitigateDllHijacking();
int exitCode = -1;
CString cmdLine(lpCmdLine);
if (cmdLine.Find(L"--checkInstall") >= 0) {
// If we're already installed, exit as fast as possible
if (!MachineInstaller::ShouldSilentInstall()) {
return 0;
}
// Make sure update.exe gets silent
wcscat(lpCmdLine, L" --silent");
}
HRESULT hr = ::CoInitialize(NULL);
ATLASSERT(SUCCEEDED(hr));
AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES);
_Module = new CAppModule();
hr = _Module->Init(NULL, hInstance);
bool isQuiet = (cmdLine.Find(L"-s") >= 0);
bool weAreUACElevated = CUpdateRunner::AreWeUACElevated() == S_OK;
bool attemptingToRerun = (cmdLine.Find(L"--rerunningWithoutUAC") >= 0);
if (weAreUACElevated && attemptingToRerun) {
CUpdateRunner::DisplayErrorMessage(CString(L"Please re-run this installer as a normal user instead of \"Run as Administrator\"."), NULL);
exitCode = E_FAIL;
goto out;
}
if (!CFxHelper::CanInstallDotNet4_5()) {
// Explain this as nicely as possible and give up.
MessageBox(0L, L"This program cannot run on Windows XP or before; it requires a later version of Windows.", L"Incompatible Operating System", 0);
exitCode = E_FAIL;
goto out;
}
NetVersion requiredVersion = CFxHelper::GetRequiredDotNetVersion();
if (!CFxHelper::IsDotNetInstalled(requiredVersion)) {
hr = CFxHelper::InstallDotNetFramework(requiredVersion, isQuiet);
if (FAILED(hr)) {
exitCode = hr; // #yolo
CUpdateRunner::DisplayErrorMessage(CString(L"Failed to install the .NET Framework, try installing the latest version manually"), NULL);
goto out;
}
// S_FALSE isn't failure, but we still shouldn't try to install
if (hr != S_OK) {
exitCode = 0;
goto out;
}
}
// If we're UAC-elevated, we shouldn't be because it will give us permissions
// problems later. Just silently rerun ourselves.
if (weAreUACElevated) {
wchar_t buf[4096];
HMODULE hMod = GetModuleHandle(NULL);
GetModuleFileNameW(hMod, buf, 4096);
wcscat(lpCmdLine, L" --rerunningWithoutUAC");
CUpdateRunner::ShellExecuteFromExplorer(buf, lpCmdLine);
exitCode = 0;
goto out;
}
exitCode = CUpdateRunner::ExtractUpdaterAndRun(lpCmdLine, false);
out:
_Module->Term();
return exitCode;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Randomized malloc, for detecting memory-based non-determinisms in redex.
* To use, build redex-all-malloc-dbg, and then run as follows (you'll probably
* want all the args from a "real" redex run, but this is the idea):
*
* MALLOC_SEED=seed1 ./redex-all-malloc-dbg --out out-seed1.apk in.apk
* MALLOC_SEED=seed2 ./redex-all-malloc-dbg --out out-seed2.apk in.apk
*
* If the two output APKs differ, it could be because of an indeterminism
* caused by branching on pointer values (e.g. containers sorted by pointer
* keys).
*
* Note that this is NOT an attempt to make a deterministic allocator. System
* malloc is non deterministic (practically speaking), but it will often behave
* very similarly, which can hide non determinisms caused by pointers. This
* allocator is intended to make such non determinisms happen *every* time,
* instead of only once in a while.
*/
#ifdef __APPLE__
#include <dlfcn.h>
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <thread>
#include "Debug.h"
namespace {
// The tinyest PRNG ever.
// http://www.woodmann.com/forum/showthread.php?3100-super-tiny-PRNG
class TinyPRNG {
public:
explicit TinyPRNG(const std::string& randSeed) { seed(randSeed); }
uint32_t next_rand() {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
// Advance the rand state.
m_next_rand += (m_next_rand * m_next_rand) | 5;
// pull out the high bit.
result |= (m_next_rand >> 31) << i;
}
return result;
}
void seed(const std::string& randSeed) {
constexpr auto state_size = sizeof(m_next_rand);
char state[state_size] = {};
std::string::size_type idx = 0;
for (auto& e : randSeed) {
state[idx % state_size] ^= e;
idx++;
}
memcpy(&m_next_rand, state, state_size);
}
private:
uint32_t m_next_rand = 0;
};
} // namespace
#ifdef __APPLE__
typedef void* (*MallocFn)(size_t);
static auto libc_malloc =
reinterpret_cast<MallocFn>(dlsym(RTLD_NEXT, "malloc"));
#endif
#ifdef __linux__
extern "C" {
extern void* __libc_malloc(size_t size);
}
static auto libc_malloc = __libc_malloc;
#endif
size_t next_power_of_two(size_t x) {
// Turn off all but msb.
while ((x & (x - 1)) != 0) {
x &= x - 1;
}
return x << 1;
}
namespace {
constexpr bool PRINT_SEED = false;
class MallocDebug {
public:
explicit MallocDebug() : m_rand("wharblegarbl") {
const char* seed_env = getenv("MALLOC_SEED");
if (seed_env != nullptr) {
if (PRINT_SEED) {
printf("re-seeding with %s\n", seed_env);
}
m_rand.seed(seed_env);
}
}
void* malloc(size_t size) noexcept {
if (m_in_malloc) {
return libc_malloc(size);
}
m_in_malloc = true;
auto ret = malloc_impl(size);
m_in_malloc = false;
return ret;
}
private:
struct Block {
void* ptr;
size_t size;
Block(void* ptr, size_t size) : ptr(ptr), size(size) {}
~Block() { free(ptr); }
Block(const Block&) = delete;
Block(Block&& other) noexcept : ptr(other.release()), size(other.size) {}
Block& operator=(const Block&) = delete;
Block& operator=(Block&& rhs) {
ptr = rhs.release();
size = rhs.size;
return *this;
}
void* release() {
void* tmp = ptr;
ptr = nullptr;
return tmp;
}
};
bool m_in_malloc = false;
std::map<size_t, std::vector<Block>> m_blocks;
TinyPRNG m_rand;
void* malloc_impl(size_t size) noexcept {
constexpr int block_count = 8;
auto next_size = next_power_of_two(size);
auto it = m_blocks.find(next_size);
if (it == m_blocks.end()) {
it = m_blocks.emplace(next_size, std::vector<Block>()).first;
}
auto& vec = it->second;
while (vec.size() < block_count) {
auto ptr = libc_malloc(next_size);
vec.emplace_back(ptr, next_size);
}
auto idx = m_rand.next_rand() % block_count;
auto block_size = vec[idx].size;
auto block_ptr = vec[idx].release();
vec.erase(vec.begin() + idx);
always_assert(block_size >= size);
return block_ptr;
}
};
thread_local MallocDebug malloc_debug;
} // namespace
extern "C" {
void* malloc(size_t sz) { return malloc_debug.malloc(sz); }
}
<commit_msg>Add more allocation entrypoints to MallocDebug<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Randomized malloc, for detecting memory-based non-determinisms in redex.
* To use, build redex-all-malloc-dbg, and then run as follows (you'll probably
* want all the args from a "real" redex run, but this is the idea):
*
* MALLOC_SEED=seed1 ./redex-all-malloc-dbg --out out-seed1.apk in.apk
* MALLOC_SEED=seed2 ./redex-all-malloc-dbg --out out-seed2.apk in.apk
*
* If the two output APKs differ, it could be because of an indeterminism
* caused by branching on pointer values (e.g. containers sorted by pointer
* keys).
*
* Note that this is NOT an attempt to make a deterministic allocator. System
* malloc is non deterministic (practically speaking), but it will often behave
* very similarly, which can hide non determinisms caused by pointers. This
* allocator is intended to make such non determinisms happen *every* time,
* instead of only once in a while.
*/
#ifdef __APPLE__
#include <dlfcn.h>
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <thread>
#include "Debug.h"
namespace {
// The tinyest PRNG ever.
// http://www.woodmann.com/forum/showthread.php?3100-super-tiny-PRNG
class TinyPRNG {
public:
explicit TinyPRNG(const std::string& randSeed) { seed(randSeed); }
uint32_t next_rand() {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
// Advance the rand state.
m_next_rand += (m_next_rand * m_next_rand) | 5;
// pull out the high bit.
result |= (m_next_rand >> 31) << i;
}
return result;
}
void seed(const std::string& randSeed) {
constexpr auto state_size = sizeof(m_next_rand);
char state[state_size] = {};
std::string::size_type idx = 0;
for (auto& e : randSeed) {
state[idx % state_size] ^= e;
idx++;
}
memcpy(&m_next_rand, state, state_size);
}
private:
uint32_t m_next_rand = 0;
};
} // namespace
#ifdef __APPLE__
typedef void* (*MallocFn)(size_t);
static auto libc_malloc =
reinterpret_cast<MallocFn>(dlsym(RTLD_NEXT, "malloc"));
typedef void* (*CallocFn)(size_t, size_t);
static auto libc_calloc =
reinterpret_cast<CallocFn>(dlsym(RTLD_NEXT, "calloc"));
typedef void* (*MemalignFn)(size_t, size_t);
static auto libc_memalign =
reinterpret_cast<MemalignFn>(dlsym(RTLD_NEXT, "memalign"));
typedef int (*PosixMemalignFn)(void**, size_t, size_t);
static auto libc_posix_memalign =
reinterpret_cast<MemalignFn>(dlsym(RTLD_NEXT, "posix_memalign"));
#endif
#ifdef __linux__
extern "C" {
extern void* __libc_malloc(size_t size);
extern void* __libc_calloc(size_t nelem, size_t elsize);
extern void* __libc_memalign(size_t alignment, size_t size);
// This isn't found?
// extern int __posix_memalign(void** out, size_t alignment, size_t size);
}
static auto libc_malloc = __libc_malloc;
static auto libc_calloc = __libc_calloc;
static auto libc_memalign = __libc_memalign;
// static auto libc_posix_memalign = __posix_memalign;
#endif
namespace {
size_t next_power_of_two(size_t x) {
// Turn off all but msb.
while ((x & (x - 1)) != 0) {
x &= x - 1;
}
return x << 1;
}
constexpr bool PRINT_SEED = false;
class MallocDebug {
public:
explicit MallocDebug() : m_rand("wharblegarbl") {
const char* seed_env = getenv("MALLOC_SEED");
if (seed_env != nullptr) {
if (PRINT_SEED) {
printf("re-seeding with %s\n", seed_env);
}
m_rand.seed(seed_env);
}
}
void* malloc(size_t size) noexcept {
if (m_in_malloc) {
return libc_malloc(size);
}
m_in_malloc = true;
auto ret = malloc_impl<false>(
size, m_blocks, [](size_t s) { return libc_malloc(s); });
m_in_malloc = false;
return ret;
}
void* calloc(size_t nelem, size_t elsize) noexcept {
if (m_in_malloc) {
return libc_calloc(nelem, elsize);
}
m_in_malloc = true;
auto ret = malloc_impl<true>(
nelem * elsize, m_blocks, [](size_t s) { return libc_malloc(s); });
m_in_malloc = false;
return ret;
}
void* memalign(size_t alignment, size_t bytes) noexcept {
if (m_in_malloc) {
return libc_memalign(alignment, bytes);
}
m_in_malloc = true;
auto ret = malloc_impl<false>(
bytes,
m_aligned_blocks[alignment],
[](size_t, size_t a, size_t b) { return libc_memalign(a, b); },
alignment,
bytes);
m_in_malloc = false;
return ret;
}
int posix_memalign(void** out, size_t alignment, size_t size) noexcept {
if (m_in_malloc) {
*out = memalign(alignment, size);
return 0;
}
m_in_malloc = true;
auto ret = malloc_impl<false>(
size,
m_aligned_blocks[alignment],
[](size_t, size_t a, size_t b) { return libc_memalign(a, b); },
alignment,
size);
m_in_malloc = false;
*out = ret;
return 0;
}
private:
struct Block {
void* ptr;
size_t size;
Block(void* ptr, size_t size) : ptr(ptr), size(size) {}
~Block() { free(ptr); }
Block(const Block&) = delete;
Block(Block&& other) noexcept : ptr(other.release()), size(other.size) {}
Block& operator=(const Block&) = delete;
Block& operator=(Block&& rhs) {
ptr = rhs.release();
size = rhs.size;
return *this;
}
void* release() {
void* tmp = ptr;
ptr = nullptr;
return tmp;
}
};
bool m_in_malloc = false;
using BlockCache = std::map<size_t, std::vector<Block>>;
BlockCache m_blocks;
std::map<size_t, BlockCache> m_aligned_blocks;
TinyPRNG m_rand;
template <bool ZERO, typename Fn, typename... Args>
void* malloc_impl(size_t size,
BlockCache& blocks,
Fn fn,
Args... args) noexcept {
constexpr int block_count = 8;
auto next_size = next_power_of_two(size);
auto it = blocks.find(next_size);
if (it == blocks.end()) {
it = blocks.emplace(next_size, std::vector<Block>()).first;
}
auto& vec = it->second;
while (vec.size() < block_count) {
auto ptr = fn(next_size, args...);
vec.emplace_back(ptr, next_size);
}
auto idx = m_rand.next_rand() % block_count;
auto block_size = vec[idx].size;
void* block_ptr = vec[idx].release();
vec.erase(vec.begin() + idx);
always_assert(block_size >= size);
if (ZERO) {
// Zero out.
memset(block_ptr, 0, size);
}
return block_ptr;
}
};
thread_local MallocDebug malloc_debug;
} // namespace
extern "C" {
void* malloc(size_t sz) { return malloc_debug.malloc(sz); }
void* calloc(size_t nelem, size_t elsize) {
return malloc_debug.calloc(nelem, elsize);
}
void* memalign(size_t alignment, size_t bytes) {
return malloc_debug.memalign(alignment, bytes);
}
int posix_memalign(void** out, size_t alignment, size_t size) {
return malloc_debug.posix_memalign(out, alignment, size);
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2015-present Advanced Micro Devices, Inc.
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 <hip/hip_runtime.h>
#include "hiprtc_internal.hpp"
#include <hip/hiprtc.h>
#include "platform/program.hpp"
namespace hiprtc {
thread_local hiprtcResult g_lastRtcError = HIPRTC_SUCCESS;
}
class ProgramState {
amd::Monitor lock_;
private:
static ProgramState* programState_;
ProgramState() : lock_("Guards program state") {}
~ProgramState() {}
public:
std::unordered_map<amd::Program*,
std::pair<std::vector<std::string>, std::vector<std::string>>> progHeaders_;
std::map<std::string, std::pair<std::string, std::string>> nameExpresssion_;
static ProgramState& instance();
void createProgramHeaders(amd::Program* program, int numHeaders,
const char** headers, const char** headerNames);
void getProgramHeaders(amd::Program* program, int* numHeaders, char** headers, char ** headerNames);
uint32_t addNameExpression(const char* name_expression);
char* getLoweredName(const char* name_expression);
};
ProgramState* ProgramState::programState_ = nullptr;
ProgramState& ProgramState::instance() {
if (programState_ == nullptr) {
programState_ = new ProgramState;
}
return *programState_;
}
void ProgramState::createProgramHeaders(amd::Program* program, int numHeaders,
const char** headers, const char** headerNames) {
amd::ScopedLock lock(lock_);
std::vector<std::string> vHeaderNames;
std::vector<std::string> vHeaders;
for (auto i = 0; i != numHeaders; ++i) {
vHeaders.emplace_back(headers[i]);
vHeaderNames.emplace_back(headerNames[i]);
progHeaders_[program] = std::make_pair(std::move(vHeaders), std::move(vHeaderNames));
}
}
void ProgramState::getProgramHeaders(amd::Program* program, int* numHeaders,
char** headers, char ** headerNames) {
amd::ScopedLock lock(lock_);
const auto it = progHeaders_.find(program);
if (it != progHeaders_.cend()) {
*numHeaders = it->second.first.size();
*headers = reinterpret_cast<char*>(it->second.first.data());
*headerNames = reinterpret_cast<char*>(it->second.second.data());
}
}
uint32_t ProgramState::addNameExpression(const char* name_expression) {
amd::ScopedLock lock(lock_);
// Strip clean of any '(' or ')' or '&'
std::string strippedName(name_expression);
if (strippedName.back() == ')') {
strippedName.pop_back();
strippedName.erase(0, strippedName.find('('));
}
if (strippedName.front() == '&') {
strippedName.erase(0, 1);
}
auto it = nameExpresssion_.find(name_expression);
if (it == nameExpresssion_.end()) {
nameExpresssion_.insert(std::pair<std::string, std::pair<std::string, std::string>>
(name_expression, std::make_pair(strippedName,"")));
}
return nameExpresssion_.size();
}
char* demangle(const char* loweredName) {
if (!loweredName) {
return nullptr;
}
#if HIPRTC_USE_CXXABI || __linux__
int status = 0;
char* demangledName = abi::__cxa_demangle(loweredName, nullptr, nullptr, &status);
if (status != 0) {
return nullptr;
}
#elif defined(_WIN32)
char* demangledName = (char*)malloc(UNDECORATED_SIZE);
if (!UnDecorateSymbolName(loweredName, demangledName,
UNDECORATED_SIZE/ sizeof(*demangledName), UNDNAME_COMPLETE))
{
free(demangledName);
return nullptr;
}
#else
#error "Only Linux and Windows are supported"
#endif // HIPRTC_USE_CXXABI || __linux__
return demangledName;
}
static std::string handleMangledName(std::string name) {
std::string loweredName;
char* demangled = demangle(name.c_str());
loweredName.assign(demangled == nullptr ? std::string() : demangled);
free(demangled);
if (loweredName.empty()) {
return name;
}
if (loweredName.find(".kd") != std::string::npos) {
return {};
}
if (loweredName.find("void ") == 0) {
loweredName.erase(0, strlen("void "));
}
auto dx{loweredName.find_first_of("(<")};
if (dx == std::string::npos) {
return loweredName;
}
if (loweredName[dx] == '<') {
uint32_t count = 1;
do {
++dx;
count += (loweredName[dx] == '<') ? 1 : ((loweredName[dx] == '>') ? -1 : 0);
} while (count);
loweredName.erase(++dx);
} else {
loweredName.erase(dx);
}
return loweredName;
}
const char* hiprtcGetErrorString(hiprtcResult x) {
switch (x) {
case HIPRTC_SUCCESS:
return "HIPRTC_SUCCESS";
case HIPRTC_ERROR_OUT_OF_MEMORY:
return "HIPRTC_ERROR_OUT_OF_MEMORY";
case HIPRTC_ERROR_PROGRAM_CREATION_FAILURE:
return "HIPRTC_ERROR_PROGRAM_CREATION_FAILURE";
case HIPRTC_ERROR_INVALID_INPUT:
return "HIPRTC_ERROR_INVALID_INPUT";
case HIPRTC_ERROR_INVALID_PROGRAM:
return "HIPRTC_ERROR_INVALID_PROGRAM";
case HIPRTC_ERROR_INVALID_OPTION:
return "HIPRTC_ERROR_INVALID_OPTION";
case HIPRTC_ERROR_COMPILATION:
return "HIPRTC_ERROR_COMPILATION";
case HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE:
return "HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE";
case HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION:
return "HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION";
case HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION:
return "HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION";
case HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID:
return "HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID";
case HIPRTC_ERROR_INTERNAL_ERROR:
return "HIPRTC_ERROR_INTERNAL_ERROR";
default:
return nullptr;
};
ShouldNotReachHere();
return nullptr;
}
hiprtcResult hiprtcCreateProgram(hiprtcProgram* prog, const char* src, const char* name,
int numHeaders, const char** headers, const char** headerNames) {
HIPRTC_INIT_API(prog, src, name, numHeaders, headers, headerNames);
if (prog == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_PROGRAM);
}
if (numHeaders < 0) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
if (numHeaders && (headers == nullptr || headerNames == nullptr)) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
amd::Program* program = new amd::Program(*hip::getCurrentDevice()->asContext(), src, amd::Program::HIP);
if (program == NULL) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
if (CL_SUCCESS != program->addDeviceProgram(*hip::getCurrentDevice()->devices()[0])) {
program->release();
HIPRTC_RETURN(HIPRTC_ERROR_PROGRAM_CREATION_FAILURE);
}
ProgramState::instance().createProgramHeaders(program, numHeaders, headers, headerNames);
*prog = reinterpret_cast<hiprtcProgram>(as_cl(program));
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcCompileProgram(hiprtcProgram prog, int numOptions, const char** options) {
// FIXME[skudchad] Add headers to amd::Program::build and device::Program::build,
// pass the saved from ProgramState to amd::Program::build
HIPRTC_INIT_API(prog, numOptions, options);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
std::ostringstream ostrstr;
std::vector<const char*> oarr(&options[0], &options[numOptions]);
std::copy(oarr.begin(), oarr.end(), std::ostream_iterator<std::string>(ostrstr, " "));
ostrstr.str().append(" -DHIP_VERSION_MAJOR=").append(std::to_string(HIP_VERSION_MAJOR));
ostrstr.str().append(" -DHIP_VERSION_MINOR=").append(std::to_string(HIP_VERSION_MINOR));
std::vector<amd::Device*> devices{hip::getCurrentDevice()->devices()[0]};
if (CL_SUCCESS != program->build(devices, ostrstr.str().c_str(), nullptr, nullptr)) {
HIPRTC_RETURN(HIPRTC_ERROR_COMPILATION);
}
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcAddNameExpression(hiprtcProgram prog, const char* name_expression) {
HIPRTC_INIT_API(prog, name_expression);
if (name_expression == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
uint32_t id = ProgramState::instance().addNameExpression(name_expression);
const auto var{"__hiprtc_" + std::to_string(id)};
const auto code{"\nextern \"C\" constexpr auto " + var + " = " + name_expression + ';'};
program->appendToSource(code.c_str());
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetLoweredName(hiprtcProgram prog, const char* name_expression,
const char** loweredName) {
HIPRTC_INIT_API(prog, name_expression, loweredName);
if (name_expression == nullptr || loweredName == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
device::Program* dev_program
= program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
auto it = ProgramState::instance().nameExpresssion_.find(name_expression);
if (it == ProgramState::instance().nameExpresssion_.end()) {
return HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID;
}
std::string strippedName = it->second.first;
std::vector<std::string> mangledNames;
if (!dev_program->getLoweredNames(&mangledNames)) {
HIPRTC_RETURN(HIPRTC_ERROR_COMPILATION);
}
for (auto &name : mangledNames) {
std::string demangledName = handleMangledName(name);
if (demangledName == strippedName) {
it->second.second.assign(name);
}
}
*loweredName = it->second.second.c_str();
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcDestroyProgram(hiprtcProgram* prog) {
HIPRTC_INIT_API(prog);
if (prog == NULL) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
// Release program. hiprtcProgram is a double pointer so free *prog
amd::Program* program = as_amd(reinterpret_cast<cl_program>(*prog));
program->release();
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetCode(hiprtcProgram prog, char* binaryMem) {
HIPRTC_INIT_API(prog, binaryMem);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
const device::Program::binary_t& binary =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0])->binary();
::memcpy(binaryMem, binary.first, binary.second);
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetCodeSize(hiprtcProgram prog, size_t* binarySizeRet) {
HIPRTC_INIT_API(prog, binarySizeRet);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
*binarySizeRet =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0])->binary().second;
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetProgramLog(hiprtcProgram prog, char* dst) {
HIPRTC_INIT_API(prog, dst);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
const device::Program* devProgram =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
auto log = program->programLog() + devProgram->buildLog().c_str();
log.copy(dst, log.size());
dst[log.size()] = '\0';
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetProgramLogSize(hiprtcProgram prog, size_t* logSizeRet) {
HIPRTC_INIT_API(prog, logSizeRet);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
const device::Program* devProgram =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
auto log = program->programLog() + devProgram->buildLog().c_str();
*logSizeRet = log.size() + 1;
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcVersion(int* major, int* minor) {
HIPRTC_INIT_API(major, minor);
if (major == nullptr || minor == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
*major = 9;
*minor = 0;
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
<commit_msg>Change HIPRTC Version to 9.0<commit_after>/* Copyright (c) 2015-present Advanced Micro Devices, Inc.
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 <hip/hip_runtime.h>
#include "hiprtc_internal.hpp"
#include <hip/hiprtc.h>
#include "platform/program.hpp"
namespace hiprtc {
thread_local hiprtcResult g_lastRtcError = HIPRTC_SUCCESS;
}
class ProgramState {
amd::Monitor lock_;
private:
static ProgramState* programState_;
ProgramState() : lock_("Guards program state") {}
~ProgramState() {}
public:
std::unordered_map<amd::Program*,
std::pair<std::vector<std::string>, std::vector<std::string>>> progHeaders_;
std::map<std::string, std::pair<std::string, std::string>> nameExpresssion_;
static ProgramState& instance();
void createProgramHeaders(amd::Program* program, int numHeaders,
const char** headers, const char** headerNames);
void getProgramHeaders(amd::Program* program, int* numHeaders, char** headers, char ** headerNames);
uint32_t addNameExpression(const char* name_expression);
char* getLoweredName(const char* name_expression);
};
ProgramState* ProgramState::programState_ = nullptr;
ProgramState& ProgramState::instance() {
if (programState_ == nullptr) {
programState_ = new ProgramState;
}
return *programState_;
}
void ProgramState::createProgramHeaders(amd::Program* program, int numHeaders,
const char** headers, const char** headerNames) {
amd::ScopedLock lock(lock_);
std::vector<std::string> vHeaderNames;
std::vector<std::string> vHeaders;
for (auto i = 0; i != numHeaders; ++i) {
vHeaders.emplace_back(headers[i]);
vHeaderNames.emplace_back(headerNames[i]);
progHeaders_[program] = std::make_pair(std::move(vHeaders), std::move(vHeaderNames));
}
}
void ProgramState::getProgramHeaders(amd::Program* program, int* numHeaders,
char** headers, char ** headerNames) {
amd::ScopedLock lock(lock_);
const auto it = progHeaders_.find(program);
if (it != progHeaders_.cend()) {
*numHeaders = it->second.first.size();
*headers = reinterpret_cast<char*>(it->second.first.data());
*headerNames = reinterpret_cast<char*>(it->second.second.data());
}
}
uint32_t ProgramState::addNameExpression(const char* name_expression) {
amd::ScopedLock lock(lock_);
// Strip clean of any '(' or ')' or '&'
std::string strippedName(name_expression);
if (strippedName.back() == ')') {
strippedName.pop_back();
strippedName.erase(0, strippedName.find('('));
}
if (strippedName.front() == '&') {
strippedName.erase(0, 1);
}
auto it = nameExpresssion_.find(name_expression);
if (it == nameExpresssion_.end()) {
nameExpresssion_.insert(std::pair<std::string, std::pair<std::string, std::string>>
(name_expression, std::make_pair(strippedName,"")));
}
return nameExpresssion_.size();
}
char* demangle(const char* loweredName) {
if (!loweredName) {
return nullptr;
}
#if HIPRTC_USE_CXXABI || __linux__
int status = 0;
char* demangledName = abi::__cxa_demangle(loweredName, nullptr, nullptr, &status);
if (status != 0) {
return nullptr;
}
#elif defined(_WIN32)
char* demangledName = (char*)malloc(UNDECORATED_SIZE);
if (!UnDecorateSymbolName(loweredName, demangledName,
UNDECORATED_SIZE/ sizeof(*demangledName), UNDNAME_COMPLETE))
{
free(demangledName);
return nullptr;
}
#else
#error "Only Linux and Windows are supported"
#endif // HIPRTC_USE_CXXABI || __linux__
return demangledName;
}
static std::string handleMangledName(std::string name) {
std::string loweredName;
char* demangled = demangle(name.c_str());
loweredName.assign(demangled == nullptr ? std::string() : demangled);
free(demangled);
if (loweredName.empty()) {
return name;
}
if (loweredName.find(".kd") != std::string::npos) {
return {};
}
if (loweredName.find("void ") == 0) {
loweredName.erase(0, strlen("void "));
}
auto dx{loweredName.find_first_of("(<")};
if (dx == std::string::npos) {
return loweredName;
}
if (loweredName[dx] == '<') {
uint32_t count = 1;
do {
++dx;
count += (loweredName[dx] == '<') ? 1 : ((loweredName[dx] == '>') ? -1 : 0);
} while (count);
loweredName.erase(++dx);
} else {
loweredName.erase(dx);
}
return loweredName;
}
const char* hiprtcGetErrorString(hiprtcResult x) {
switch (x) {
case HIPRTC_SUCCESS:
return "HIPRTC_SUCCESS";
case HIPRTC_ERROR_OUT_OF_MEMORY:
return "HIPRTC_ERROR_OUT_OF_MEMORY";
case HIPRTC_ERROR_PROGRAM_CREATION_FAILURE:
return "HIPRTC_ERROR_PROGRAM_CREATION_FAILURE";
case HIPRTC_ERROR_INVALID_INPUT:
return "HIPRTC_ERROR_INVALID_INPUT";
case HIPRTC_ERROR_INVALID_PROGRAM:
return "HIPRTC_ERROR_INVALID_PROGRAM";
case HIPRTC_ERROR_INVALID_OPTION:
return "HIPRTC_ERROR_INVALID_OPTION";
case HIPRTC_ERROR_COMPILATION:
return "HIPRTC_ERROR_COMPILATION";
case HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE:
return "HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE";
case HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION:
return "HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION";
case HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION:
return "HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION";
case HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID:
return "HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID";
case HIPRTC_ERROR_INTERNAL_ERROR:
return "HIPRTC_ERROR_INTERNAL_ERROR";
default:
return nullptr;
};
ShouldNotReachHere();
return nullptr;
}
hiprtcResult hiprtcCreateProgram(hiprtcProgram* prog, const char* src, const char* name,
int numHeaders, const char** headers, const char** headerNames) {
HIPRTC_INIT_API(prog, src, name, numHeaders, headers, headerNames);
if (prog == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_PROGRAM);
}
if (numHeaders < 0) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
if (numHeaders && (headers == nullptr || headerNames == nullptr)) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
amd::Program* program = new amd::Program(*hip::getCurrentDevice()->asContext(), src, amd::Program::HIP);
if (program == NULL) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
if (CL_SUCCESS != program->addDeviceProgram(*hip::getCurrentDevice()->devices()[0])) {
program->release();
HIPRTC_RETURN(HIPRTC_ERROR_PROGRAM_CREATION_FAILURE);
}
ProgramState::instance().createProgramHeaders(program, numHeaders, headers, headerNames);
*prog = reinterpret_cast<hiprtcProgram>(as_cl(program));
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcCompileProgram(hiprtcProgram prog, int numOptions, const char** options) {
// FIXME[skudchad] Add headers to amd::Program::build and device::Program::build,
// pass the saved from ProgramState to amd::Program::build
HIPRTC_INIT_API(prog, numOptions, options);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
std::ostringstream ostrstr;
std::vector<const char*> oarr(&options[0], &options[numOptions]);
std::copy(oarr.begin(), oarr.end(), std::ostream_iterator<std::string>(ostrstr, " "));
ostrstr.str().append(" -DHIP_VERSION_MAJOR=9");
ostrstr.str().append(" -DHIP_VERSION_MINOR=0");
std::vector<amd::Device*> devices{hip::getCurrentDevice()->devices()[0]};
if (CL_SUCCESS != program->build(devices, ostrstr.str().c_str(), nullptr, nullptr)) {
HIPRTC_RETURN(HIPRTC_ERROR_COMPILATION);
}
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcAddNameExpression(hiprtcProgram prog, const char* name_expression) {
HIPRTC_INIT_API(prog, name_expression);
if (name_expression == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
uint32_t id = ProgramState::instance().addNameExpression(name_expression);
const auto var{"__hiprtc_" + std::to_string(id)};
const auto code{"\nextern \"C\" constexpr auto " + var + " = " + name_expression + ';'};
program->appendToSource(code.c_str());
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetLoweredName(hiprtcProgram prog, const char* name_expression,
const char** loweredName) {
HIPRTC_INIT_API(prog, name_expression, loweredName);
if (name_expression == nullptr || loweredName == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
device::Program* dev_program
= program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
auto it = ProgramState::instance().nameExpresssion_.find(name_expression);
if (it == ProgramState::instance().nameExpresssion_.end()) {
return HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID;
}
std::string strippedName = it->second.first;
std::vector<std::string> mangledNames;
if (!dev_program->getLoweredNames(&mangledNames)) {
HIPRTC_RETURN(HIPRTC_ERROR_COMPILATION);
}
for (auto &name : mangledNames) {
std::string demangledName = handleMangledName(name);
if (demangledName == strippedName) {
it->second.second.assign(name);
}
}
*loweredName = it->second.second.c_str();
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcDestroyProgram(hiprtcProgram* prog) {
HIPRTC_INIT_API(prog);
if (prog == NULL) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
// Release program. hiprtcProgram is a double pointer so free *prog
amd::Program* program = as_amd(reinterpret_cast<cl_program>(*prog));
program->release();
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetCode(hiprtcProgram prog, char* binaryMem) {
HIPRTC_INIT_API(prog, binaryMem);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
const device::Program::binary_t& binary =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0])->binary();
::memcpy(binaryMem, binary.first, binary.second);
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetCodeSize(hiprtcProgram prog, size_t* binarySizeRet) {
HIPRTC_INIT_API(prog, binarySizeRet);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
*binarySizeRet =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0])->binary().second;
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetProgramLog(hiprtcProgram prog, char* dst) {
HIPRTC_INIT_API(prog, dst);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
const device::Program* devProgram =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
auto log = program->programLog() + devProgram->buildLog().c_str();
log.copy(dst, log.size());
dst[log.size()] = '\0';
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcGetProgramLogSize(hiprtcProgram prog, size_t* logSizeRet) {
HIPRTC_INIT_API(prog, logSizeRet);
amd::Program* program = as_amd(reinterpret_cast<cl_program>(prog));
const device::Program* devProgram =
program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
auto log = program->programLog() + devProgram->buildLog().c_str();
*logSizeRet = log.size() + 1;
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
hiprtcResult hiprtcVersion(int* major, int* minor) {
HIPRTC_INIT_API(major, minor);
if (major == nullptr || minor == nullptr) {
HIPRTC_RETURN(HIPRTC_ERROR_INVALID_INPUT);
}
*major = 9;
*minor = 0;
HIPRTC_RETURN(HIPRTC_SUCCESS);
}
<|endoftext|> |
<commit_before>
// Copyright (c) 2012, 2013 Pierre MOULON.
// 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 <cstdlib>
#include "software/SfM/SfMIncrementalEngine.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "openMVG/system/timer.hpp"
using namespace openMVG;
bool computeIndexFromImageNames(const std::string& sMatchesDir, const std::pair<std::string,std::string>& initialPairName, std::pair<size_t, size_t>& initialPairIndex)
{
const std::string sListsFile = stlplus::create_filespec(sMatchesDir, "lists.txt" );
if (!stlplus::is_file(sListsFile)) {
std::cerr << "Cannont access input file \""<< sListsFile << "\"" << std::endl;
return false;
}
std::vector<std::string> vec_camImageName;
if (!openMVG::SfMIO::loadImageList(vec_camImageName, sListsFile, false))
{
std::cerr << "\nEmpty or invalid image list." << std::endl;
return false;
}
std::vector<std::string>::const_iterator imageName;
imageName = find(vec_camImageName.begin(), vec_camImageName.end(), initialPairName.first);
if(imageName == vec_camImageName.end())
{
std::cerr << "\nCannot access image \""<< *imageName << "\"" << std::endl;
return false;
}
initialPairIndex.first = std::distance<std::vector<std::string>::const_iterator>(vec_camImageName.begin(), imageName);
imageName = find(vec_camImageName.begin(), vec_camImageName.end(), initialPairName.second);
if(imageName == vec_camImageName.end())
{
std::cerr << "\nCannot access image \""<< *imageName << "\"" << std::endl;
return false;
}
initialPairIndex.second = std::distance<std::vector<std::string>::const_iterator>(vec_camImageName.begin(), imageName);
return true;
}
int main(int argc, char **argv)
{
using namespace std;
std::cout << "Incremental reconstruction" << std::endl
<< " Perform incremental SfM (Initial Pair Essential + Resection)." << std::endl
<< std::endl;
CmdLine cmd;
std::string sImaDirectory;
std::string sMatchesDir;
std::string sOutDir = "";
bool bPmvsExport = false;
bool bRefinePPandDisto = true;
bool bRefineFocal = true;
bool bColoredPointCloud = false;
std::pair<std::string,std::string> initialPair;
cmd.add( make_option('i', sImaDirectory, "imadir") );
cmd.add( make_option('m', sMatchesDir, "matchdir") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('p', bPmvsExport, "pmvs") );
cmd.add( make_option('a', initialPair.first, "initialPairA") );
cmd.add( make_option('b', initialPair.second, "initialPairB") );
cmd.add( make_option('c', bColoredPointCloud, "coloredPointCloud") );
cmd.add( make_option('d', bRefinePPandDisto, "refinePPandDisto") );
cmd.add( make_option('f', bRefineFocal, "refineFocal") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--imadir PATH] \n"
<< "[-m|--matchdir PATH] \n"
<< "[-o|--outdir PATH] \n"
<< "[-p|--pmvs 0 or 1] \n"
<< "[-a|--initialPairA NAME] \n"
<< "[-b|--initialPairB NAME] \n"
<< "[-c|--coloredPointCloud 0(default) or 1]\n"
<< "[-d|--refinePPandDisto \n"
<< "\t 0-> refine only the Focal,\n"
<< "\t 1-> refine Focal, Principal point and radial distortion factors.] \n"
<< "[-f|--refineFocal \n"
<< "\t 0-> refine only Principal point and radial distortion,\n"
<< "\t 1-> refine Focal, Principal point and radial distortion ] \n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty()) {
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
stlplus::folder_create(sOutDir);
//---------------------------------------
// Incremental reconstruction process
//---------------------------------------
openMVG::Timer timer;
IncrementalReconstructionEngine to3DEngine(sImaDirectory,
sMatchesDir,
sOutDir,
true);
std::pair<size_t, size_t> initialPairIndex;
if(!computeIndexFromImageNames(sMatchesDir, initialPair, initialPairIndex))
return EXIT_FAILURE;
to3DEngine.setInitialPair(initialPairIndex);
to3DEngine.setIfRefinePrincipalPointAndRadialDisto(bRefinePPandDisto);
to3DEngine.setIfRefineFocal(bRefineFocal);
if (to3DEngine.Process())
{
clock_t timeEnd = clock();
std::cout << std::endl << " Ac-Sfm took (s): " << timer.elapsed() << "." << std::endl;
const reconstructorHelper & reconstructorHelperRef = to3DEngine.refToReconstructorHelper();
std::vector<Vec3> vec_tracksColor;
if (bColoredPointCloud)
{
// Compute the color of each track
to3DEngine.ColorizeTracks(vec_tracksColor);
}
reconstructorHelperRef.exportToPly(
stlplus::create_filespec(sOutDir, "FinalColorized", ".ply"),
bColoredPointCloud ? &vec_tracksColor : NULL);
// Export to openMVG format
std::cout << std::endl << "Export 3D scene to openMVG format" << std::endl
<< " -- Point cloud color: " << (bColoredPointCloud ? "ON" : "OFF") << std::endl;
if (!reconstructorHelperRef.ExportToOpenMVGFormat(
stlplus::folder_append_separator(sOutDir) + "SfM_output",
to3DEngine.getFilenamesVector(),
sImaDirectory,
to3DEngine.getImagesSize(),
to3DEngine.getTracks(),
bColoredPointCloud ? &vec_tracksColor : NULL,
true,
std::string("generated by the Sequential OpenMVG Calibration Engine")))
{
std::cerr << "Error while saving the scene." << std::endl;
}
// Manage export data to desired format
// -> PMVS
if (bPmvsExport) {
std::cout << std::endl << "Export 3D scene to PMVS format" << std::endl;
reconstructorHelperRef.exportToPMVSFormat(
stlplus::folder_append_separator(sOutDir) + "PMVS",
to3DEngine.getFilenamesVector(),
sImaDirectory);
}
return EXIT_SUCCESS;
}
else
{
std::cerr << "\n Something goes wrong in the Structure from Motion process" << std::endl;
}
return EXIT_FAILURE;
}
<commit_msg>Update main_IncrementalSfM.cpp<commit_after>
// Copyright (c) 2012, 2013 Pierre MOULON.
// 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 <cstdlib>
#include "software/SfM/SfMIncrementalEngine.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "openMVG/system/timer.hpp"
using namespace openMVG;
bool computeIndexFromImageNames(const std::string& sMatchesDir, const std::pair<std::string,std::string>& initialPairName, std::pair<size_t, size_t>& initialPairIndex)
{
const std::string sListsFile = stlplus::create_filespec(sMatchesDir, "lists.txt" );
if (!stlplus::is_file(sListsFile)) {
std::cerr << "\nCannot access input file \""<< sListsFile << "\"" << std::endl;
return false;
}
std::vector<std::string> vec_camImageName;
if (!openMVG::SfMIO::loadImageList(vec_camImageName, sListsFile, false))
{
std::cerr << "\nEmpty or invalid image list." << std::endl;
return false;
}
std::vector<std::string>::const_iterator imageName;
imageName = find(vec_camImageName.begin(), vec_camImageName.end(), initialPairName.first);
if(imageName == vec_camImageName.end())
{
std::cerr << "\nCannot access image \""<< *imageName << "\"" << std::endl;
return false;
}
initialPairIndex.first = std::distance<std::vector<std::string>::const_iterator>(vec_camImageName.begin(), imageName);
imageName = find(vec_camImageName.begin(), vec_camImageName.end(), initialPairName.second);
if(imageName == vec_camImageName.end())
{
std::cerr << "\nCannot access image \""<< *imageName << "\"" << std::endl;
return false;
}
initialPairIndex.second = std::distance<std::vector<std::string>::const_iterator>(vec_camImageName.begin(), imageName);
return true;
}
int main(int argc, char **argv)
{
using namespace std;
std::cout << "Incremental reconstruction" << std::endl
<< " Perform incremental SfM (Initial Pair Essential + Resection)." << std::endl
<< std::endl;
CmdLine cmd;
std::string sImaDirectory;
std::string sMatchesDir;
std::string sOutDir = "";
bool bPmvsExport = false;
bool bRefinePPandDisto = true;
bool bRefineFocal = true;
bool bColoredPointCloud = false;
std::pair<std::string,std::string> initialPair;
cmd.add( make_option('i', sImaDirectory, "imadir") );
cmd.add( make_option('m', sMatchesDir, "matchdir") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('p', bPmvsExport, "pmvs") );
cmd.add( make_option('a', initialPair.first, "initialPairA") );
cmd.add( make_option('b', initialPair.second, "initialPairB") );
cmd.add( make_option('c', bColoredPointCloud, "coloredPointCloud") );
cmd.add( make_option('d', bRefinePPandDisto, "refinePPandDisto") );
cmd.add( make_option('f', bRefineFocal, "refineFocal") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--imadir PATH] \n"
<< "[-m|--matchdir PATH] \n"
<< "[-o|--outdir PATH] \n"
<< "[-p|--pmvs 0 or 1] \n"
<< "[-a|--initialPairA NAME] \n"
<< "[-b|--initialPairB NAME] \n"
<< "[-c|--coloredPointCloud 0(default) or 1]\n"
<< "[-d|--refinePPandDisto \n"
<< "\t 0-> refine only the Focal,\n"
<< "\t 1-> refine Focal, Principal point and radial distortion factors.] \n"
<< "[-f|--refineFocal \n"
<< "\t 0-> refine only Principal point and radial distortion,\n"
<< "\t 1-> refine Focal, Principal point and radial distortion ] \n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty()) {
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
stlplus::folder_create(sOutDir);
//---------------------------------------
// Incremental reconstruction process
//---------------------------------------
openMVG::Timer timer;
IncrementalReconstructionEngine to3DEngine(sImaDirectory,
sMatchesDir,
sOutDir,
true);
std::pair<size_t, size_t> initialPairIndex;
if(!computeIndexFromImageNames(sMatchesDir, initialPair, initialPairIndex))
return EXIT_FAILURE;
to3DEngine.setInitialPair(initialPairIndex);
to3DEngine.setIfRefinePrincipalPointAndRadialDisto(bRefinePPandDisto);
to3DEngine.setIfRefineFocal(bRefineFocal);
if (to3DEngine.Process())
{
clock_t timeEnd = clock();
std::cout << std::endl << " Ac-Sfm took (s): " << timer.elapsed() << "." << std::endl;
const reconstructorHelper & reconstructorHelperRef = to3DEngine.refToReconstructorHelper();
std::vector<Vec3> vec_tracksColor;
if (bColoredPointCloud)
{
// Compute the color of each track
to3DEngine.ColorizeTracks(vec_tracksColor);
}
reconstructorHelperRef.exportToPly(
stlplus::create_filespec(sOutDir, "FinalColorized", ".ply"),
bColoredPointCloud ? &vec_tracksColor : NULL);
// Export to openMVG format
std::cout << std::endl << "Export 3D scene to openMVG format" << std::endl
<< " -- Point cloud color: " << (bColoredPointCloud ? "ON" : "OFF") << std::endl;
if (!reconstructorHelperRef.ExportToOpenMVGFormat(
stlplus::folder_append_separator(sOutDir) + "SfM_output",
to3DEngine.getFilenamesVector(),
sImaDirectory,
to3DEngine.getImagesSize(),
to3DEngine.getTracks(),
bColoredPointCloud ? &vec_tracksColor : NULL,
true,
std::string("generated by the Sequential OpenMVG Calibration Engine")))
{
std::cerr << "Error while saving the scene." << std::endl;
}
// Manage export data to desired format
// -> PMVS
if (bPmvsExport) {
std::cout << std::endl << "Export 3D scene to PMVS format" << std::endl;
reconstructorHelperRef.exportToPMVSFormat(
stlplus::folder_append_separator(sOutDir) + "PMVS",
to3DEngine.getFilenamesVector(),
sImaDirectory);
}
return EXIT_SUCCESS;
}
else
{
std::cerr << "\n Something goes wrong in the Structure from Motion process" << std::endl;
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include <chrono>
#include <algorithm>
#include <vector>
#include <cassert>
#include "foo.h"
#include "util.h"
static double
iterateTest(std::vector<Foo*> &foo_ptrs)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (auto f : foo_ptrs) {
f->update();
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
batchedIterateTest(std::vector<std::pair<Foo*,bool>> &foo_ptrs)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (auto f : foo_ptrs) {
f.first->update();
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
// Sets each Foo*'s bool to false, so it will be removed when batch adding
static double
batchedRemoveTest(std::vector<std::pair<Foo*,bool>> &foo_ptrs,
const std::vector<Foo*> &to_remove)
{
auto compare = [](std::pair<Foo*,bool> f1, Foo *f2) {
return f1.first < f2; };
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_remove) {
auto iter = std::lower_bound(foo_ptrs.begin(), foo_ptrs.end(),
f, compare);
iter->second = false;
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
sortedRemoveTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_remove)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_remove) {
auto iter = std::lower_bound(foo_ptrs.begin(), foo_ptrs.end(), f);
foo_ptrs.erase(iter);
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
removeTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_remove)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_remove) {
auto iter = std::find(foo_ptrs.begin(), foo_ptrs.end(), f);
*iter = foo_ptrs.back();
foo_ptrs.pop_back();
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
sortedAddTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_add)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_add) {
auto iter = std::lower_bound(foo_ptrs.begin(), foo_ptrs.end(), f);
foo_ptrs.insert(iter, f);
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
// Adds all Foo* to end of vector then does one sort, which also places
// Foo* with false flag to end and removes all at once.
static double
batchedAddTest(std::vector<std::pair<Foo*,bool>> &foo_ptrs,
const std::vector<Foo*> &to_add)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_add) {
foo_ptrs.push_back(std::make_pair(f, true));
}
auto compare = [](std::pair<Foo*,bool> f1, std::pair<Foo*,bool> f2) {
if (f1.second == false) {
return false;
} else if (f2.second == false) {
return true;
} else {
return f1.first < f2.first;
}
};
std::sort(foo_ptrs.begin(), foo_ptrs.end(), compare);
while (foo_ptrs.back().second == false) {
foo_ptrs.pop_back();
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
addTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_add)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_add) {
foo_ptrs.push_back(f);
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
TestResult
vectorTest(int iters, int num_elements, bool sorted, int num_add_remove,
bool batched)
{
using std::vector;
using std::pair;
using std::make_pair;
const int NUM_EACH_TYPE = num_elements / 4;
const int NUM_FOOS = NUM_EACH_TYPE * 4;
vector<Foo_A> foo_a_pool(NUM_EACH_TYPE);
vector<Foo_B> foo_b_pool(NUM_EACH_TYPE);
vector<Foo_C> foo_c_pool(NUM_EACH_TYPE);
vector<Foo_D> foo_d_pool(NUM_EACH_TYPE);
vector<Foo*> foo_ptrs;
// For batched tests, each Foo* has a bool to tell if it should be removed
vector<pair<Foo*,bool>> foo_ptrs2;
foo_ptrs.reserve(NUM_FOOS);
foo_ptrs2.reserve(NUM_FOOS+num_add_remove);
for (int i = 0; i < NUM_EACH_TYPE; ++i) {
foo_ptrs.push_back(&foo_a_pool[i]);
foo_ptrs.push_back(&foo_b_pool[i]);
foo_ptrs.push_back(&foo_c_pool[i]);
foo_ptrs.push_back(&foo_d_pool[i]);
}
if (sorted) {
std::sort(foo_ptrs.begin(), foo_ptrs.end());
}
for (auto f : foo_ptrs) {
foo_ptrs2.push_back(make_pair(f, true));
}
vector<double> iterate_times(iters);
vector<double> add_times(iters);
vector<double> remove_times(iters);
vector<Foo*> rand_foos;
rand_foos.reserve(num_add_remove);
if (sorted) {
if (batched) {
for (int i = 0; i < iters; i++) {
iterate_times[i] = batchedIterateTest(foo_ptrs2);
getRandElems(foo_ptrs, rand_foos, num_add_remove);
remove_times[i] = batchedRemoveTest(foo_ptrs2, rand_foos);
add_times[i] = batchedAddTest(foo_ptrs2, rand_foos);
}
} else {
for (int i = 0; i < iters; i++) {
iterate_times[i] = iterateTest(foo_ptrs);
getRandElems(foo_ptrs, rand_foos, num_add_remove);
remove_times[i] = sortedRemoveTest(foo_ptrs, rand_foos);
add_times[i] = sortedAddTest(foo_ptrs, rand_foos);
}
}
} else {
for (int i = 0; i < iters; i++) {
iterate_times[i] = iterateTest(foo_ptrs);
getRandElems(foo_ptrs, rand_foos, num_add_remove);
remove_times[i] = removeTest(foo_ptrs, rand_foos);
add_times[i] = addTest(foo_ptrs, rand_foos);
}
}
TestResult result = { TimeResult(iterate_times),
TimeResult(add_times),
TimeResult(remove_times) };
return result;
}
<commit_msg>Changed batchAddTest to use a merge sort instead of quicksort<commit_after>#include <chrono>
#include <algorithm>
#include <vector>
#include <cassert>
#include "foo.h"
#include "util.h"
static double
iterateTest(std::vector<Foo*> &foo_ptrs)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (auto f : foo_ptrs) {
f->update();
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
batchedIterateTest(std::vector<std::pair<Foo*,bool>> &foo_ptrs)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (auto f : foo_ptrs) {
f.first->update();
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
// Sets each Foo*'s bool to false, so it will be removed when batch adding
static double
batchedRemoveTest(std::vector<std::pair<Foo*,bool>> &foo_ptrs,
const std::vector<Foo*> &to_remove)
{
auto compare = [](std::pair<Foo*,bool> f1, Foo *f2) {
return f1.first < f2; };
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_remove) {
auto iter = std::lower_bound(foo_ptrs.begin(), foo_ptrs.end(),
f, compare);
iter->second = false;
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
sortedRemoveTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_remove)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_remove) {
auto iter = std::lower_bound(foo_ptrs.begin(), foo_ptrs.end(), f);
foo_ptrs.erase(iter);
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
removeTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_remove)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_remove) {
auto iter = std::find(foo_ptrs.begin(), foo_ptrs.end(), f);
*iter = foo_ptrs.back();
foo_ptrs.pop_back();
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
sortedAddTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_add)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_add) {
auto iter = std::lower_bound(foo_ptrs.begin(), foo_ptrs.end(), f);
foo_ptrs.insert(iter, f);
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
// Adds all Foo* to end of vector then does one sort, which also places
// Foo* with false flag to end and removes all at once.
static double
batchedAddTest(std::vector<std::pair<Foo*,bool>> &foo_ptrs,
const std::vector<Foo*> &to_add)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_add) {
foo_ptrs.push_back(std::make_pair(f, true));
}
std::vector<std::pair<Foo*,bool>> cpy_buff(foo_ptrs.size());
const auto new_begin_it = foo_ptrs.end() - to_add.size();
auto compare = [](std::pair<Foo*,bool> f1, std::pair<Foo*,bool> f2) {
return f1.first < f2.first;
};
std::sort(new_begin_it, foo_ptrs.end(), compare);
auto it = foo_ptrs.begin();
auto new_it = new_begin_it;
auto cpy_it = cpy_buff.begin();
const auto end_it = foo_ptrs.end();
while (it != new_begin_it && new_it != end_it) {
if (it->second == false) {
++it;
cpy_buff.pop_back();
continue;
} else if (it->first < new_it->first) {
*cpy_it = *it;
++it;
} else {
*cpy_it = *new_it;
++new_it;
}
++cpy_it;
}
if (it != new_begin_it) {
while (it != new_begin_it) {
if (it->second == false) {
++it;
cpy_buff.pop_back();
continue;
}
*cpy_it = *it;
++it;
++cpy_it;
}
} else {
while (new_it != end_it) {
*cpy_it = *new_it;
++new_it;
++cpy_it;
}
}
foo_ptrs = std::move(cpy_buff);
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
static double
addTest(std::vector<Foo*> &foo_ptrs, const std::vector<Foo*> &to_add)
{
namespace c = std::chrono;
auto start = c::high_resolution_clock::now();
for (Foo *f : to_add) {
foo_ptrs.push_back(f);
}
auto end = c::high_resolution_clock::now();
auto d = c::duration<double, c::milliseconds::period>(end-start);
return d.count();
}
TestResult
vectorTest(int iters, int num_elements, bool sorted, int num_add_remove,
bool batched)
{
using std::vector;
using std::pair;
using std::make_pair;
const int NUM_EACH_TYPE = num_elements / 4;
const int NUM_FOOS = NUM_EACH_TYPE * 4;
vector<Foo_A> foo_a_pool(NUM_EACH_TYPE);
vector<Foo_B> foo_b_pool(NUM_EACH_TYPE);
vector<Foo_C> foo_c_pool(NUM_EACH_TYPE);
vector<Foo_D> foo_d_pool(NUM_EACH_TYPE);
vector<Foo*> foo_ptrs;
// For batched tests, each Foo* has a bool to tell if it should be removed
vector<pair<Foo*,bool>> foo_ptrs2;
foo_ptrs.reserve(NUM_FOOS);
foo_ptrs2.reserve(NUM_FOOS+num_add_remove);
for (int i = 0; i < NUM_EACH_TYPE; ++i) {
foo_ptrs.push_back(&foo_a_pool[i]);
foo_ptrs.push_back(&foo_b_pool[i]);
foo_ptrs.push_back(&foo_c_pool[i]);
foo_ptrs.push_back(&foo_d_pool[i]);
}
if (sorted) {
std::sort(foo_ptrs.begin(), foo_ptrs.end());
}
for (auto f : foo_ptrs) {
foo_ptrs2.push_back(make_pair(f, true));
}
vector<double> iterate_times(iters);
vector<double> add_times(iters);
vector<double> remove_times(iters);
vector<Foo*> rand_foos;
rand_foos.reserve(num_add_remove);
if (sorted) {
if (batched) {
for (int i = 0; i < iters; i++) {
iterate_times[i] = batchedIterateTest(foo_ptrs2);
getRandElems(foo_ptrs, rand_foos, num_add_remove);
remove_times[i] = batchedRemoveTest(foo_ptrs2, rand_foos);
add_times[i] = batchedAddTest(foo_ptrs2, rand_foos);
}
} else {
for (int i = 0; i < iters; i++) {
iterate_times[i] = iterateTest(foo_ptrs);
getRandElems(foo_ptrs, rand_foos, num_add_remove);
remove_times[i] = sortedRemoveTest(foo_ptrs, rand_foos);
add_times[i] = sortedAddTest(foo_ptrs, rand_foos);
}
}
} else {
for (int i = 0; i < iters; i++) {
iterate_times[i] = iterateTest(foo_ptrs);
getRandElems(foo_ptrs, rand_foos, num_add_remove);
remove_times[i] = removeTest(foo_ptrs, rand_foos);
add_times[i] = addTest(foo_ptrs, rand_foos);
}
}
TestResult result = { TimeResult(iterate_times),
TimeResult(add_times),
TimeResult(remove_times) };
return result;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "mutation_reader.hh"
#include "memtable.hh"
#include "utils/phased_barrier.hh"
#include <seastar/core/circular_buffer.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/condition-variable.hh>
// in-memory snapshottable mutation source.
// Must be destroyed in a seastar thread.
class memtable_snapshot_source {
schema_ptr _s;
circular_buffer<lw_shared_ptr<memtable>> _memtables;
utils::phased_barrier _apply;
bool _closed = false;
seastar::condition_variable _should_compact;
future<> _compactor;
private:
bool should_compact() const {
return !_closed && _memtables.size() >= 3;
}
lw_shared_ptr<memtable> new_memtable() {
return make_lw_shared<memtable>(_s);
}
lw_shared_ptr<memtable> pending() {
if (_memtables.empty()) {
_memtables.push_back(new_memtable());
on_new_memtable();
}
return _memtables.back();
}
void on_new_memtable() {
if (should_compact()) {
_should_compact.signal();
}
}
void compact() {
if (_memtables.empty()) {
return;
}
auto count = _memtables.size();
auto op = _apply.start();
auto new_mt = make_lw_shared<memtable>(_memtables.back()->schema());
std::vector<mutation_reader> readers;
for (auto&& mt : _memtables) {
readers.push_back(mt->make_reader(new_mt->schema(),
query::full_partition_range,
new_mt->schema()->full_slice(),
default_priority_class(),
nullptr,
streamed_mutation::forwarding::no,
mutation_reader::forwarding::yes));
}
auto&& rd = make_combined_reader(new_mt->schema(), std::move(readers));
consume(rd, [&] (mutation&& m) {
new_mt->apply(std::move(m));
return stop_iteration::no;
}).get();
_memtables.erase(_memtables.begin(), _memtables.begin() + count);
_memtables.push_back(new_mt);
}
public:
memtable_snapshot_source(schema_ptr s)
: _s(s)
, _compactor(seastar::async([this] {
while (!_closed) {
_should_compact.wait().get();
while (should_compact()) {
compact();
}
}
}))
{ }
memtable_snapshot_source(memtable_snapshot_source&&) = delete; // 'this' captured.
~memtable_snapshot_source() {
_closed = true;
_should_compact.broadcast();
_compactor.get();
}
// Must run in a seastar thread
void clear() {
_memtables.erase(_memtables.begin(), _memtables.end());
_apply.advance_and_await().get();
_memtables.erase(_memtables.begin(), _memtables.end());
}
void apply(const mutation& mt) {
pending()->apply(mt);
}
// Must run in a seastar thread
void apply(memtable& mt) {
auto op = _apply.start();
auto new_mt = new_memtable();
new_mt->apply(mt).get();
_memtables.push_back(new_mt);
}
// mt must not change from now on.
void apply(lw_shared_ptr<memtable> mt) {
auto op = _apply.start();
_memtables.push_back(std::move(mt));
on_new_memtable();
}
mutation_source operator()() {
std::vector<mutation_source> src;
for (auto&& mt : _memtables) {
src.push_back(mt->as_data_source());
}
_memtables.push_back(new_memtable()); // so that src won't change any more.
on_new_memtable();
return make_combined_mutation_source(std::move(src));
}
};
<commit_msg>Stop using memtable::make_reader in memtable_snapshot_source.hh<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "mutation_reader.hh"
#include "memtable.hh"
#include "utils/phased_barrier.hh"
#include <seastar/core/circular_buffer.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/condition-variable.hh>
// in-memory snapshottable mutation source.
// Must be destroyed in a seastar thread.
class memtable_snapshot_source {
schema_ptr _s;
circular_buffer<lw_shared_ptr<memtable>> _memtables;
utils::phased_barrier _apply;
bool _closed = false;
seastar::condition_variable _should_compact;
future<> _compactor;
private:
bool should_compact() const {
return !_closed && _memtables.size() >= 3;
}
lw_shared_ptr<memtable> new_memtable() {
return make_lw_shared<memtable>(_s);
}
lw_shared_ptr<memtable> pending() {
if (_memtables.empty()) {
_memtables.push_back(new_memtable());
on_new_memtable();
}
return _memtables.back();
}
void on_new_memtable() {
if (should_compact()) {
_should_compact.signal();
}
}
void compact() {
if (_memtables.empty()) {
return;
}
auto count = _memtables.size();
auto op = _apply.start();
auto new_mt = make_lw_shared<memtable>(_memtables.back()->schema());
std::vector<flat_mutation_reader> readers;
for (auto&& mt : _memtables) {
readers.push_back(mt->make_flat_reader(new_mt->schema(),
query::full_partition_range,
new_mt->schema()->full_slice(),
default_priority_class(),
nullptr,
streamed_mutation::forwarding::no,
mutation_reader::forwarding::yes));
}
auto&& rd = make_combined_reader(new_mt->schema(), std::move(readers));
consume_partitions(rd, [&] (mutation&& m) {
new_mt->apply(std::move(m));
return stop_iteration::no;
}).get();
_memtables.erase(_memtables.begin(), _memtables.begin() + count);
_memtables.push_back(new_mt);
}
public:
memtable_snapshot_source(schema_ptr s)
: _s(s)
, _compactor(seastar::async([this] {
while (!_closed) {
_should_compact.wait().get();
while (should_compact()) {
compact();
}
}
}))
{ }
memtable_snapshot_source(memtable_snapshot_source&&) = delete; // 'this' captured.
~memtable_snapshot_source() {
_closed = true;
_should_compact.broadcast();
_compactor.get();
}
// Must run in a seastar thread
void clear() {
_memtables.erase(_memtables.begin(), _memtables.end());
_apply.advance_and_await().get();
_memtables.erase(_memtables.begin(), _memtables.end());
}
void apply(const mutation& mt) {
pending()->apply(mt);
}
// Must run in a seastar thread
void apply(memtable& mt) {
auto op = _apply.start();
auto new_mt = new_memtable();
new_mt->apply(mt).get();
_memtables.push_back(new_mt);
}
// mt must not change from now on.
void apply(lw_shared_ptr<memtable> mt) {
auto op = _apply.start();
_memtables.push_back(std::move(mt));
on_new_memtable();
}
mutation_source operator()() {
std::vector<mutation_source> src;
for (auto&& mt : _memtables) {
src.push_back(mt->as_data_source());
}
_memtables.push_back(new_memtable()); // so that src won't change any more.
on_new_memtable();
return make_combined_mutation_source(std::move(src));
}
};
<|endoftext|> |
<commit_before>/*
* HyPerLayer.hpp
*
* Created on: Aug 3, 2008
* Author: dcoates
*/
#ifndef HYPERLAYER_HPP_
#define HYPERLAYER_HPP_
#include "../layers/PVLayer.h"
#include "../layers/LayerDataInterface.hpp"
#include "../layers/LIF2.h"
#include "../columns/DataStore.hpp"
#include "../columns/HyPerCol.hpp"
#include "../columns/InterColComm.hpp"
#include "../io/LayerProbe.hpp"
#include "../include/pv_types.h"
#include "../utils/Timer.hpp"
#ifdef PV_USE_OPENCL
#include "../arch/opencl/CLKernel.hpp"
#endif
namespace PV {
// HyPerLayer uses C code from PVLayer.{h,c}, and LIF2.{h,c}
typedef LIF2_params HyPerLayerParams;
/**
* OpenCLLayer collects memory objects for sharing data with OpenCL devices
*/
#ifdef PV_USE_OPENCL
typedef struct {
CLBuffer * V;
CLBuffer * Vth;
CLBuffer * G_E;
CLBuffer * G_I;
CLBuffer * G_IB;
CLBuffer * phi; // collects all three phi buffers and hopefully will go away
CLBuffer * activity;
CLBuffer * prevActivity;
} OpenCLLayer;
#endif
class HyPerLayer : public LayerDataInterface {
protected:
// only subclasses can be constructed directly
HyPerLayer(const char * name, HyPerCol * hc);
virtual int initializeLayerId(int layerId);
#ifdef PV_USE_OPENCL
virtual int initializeThreadBuffers();
virtual int initializeThreadData() = 0;
virtual int initializeThreadKernels() = 0;
#endif
private:
int initialize_base(const char * name, HyPerCol * hc);
public:
virtual ~HyPerLayer() = 0;
static int copyToBuffer(pvdata_t * buf, const pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
static int copyToBuffer(unsigned char * buf, const pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
static int copyFromBuffer(const pvdata_t * buf, pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
static int copyFromBuffer(const unsigned char * buf, pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
// TODO - make protected
PVLayer* clayer;
HyPerCol* parent;
virtual int updateState(float time, float dt);
virtual int updateV();
virtual int setActivity();
virtual int resetPhiBuffers();
int resetBuffer(pvdata_t * buf, int numItems);
virtual int
recvSynapticInput(HyPerConn * conn, PVLayerCube * cube, int neighbor);
virtual int reconstruct(HyPerConn * conn, PVLayerCube * cube);
int initialize(PVLayerType type);
int initFinish();
#ifdef DEPRECATED
PVLayerCube * initBorder(PVLayerCube * border, int borderId);
#endif
int mirrorInteriorToBorder(int whichBorder, PVLayerCube * cube, PVLayerCube * borderCube);
virtual int columnWillAddLayer(InterColComm * comm, int id);
virtual int setParams(int numParams, size_t sizeParams, float * params);
virtual int getParams(int * numParams, float ** params);
virtual int setFuncs(void * initFunc, void * updateFunc);
virtual int publish(InterColComm * comm, float time);
virtual int outputState(float time, bool last=false);
virtual int writeState(const char * name, float time, bool last=false);
virtual int writeActivity(const char * filename, float time);
virtual int writeActivity(float time);
virtual int writeActivitySparse(float time);
virtual int readState(const char * name, float * time);
virtual int insertProbe(LayerProbe * probe);
/** returns the number of neurons in layer (for borderId=0) or a border region **/
virtual int numberOfNeurons(int borderId);
virtual int mirrorToNorthWest(PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToNorth (PVLayerCube * dest, PVLayerCube* src);
virtual int mirrorToNorthEast(PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToWest (PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToEast (PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToSouthWest(PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToSouth (PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToSouthEast(PVLayerCube * dest, PVLayerCube * src);
// Public access functions:
const char * getName() {return name;}
int getNumNeurons() {return clayer->numNeurons;}
int getNumExtended() {return clayer->numExtended;}
int getLayerId() {return clayer->layerId;}
PVLayerType getLayerType() {return clayer->layerType;}
void setLayerId(int id) {clayer->layerId = id;}
PVLayer* getCLayer() {return clayer;}
pvdata_t * getV() {return clayer->V;} // name query
pvdata_t * getChannel(ChannelType ch) { // name query
return ch < clayer->numPhis ? clayer->phi[ch] : NULL;
}
int getXScale() {return clayer->xScale;}
int getYScale() {return clayer->yScale;}
HyPerCol* getParent() {return parent;}
void setParent(HyPerCol* parent) {this->parent = parent;}
bool useMirrorBCs() {return this->mirrorBCflag;}
// implementation of LayerDataInterface interface
//
const pvdata_t * getLayerData();
const PVLayerLoc * getLayerLoc() { return &clayer->loc; }
bool isExtended() { return true; }
virtual int gatherToInteriorBuffer(unsigned char * buf);
protected:
#ifdef OBSOLETE
virtual int initGlobal(int colId, int colRow, int colCol, int nRows, int nCols);
#endif
char * name; // well known name of layer
int numProbes;
LayerProbe ** probes;
bool mirrorBCflag; // true when mirror BC are to be applied
int ioAppend; // controls opening of binary files
float writeTime; // time of next output
float writeStep; // output time interval
// OpenCL variables
//
#ifdef PV_USE_OPENCL
OpenCLLayer clBuffers; // data shared with OpenCL devices
CLKernel * updatestate_kernel; // CL kernel for update state call
int nxl; // local OpenCL grid size in x
int nyl; // local OpenCL grid size in y
#endif
Timer * update_timer;
};
} // namespace PV
#endif /* HYPERLAYER_HPP_ */
<commit_msg>Many code changes related to using OpenCL kernels.<commit_after>/*
* HyPerLayer.hpp
*
* Created on: Aug 3, 2008
* Author: dcoates
*/
#ifndef HYPERLAYER_HPP_
#define HYPERLAYER_HPP_
#include "../layers/PVLayer.h"
#include "../layers/LayerDataInterface.hpp"
#include "../columns/DataStore.hpp"
#include "../columns/HyPerCol.hpp"
#include "../columns/InterColComm.hpp"
#include "../io/LayerProbe.hpp"
#include "../include/pv_types.h"
#include "../utils/Timer.hpp"
#ifdef PV_USE_OPENCL
#include "../arch/opencl/CLKernel.hpp"
#endif
namespace PV {
class HyPerLayer : public LayerDataInterface {
protected:
// only subclasses can be constructed directly
HyPerLayer(const char * name, HyPerCol * hc, int numChannels);
virtual int initializeLayerId(int layerId);
#ifdef PV_USE_OPENCL
virtual int initializeThreadBuffers() = 0;
virtual int initializeThreadKernels() = 0;
#endif
private:
int initialize_base(const char * name, HyPerCol * hc, int numChannels);
public:
virtual ~HyPerLayer() = 0;
static int copyToBuffer(pvdata_t * buf, const pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
static int copyToBuffer(unsigned char * buf, const pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
static int copyFromBuffer(const pvdata_t * buf, pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
static int copyFromBuffer(const unsigned char * buf, pvdata_t * data,
const PVLayerLoc * loc, bool extended, float scale);
// TODO - make protected
PVLayer * clayer;
HyPerCol * parent;
virtual int triggerReceive(InterColComm * comm);
virtual int recvSynapticInput(HyPerConn * conn, PVLayerCube * cube, int neighbor);
virtual int updateState (float time, float dt);
virtual int updateBorder(float time, float dt);
virtual int publish(InterColComm * comm, float time);
virtual int waitOnPublish(InterColComm * comm);
virtual int updateV();
virtual int setActivity();
virtual int resetPhiBuffers();
int resetBuffer(pvdata_t * buf, int numItems);
virtual int reconstruct(HyPerConn * conn, PVLayerCube * cube);
int initialize(PVLayerType type);
int initFinish();
int mirrorInteriorToBorder(int whichBorder, PVLayerCube * cube, PVLayerCube * borderCube);
virtual int columnWillAddLayer(InterColComm * comm, int id);
virtual int outputState(float time, bool last=false);
virtual int writeState(const char * name, float time, bool last=false);
virtual int writeActivity(const char * filename, float time);
virtual int writeActivity(float time);
virtual int writeActivitySparse(float time);
virtual int readState(const char * name, float * time);
virtual int insertProbe(LayerProbe * probe);
/** returns the number of neurons in layer (for borderId=0) or a border region **/
virtual int numberOfNeurons(int borderId);
virtual int mirrorToNorthWest(PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToNorth (PVLayerCube * dest, PVLayerCube* src);
virtual int mirrorToNorthEast(PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToWest (PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToEast (PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToSouthWest(PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToSouth (PVLayerCube * dest, PVLayerCube * src);
virtual int mirrorToSouthEast(PVLayerCube * dest, PVLayerCube * src);
// Public access functions:
const char * getName() {return name;}
int getNumNeurons() {return clayer->numNeurons;}
int getNumExtended() {return clayer->numExtended;}
int getLayerId() {return clayer->layerId;}
PVLayerType getLayerType() {return clayer->layerType;}
void setLayerId(int id) {clayer->layerId = id;}
PVLayer* getCLayer() {return clayer;}
pvdata_t * getV() {return clayer->V;} // name query
pvdata_t * getChannel(ChannelType ch) { // name query
return ch < this->numChannels ? phi[ch] : NULL;
}
int getXScale() {return clayer->xScale;}
int getYScale() {return clayer->yScale;}
HyPerCol* getParent() {return parent;}
void setParent(HyPerCol* parent) {this->parent = parent;}
bool useMirrorBCs() {return this->mirrorBCflag;}
// implementation of LayerDataInterface interface
//
const pvdata_t * getLayerData();
const PVLayerLoc * getLayerLoc() { return &clayer->loc; }
bool isExtended() { return true; }
virtual int gatherToInteriorBuffer(unsigned char * buf);
protected:
char * name; // well known name of layer
int numChannels; // number of channels
pvdata_t * phi[MAX_CHANNELS];
int numProbes;
LayerProbe ** probes;
bool mirrorBCflag; // true when mirror BC are to be applied
int ioAppend; // controls opening of binary files
float writeTime; // time of next output
float writeStep; // output time interval
// OpenCL variables
//
#ifdef PV_USE_OPENCL
CLKernel * krUpdate; // CL kernel for update state call
// OpenCL buffers
//
CLBuffer * clV;
CLBuffer * clVth;
CLBuffer * clPhiE;
CLBuffer * clPhiI;
CLBuffer * clPhiIB;
CLBuffer * clActivity;
CLBuffer * clPrevTime;
CLBuffer * clParams; // for transferring params to kernel
int numEvents; // number of events in event list
cl_event * evList; // event list
cl_event evUpdate;
int nxl; // local OpenCL grid size in x
int nyl; // local OpenCL grid size in y
#endif
Timer * update_timer;
};
} // namespace PV
#endif /* HYPERLAYER_HPP_ */
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2004 by Stanislav Karchebny *
* [email protected] *
* *
* Licensed under GPL. *
***************************************************************************/
#include "app.h"
#include "akregator.h"
#include "trayicon.h"
#include "akregatorconfig.h"
//settings
#include "settings_general.h"
#include "settings_browser.h"
#include <dcopclient.h>
#include <dcopobject.h>
#include <ksqueezedtextlabel.h>
#include <kkeydialog.h>
#include <kfiledialog.h>
#include <kprogress.h>
#include <kconfig.h>
#include <kurl.h>
#include <kconfigdialog.h>
#include <kedittoolbar.h>
#include <kaction.h>
#include <kstdaction.h>
#include <klibloader.h>
#include <kmessagebox.h>
#include <kstatusbar.h>
#include <klocale.h>
#include <kdebug.h>
#include <qmetaobject.h>
#include <private/qucomextra_p.h>
#include <akregator_part.h>
using namespace Akregator;
BrowserInterface::BrowserInterface( aKregator *shell, const char *name )
: KParts::BrowserInterface( shell, name )
{
m_shell = shell;
}
void BrowserInterface::updateUnread(int unread)
{
m_shell->updateUnread(unread);
}
bool BrowserInterface::haveWindowLoaded() const
{
return akreapp->haveWindowLoaded();
}
aKregator::aKregator()
: KParts::MainWindow( 0L, "aKregator" )
, m_quit(false)
{
// set the shell's ui resource file
setXMLFile("akregator_shell.rc");
m_browserIface=new BrowserInterface(this, "browser_interface");
m_activePart=0;
m_part=0;
// then, setup our actions
setupActions();
m_icon = new TrayIcon(this);
m_icon->show();
connect(m_icon, SIGNAL(quitSelected()),
this, SLOT(quitProgram()));
// and a status bar
statusBar()->show();
int statH=fontMetrics().height()+2;
m_statusLabel = new KSqueezedTextLabel(this);
m_statusLabel->setTextFormat(Qt::RichText);
m_statusLabel->setSizePolicy(QSizePolicy( QSizePolicy::Ignored, QSizePolicy::Fixed ));
m_statusLabel->setMinimumWidth( 0 );
m_statusLabel->setFixedHeight( statH );
statusBar()->addWidget (m_statusLabel, 1, false);
m_progressBar = new KProgress( this );
// blame the following on KMLittleProgress
m_progressBar->setMaximumWidth(fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 14);
m_progressBar->setFixedHeight(statH);
m_progressBar->hide();
statusBar()->addWidget( m_progressBar, 0, true);
// apply the saved mainwindow settings, if any, and ask the mainwindow
// to automatically save settings if changed: window size, toolbar
// position, icon size, etc.
setAutoSaveSettings();
}
bool aKregator::loadPart()
{
// this routine will find and load our Part. it finds the Part by
// name which is a bad idea usually.. but it's alright in this
// case since our Part is made for this Shell
KLibFactory *factory = KLibLoader::self()->factory("libakregatorpart");
if (factory)
{
// now that the Part is loaded, we cast it to a Part to get
// our hands on it
m_part = static_cast<KParts::ReadWritePart*>(factory->create(this, "akregator_part", "KParts::ReadWritePart" ));
if (m_part)
{
// tell the KParts::MainWindow that this is indeed the main widget
setCentralWidget(m_part->widget());
connect(m_part, SIGNAL(started(KIO::Job*)), this, SLOT(slotStarted(KIO::Job*)));
connect(m_part, SIGNAL(completed()), this, SLOT(slotCompleted()));
connect(m_part, SIGNAL(canceled(const QString&)), this, SLOT(slotCanceled(const QString &)));
connect(m_part, SIGNAL(completed(bool)), this, SLOT(slotCompleted()));
connect(m_part, SIGNAL(setWindowCaption (const QString &)), this, SLOT(setCaption (const QString &)));
connect (m_part, SIGNAL(partChanged(KParts::ReadOnlyPart *)), this, SLOT(partChanged(KParts::ReadOnlyPart *)));
connect( browserExtension(m_part), SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
m_activePart=m_part;
// and integrate the part's GUI with the shell's
connectActionCollection(m_part->actionCollection());
createGUI(m_part);
browserExtension(m_part)->setBrowserInterface(m_browserIface);
}
return true;
}
else
{
KMessageBox::error(this, i18n("Could not find our part. Please check your installation."));
return false;
}
}
void aKregator::loadLastOpenFile()
{
show();
load( Settings::lastOpenFile() );
}
aKregator::~aKregator()
{
Settings::setLastOpenFile( m_part->url().url() );
Settings::writeConfig();
}
void aKregator::partChanged(KParts::ReadOnlyPart *p)
{
m_activePart=p;
createGUI(p);
}
void aKregator::load(const KURL& url)
{
if (!m_part)
loadPart();
m_part->openURL( url );
}
void aKregator::addFeedToGroup(const QString& url, const QString& group)
{
if (!m_part)
loadPart();
static_cast<aKregatorPart*>(m_part)->addFeedToGroup( url, group );
}
void aKregator::setupActions()
{
connectActionCollection(actionCollection());
KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
KStdAction::quit(this, SLOT(quitProgram()), actionCollection());
m_stopAction = new KAction( i18n( "&Stop" ), "stop", Key_Escape, this, SLOT( slotStop() ), actionCollection(), "stop" );
m_stopAction->setEnabled(false);
m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());
KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
KStdAction::preferences(this, SLOT(showOptions()), actionCollection());
}
void aKregator::saveProperties(KConfig* /*config*/)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
}
void aKregator::readProperties(KConfig* /*config*/)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
}
void aKregator::fileNew()
{
// this slot is called whenever the File->New menu is selected,
// the New shortcut is pressed (usually CTRL+N) or the New toolbar
// button is clicked
// About this function, the style guide (
// http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
// says that it should open a new window if the document is _not_
// in its initial state. This is what we do here..
if ( ! m_part->url().isEmpty() || m_part->isModified() )
{
callObjectSlot( browserExtension(m_part), "saveSettings()", QVariant());
aKregator *w=new aKregator();
w->loadPart();
w->show();
};
}
void aKregator::optionsShowToolbar()
{
// this is all very cut and paste code for showing/hiding the
// toolbar
if (m_toolbarAction->isChecked())
toolBar()->show();
else
toolBar()->hide();
}
void aKregator::optionsShowStatusbar()
{
// this is all very cut and paste code for showing/hiding the
// statusbar
if (m_statusbarAction->isChecked())
statusBar()->show();
else
statusBar()->hide();
}
void aKregator::optionsConfigureKeys()
{
KKeyDialog dlg( true, this );
dlg.insert(actionCollection());
if (m_part)
dlg.insert(m_part->actionCollection());
dlg.configure();
}
void aKregator::optionsConfigureToolbars()
{
saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
// use the standard toolbar editor
KEditToolbar dlg(factory());
connect(&dlg, SIGNAL(newToolbarConfig()),
this, SLOT(applyNewToolbarConfig()));
dlg.exec();
}
void aKregator::showOptions()
{
if ( KConfigDialog::showDialog( "settings" ) )
return;
KConfigDialog *dialog = new KConfigDialog( this, "settings", Settings::self() );
dialog->addPage(new settings_general(0, "General"), i18n("General"), "package_settings");
dialog->addPage(new settings_browser(0, "Browser"), i18n("Browser"), "browser");
connect( dialog, SIGNAL(settingsChanged()),
m_part, SLOT(saveSettings()) );
dialog->show();
}
void aKregator::applyNewToolbarConfig()
{
applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
}
void aKregator::fileOpen()
{
// this slot is called whenever the File->Open menu is selected,
// the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
// button is clicked
KURL url =
KFileDialog::getOpenURL( QString::null, QString::null, this );
if (url.isEmpty() == false)
{
// About this function, the style guide (
// http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
// says that it should open a new window if the document is _not_
// in its initial state. This is what we do here..
if ( m_part->url().isEmpty() && ! m_part->isModified() )
{
// we open the file in this window...
load( url );
}
else
{
// we open the file in a new window...
aKregator* newWin = new aKregator;
newWin->load( url );
newWin->show();
}
}
}
KParts::BrowserExtension *aKregator::browserExtension(KParts::ReadOnlyPart *p)
{
return KParts::BrowserExtension::childObject( p );
}
// from konqmainwindow
void aKregator::connectActionCollection( KActionCollection *coll )
{
if (!coll) return;
connect( coll, SIGNAL( actionStatusText( const QString & ) ),
this, SLOT( slotActionStatusText( const QString & ) ) );
connect( coll, SIGNAL( clearStatusText() ),
this, SLOT( slotClearStatusText() ) );
}
void aKregator::disconnectActionCollection( KActionCollection *coll )
{
if (!coll) return;
disconnect( coll, SIGNAL( actionStatusText( const QString & ) ),
this, SLOT( slotActionStatusText( const QString & ) ) );
disconnect( coll, SIGNAL( clearStatusText() ),
this, SLOT( slotClearStatusText() ) );
}
void aKregator::quitProgram()
{
// will call queryClose()
m_quit = true;
if( Settings::markAllFeedsReadOnExit() )
{
emit markAllFeedsRead();
}
close();
}
// from KonqFrameStatusBar
void aKregator::fontChange(const QFont & /* oldFont */)
{
int h = fontMetrics().height();
if ( h < 13 ) h = 13;
m_progressBar->setFixedHeight( h + 2 );
}
void aKregator::updateUnread(int unread)
{
m_icon->updateUnread(unread);
}
void aKregator::loadingProgress(int percent)
{
if ( percent > -1 && percent < 100 )
{
if ( !m_progressBar->isVisible() )
m_progressBar->show();
}
else
m_progressBar->hide();
m_progressBar->setValue( percent );
}
void aKregator::slotSetStatusBarText(const QString & s)
{
m_permStatusText=s;
m_statusLabel->setText(s);
}
void aKregator::slotActionStatusText(const QString &s)
{
kdError() << "action="<<s<<endl;
m_statusLabel->setText(s);
}
void aKregator::slotClearStatusText()
{
m_statusLabel->setText(m_permStatusText);
}
void aKregator::closeEvent(QCloseEvent* e)
{
if (!m_quit && !kapp->sessionSaving())
{
kdDebug() << "aKregator::closeEvent m_quit is false" << endl;
KMessageBox::information(this, i18n( "<qt>Closing the main window will keep aKregator running in the system tray. Use 'Quit' from the 'File' menu to quit the application.</qt>" ), i18n( "Docking in System Tray" ), "hideOnCloseInfo");
hide();
e->ignore();
}
else
{
kdDebug() << "aKregator::closeEvent m_quit is true" << endl;
if (m_part->queryClose())
KMainWindow::closeEvent(e);
}
// Commenting this out fixes crash when quitting from system tray icon. Why was it here? ..cramblitt
// m_quit = false;
}
void aKregator::slotStop()
{
m_activePart->closeURL();
}
// yanked from kdelibs
void aKregator::callObjectSlot( QObject *obj, const char *name, const QVariant &argument )
{
if (!obj)
return;
int slot = obj->metaObject()->findSlot( name );
QUObject o[ 2 ];
QStringList strLst;
uint i;
switch ( argument.type() )
{
case QVariant::Invalid:
break;
case QVariant::String:
static_QUType_QString.set( o + 1, argument.toString() );
break;
case QVariant::StringList:
strLst = argument.toStringList();
static_QUType_ptr.set( o + 1, &strLst );
break;
case QVariant::Int:
static_QUType_int.set( o + 1, argument.toInt() );
break;
case QVariant::UInt:
i = argument.toUInt();
static_QUType_ptr.set( o + 1, &i );
break;
case QVariant::Bool:
static_QUType_bool.set( o + 1, argument.toBool() );
break;
default: return;
}
obj->qt_invoke( slot, o );
}
void aKregator::slotStarted(KIO::Job *)
{
m_stopAction->setEnabled(true);
}
void aKregator::slotCanceled(const QString &)
{
m_stopAction->setEnabled(false);
}
void aKregator::slotCompleted()
{
m_stopAction->setEnabled(false);
}
#include "akregator.moc"
// vim: set et ts=4 sts=4 sw=4:
<commit_msg>CVS_SILENT<commit_after>/***************************************************************************
* Copyright (C) 2004 by Stanislav Karchebny *
* [email protected] *
* *
* Licensed under GPL. *
***************************************************************************/
#include "app.h"
#include "akregator.h"
#include "trayicon.h"
#include "akregatorconfig.h"
//settings
#include "settings_general.h"
#include "settings_browser.h"
#include <dcopclient.h>
#include <dcopobject.h>
#include <ksqueezedtextlabel.h>
#include <kkeydialog.h>
#include <kfiledialog.h>
#include <kprogress.h>
#include <kconfig.h>
#include <kurl.h>
#include <kconfigdialog.h>
#include <kedittoolbar.h>
#include <kaction.h>
#include <kstdaction.h>
#include <klibloader.h>
#include <kmessagebox.h>
#include <kstatusbar.h>
#include <klocale.h>
#include <kdebug.h>
#include <qmetaobject.h>
#include <private/qucomextra_p.h>
#include <akregator_part.h>
using namespace Akregator;
BrowserInterface::BrowserInterface( aKregator *shell, const char *name )
: KParts::BrowserInterface( shell, name )
{
m_shell = shell;
}
void BrowserInterface::updateUnread(int unread)
{
m_shell->updateUnread(unread);
}
bool BrowserInterface::haveWindowLoaded() const
{
return akreapp->haveWindowLoaded();
}
aKregator::aKregator()
: KParts::MainWindow( 0L, "aKregator" )
, m_quit(false)
{
// set the shell's ui resource file
setXMLFile("akregator_shell.rc");
m_browserIface=new BrowserInterface(this, "browser_interface");
m_activePart=0;
m_part=0;
// then, setup our actions
setupActions();
m_icon = new TrayIcon(this);
m_icon->show();
connect(m_icon, SIGNAL(quitSelected()),
this, SLOT(quitProgram()));
// and a status bar
statusBar()->show();
int statH=fontMetrics().height()+2;
m_statusLabel = new KSqueezedTextLabel(this);
m_statusLabel->setTextFormat(Qt::RichText);
m_statusLabel->setSizePolicy(QSizePolicy( QSizePolicy::Ignored, QSizePolicy::Fixed ));
m_statusLabel->setMinimumWidth( 0 );
m_statusLabel->setFixedHeight( statH );
statusBar()->addWidget (m_statusLabel, 1, false);
m_progressBar = new KProgress( this );
// blame the following on KMLittleProgress
m_progressBar->setMaximumWidth(fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 14);
m_progressBar->setFixedHeight(statH);
m_progressBar->hide();
statusBar()->addWidget( m_progressBar, 0, true);
// apply the saved mainwindow settings, if any, and ask the mainwindow
// to automatically save settings if changed: window size, toolbar
// position, icon size, etc.
setAutoSaveSettings();
}
bool aKregator::loadPart()
{
// this routine will find and load our Part. it finds the Part by
// name which is a bad idea usually.. but it's alright in this
// case since our Part is made for this Shell
KLibFactory *factory = KLibLoader::self()->factory("libakregatorpart");
if (factory)
{
// now that the Part is loaded, we cast it to a Part to get
// our hands on it
m_part = static_cast<KParts::ReadWritePart*>(factory->create(this, "akregator_part", "KParts::ReadWritePart" ));
if (m_part)
{
// tell the KParts::MainWindow that this is indeed the main widget
setCentralWidget(m_part->widget());
connect(m_part, SIGNAL(started(KIO::Job*)), this, SLOT(slotStarted(KIO::Job*)));
connect(m_part, SIGNAL(completed()), this, SLOT(slotCompleted()));
connect(m_part, SIGNAL(canceled(const QString&)), this, SLOT(slotCanceled(const QString &)));
connect(m_part, SIGNAL(completed(bool)), this, SLOT(slotCompleted()));
connect(m_part, SIGNAL(setWindowCaption (const QString &)), this, SLOT(setCaption (const QString &)));
connect (m_part, SIGNAL(partChanged(KParts::ReadOnlyPart *)), this, SLOT(partChanged(KParts::ReadOnlyPart *)));
connect( browserExtension(m_part), SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
m_activePart=m_part;
// and integrate the part's GUI with the shell's
connectActionCollection(m_part->actionCollection());
createGUI(m_part);
browserExtension(m_part)->setBrowserInterface(m_browserIface);
}
return true;
}
else
{
KMessageBox::error(this, i18n("Could not find our part. Please check your installation."));
return false;
}
}
void aKregator::loadLastOpenFile()
{
show();
load( Settings::lastOpenFile() );
}
aKregator::~aKregator()
{
Settings::setLastOpenFile( m_part->url().url() );
Settings::writeConfig();
}
void aKregator::partChanged(KParts::ReadOnlyPart *p)
{
m_activePart=p;
createGUI(p);
}
void aKregator::load(const KURL& url)
{
if (!m_part)
loadPart();
m_part->openURL( url );
}
void aKregator::addFeedToGroup(const QString& url, const QString& group)
{
if (!m_part)
loadPart();
static_cast<aKregatorPart*>(m_part)->addFeedToGroup( url, group );
}
void aKregator::setupActions()
{
connectActionCollection(actionCollection());
KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
KStdAction::quit(this, SLOT(quitProgram()), actionCollection());
m_stopAction = new KAction( i18n( "&Stop" ), "stop", Key_Escape, this, SLOT( slotStop() ), actionCollection(), "stop" );
m_stopAction->setEnabled(false);
m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());
KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
KStdAction::preferences(this, SLOT(showOptions()), actionCollection());
}
void aKregator::saveProperties(KConfig* /*config*/)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
}
void aKregator::readProperties(KConfig* /*config*/)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
}
void aKregator::fileNew()
{
// this slot is called whenever the File->New menu is selected,
// the New shortcut is pressed (usually CTRL+N) or the New toolbar
// button is clicked
// About this function, the style guide (
// http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
// says that it should open a new window if the document is _not_
// in its initial state. This is what we do here..
if ( ! m_part->url().isEmpty() || m_part->isModified() )
{
callObjectSlot( browserExtension(m_part), "saveSettings()", QVariant());
aKregator *w=new aKregator();
w->loadPart();
w->show();
};
}
void aKregator::optionsShowToolbar()
{
// this is all very cut and paste code for showing/hiding the
// toolbar
if (m_toolbarAction->isChecked())
toolBar()->show();
else
toolBar()->hide();
}
void aKregator::optionsShowStatusbar()
{
// this is all very cut and paste code for showing/hiding the
// statusbar
if (m_statusbarAction->isChecked())
statusBar()->show();
else
statusBar()->hide();
}
void aKregator::optionsConfigureKeys()
{
KKeyDialog dlg( true, this );
dlg.insert(actionCollection());
if (m_part)
dlg.insert(m_part->actionCollection());
dlg.configure();
}
void aKregator::optionsConfigureToolbars()
{
saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
// use the standard toolbar editor
KEditToolbar dlg(factory());
connect(&dlg, SIGNAL(newToolbarConfig()),
this, SLOT(applyNewToolbarConfig()));
dlg.exec();
}
void aKregator::showOptions()
{
if ( KConfigDialog::showDialog( "settings" ) )
return;
KConfigDialog *dialog = new KConfigDialog( this, "settings", Settings::self() );
dialog->addPage(new settings_general(0, "General"), i18n("General"), "package_settings");
dialog->addPage(new settings_browser(0, "Browser"), i18n("Browser"), "browser");
connect( dialog, SIGNAL(settingsChanged()),
m_part, SLOT(saveSettings()) );
dialog->show();
}
void aKregator::applyNewToolbarConfig()
{
applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
}
void aKregator::fileOpen()
{
// this slot is called whenever the File->Open menu is selected,
// the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
// button is clicked
KURL url =
KFileDialog::getOpenURL( QString::null, QString::null, this );
if (url.isEmpty() == false)
{
// About this function, the style guide (
// http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
// says that it should open a new window if the document is _not_
// in its initial state. This is what we do here..
if ( m_part->url().isEmpty() && ! m_part->isModified() )
{
// we open the file in this window...
load( url );
}
else
{
// we open the file in a new window...
aKregator* newWin = new aKregator;
newWin->load( url );
newWin->show();
}
}
}
KParts::BrowserExtension *aKregator::browserExtension(KParts::ReadOnlyPart *p)
{
return KParts::BrowserExtension::childObject( p );
}
// from konqmainwindow
void aKregator::connectActionCollection( KActionCollection *coll )
{
if (!coll) return;
connect( coll, SIGNAL( actionStatusText( const QString & ) ),
this, SLOT( slotActionStatusText( const QString & ) ) );
connect( coll, SIGNAL( clearStatusText() ),
this, SLOT( slotClearStatusText() ) );
}
void aKregator::disconnectActionCollection( KActionCollection *coll )
{
if (!coll) return;
disconnect( coll, SIGNAL( actionStatusText( const QString & ) ),
this, SLOT( slotActionStatusText( const QString & ) ) );
disconnect( coll, SIGNAL( clearStatusText() ),
this, SLOT( slotClearStatusText() ) );
}
void aKregator::quitProgram()
{
// will call queryClose()
m_quit = true;
if( Settings::markAllFeedsReadOnExit() )
{
emit markAllFeedsRead();
}
close();
}
// from KonqFrameStatusBar
void aKregator::fontChange(const QFont & /* oldFont */)
{
int h = fontMetrics().height();
if ( h < 13 ) h = 13;
m_progressBar->setFixedHeight( h + 2 );
}
void aKregator::updateUnread(int unread)
{
m_icon->updateUnread(unread);
}
void aKregator::loadingProgress(int percent)
{
if ( percent > -1 && percent < 100 )
{
if ( !m_progressBar->isVisible() )
m_progressBar->show();
}
else
m_progressBar->hide();
m_progressBar->setValue( percent );
}
void aKregator::slotSetStatusBarText(const QString & s)
{
m_permStatusText=s;
m_statusLabel->setText(s);
}
void aKregator::slotActionStatusText(const QString &s)
{
m_statusLabel->setText(s);
}
void aKregator::slotClearStatusText()
{
m_statusLabel->setText(m_permStatusText);
}
void aKregator::closeEvent(QCloseEvent* e)
{
if (!m_quit && !kapp->sessionSaving())
{
kdDebug() << "aKregator::closeEvent m_quit is false" << endl;
KMessageBox::information(this, i18n( "<qt>Closing the main window will keep aKregator running in the system tray. Use 'Quit' from the 'File' menu to quit the application.</qt>" ), i18n( "Docking in System Tray" ), "hideOnCloseInfo");
hide();
e->ignore();
}
else
{
kdDebug() << "aKregator::closeEvent m_quit is true" << endl;
if (m_part->queryClose())
KMainWindow::closeEvent(e);
}
// Commenting this out fixes crash when quitting from system tray icon. Why was it here? ..cramblitt
// m_quit = false;
}
void aKregator::slotStop()
{
m_activePart->closeURL();
}
// yanked from kdelibs
void aKregator::callObjectSlot( QObject *obj, const char *name, const QVariant &argument )
{
if (!obj)
return;
int slot = obj->metaObject()->findSlot( name );
QUObject o[ 2 ];
QStringList strLst;
uint i;
switch ( argument.type() )
{
case QVariant::Invalid:
break;
case QVariant::String:
static_QUType_QString.set( o + 1, argument.toString() );
break;
case QVariant::StringList:
strLst = argument.toStringList();
static_QUType_ptr.set( o + 1, &strLst );
break;
case QVariant::Int:
static_QUType_int.set( o + 1, argument.toInt() );
break;
case QVariant::UInt:
i = argument.toUInt();
static_QUType_ptr.set( o + 1, &i );
break;
case QVariant::Bool:
static_QUType_bool.set( o + 1, argument.toBool() );
break;
default: return;
}
obj->qt_invoke( slot, o );
}
void aKregator::slotStarted(KIO::Job *)
{
m_stopAction->setEnabled(true);
}
void aKregator::slotCanceled(const QString &)
{
m_stopAction->setEnabled(false);
}
void aKregator::slotCompleted()
{
m_stopAction->setEnabled(false);
}
#include "akregator.moc"
// vim: set et ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors 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 COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
#include <curl/curl.h>
#else
class CURL;
#endif
static void cleanup_curl(void)
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
curl_global_cleanup();
#endif
}
static void initialize_curl_startup()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (curl_global_init(CURL_GLOBAL_ALL))
{
FATAL("curl_global_init(CURL_GLOBAL_ALL) failed");
}
#endif
if (atexit(cleanup_curl))
{
FATAL("atexit() failed");
}
}
static pthread_once_t start_key_once= PTHREAD_ONCE_INIT;
static void initialize_curl(void)
{
int ret;
if ((ret= pthread_once(&start_key_once, initialize_curl_startup)) != 0)
{
FATAL(strerror(ret));
}
}
namespace libtest {
namespace http {
#define YATL_USERAGENT "YATL/1.0"
static size_t http_get_result_callback(void *ptr, size_t size, size_t nmemb, void *data)
{
vchar_t *_body= (vchar_t*)data;
_body->resize(size * nmemb);
memcpy(&_body[0], ptr, _body->size());
return _body->size();
}
static void init(CURL *curl, const std::string& url)
{
(void)http_get_result_callback;
(void)curl;
(void)url;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
assert(curl);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, YATL_USERAGENT);
}
#endif
}
HTTP::HTTP(const std::string& url_arg) :
_url(url_arg),
_response(0)
{
initialize_curl();
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool GET::execute()
{
(void)init;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool POST::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, _body.size());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool TRACE::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "TRACE");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool HEAD::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
} // namespace http
} // namespace libtest
<commit_msg>Fix memcpy() call to compile with gcc 8<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors 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 COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
#include <curl/curl.h>
#else
class CURL;
#endif
static void cleanup_curl(void)
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
curl_global_cleanup();
#endif
}
static void initialize_curl_startup()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (curl_global_init(CURL_GLOBAL_ALL))
{
FATAL("curl_global_init(CURL_GLOBAL_ALL) failed");
}
#endif
if (atexit(cleanup_curl))
{
FATAL("atexit() failed");
}
}
static pthread_once_t start_key_once= PTHREAD_ONCE_INIT;
static void initialize_curl(void)
{
int ret;
if ((ret= pthread_once(&start_key_once, initialize_curl_startup)) != 0)
{
FATAL(strerror(ret));
}
}
namespace libtest {
namespace http {
#define YATL_USERAGENT "YATL/1.0"
static size_t http_get_result_callback(void *ptr, size_t size, size_t nmemb, void *data)
{
vchar_t *_body= (vchar_t*)data;
_body->resize(size * nmemb);
memcpy(static_cast<void*>(&_body[0]), ptr, _body->size());
return _body->size();
}
static void init(CURL *curl, const std::string& url)
{
(void)http_get_result_callback;
(void)curl;
(void)url;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
assert(curl);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, YATL_USERAGENT);
}
#endif
}
HTTP::HTTP(const std::string& url_arg) :
_url(url_arg),
_response(0)
{
initialize_curl();
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool GET::execute()
{
(void)init;
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool POST::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, _body.size());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return bool(retref == CURLE_OK);
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool TRACE::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();;
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "TRACE");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body[0]);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool HEAD::execute()
{
#if defined(HAVE_LIBCURL) && HAVE_LIBCURL
if (HAVE_LIBCURL)
{
CURL *curl= curl_easy_init();
init(curl, url());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback);
CURLcode retref= curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, _response);
curl_easy_cleanup(curl);
return retref == CURLE_OK;
}
#endif
return false;
}
#pragma GCC diagnostic pop
} // namespace http
} // namespace libtest
<|endoftext|> |
<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved.
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 "tensorflow_serving/core/loader_harness.h"
#include <algorithm>
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/env.h"
namespace tensorflow {
namespace serving {
LoaderHarness::LoaderHarness(const ServableId& id,
std::unique_ptr<Loader> loader,
const Options& options)
: id_(id),
loader_(std::move(loader)),
additional_state_(nullptr),
options_(options) {}
LoaderHarness::~LoaderHarness() {
mutex_lock l(mu_);
DCHECK(state_ == State::kNew || state_ == State::kDisabled ||
state_ == State::kError)
<< "Servable: " << id_ << " state: " << state_;
}
LoaderHarness::State LoaderHarness::state() const {
mutex_lock l(mu_);
return state_;
}
Status LoaderHarness::LoadRequested() {
mutex_lock l(mu_);
if (state_ != State::kNew) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(),
" cannot be transitioned to load-requested. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kNew));
}
state_ = State::kLoadRequested;
return Status::OK();
}
Status LoaderHarness::LoadApproved() {
mutex_lock l(mu_);
if (state_ != State::kLoadRequested) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(),
" cannot be approved for loading. In state: ", StateDebugString(state_),
" instead of state: ", StateDebugString(State::kLoadRequested));
}
state_ = State::kLoadApproved;
LOG(INFO) << "Approving load for servable version " << id_;
return Status::OK();
}
Status LoaderHarness::Load(const ResourceAllocation& available_resources) {
{
mutex_lock l(mu_);
if (state_ != State::kLoadApproved) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(), " cannot be loaded. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kLoadApproved));
}
state_ = State::kLoading;
LOG(INFO) << "Loading servable version " << id_;
}
const Status status = [&]() {
Status load_status;
int num_tries = 0;
do {
if (num_tries > 0) {
if (cancel_load_retry()) {
LOG(INFO) << "Load retry cancelled for servable: " << id_;
break;
}
Env::Default()->SleepForMicroseconds(
options_.load_retry_interval_micros);
LOG(INFO) << "Retrying load on servable version: " << id_
<< " retry: " << num_tries;
}
load_status = loader_->Load(available_resources);
if (!load_status.ok()) {
LOG(ERROR) << "Servable: " << id_ << " load failure: " << load_status;
}
++num_tries;
} while (!cancel_load_retry() && !load_status.ok() &&
(num_tries - 1) < options_.max_num_load_retries);
return load_status;
}();
{
mutex_lock l(mu_);
DCHECK_EQ(State::kLoading, state_);
if (status.ok()) {
state_ = State::kReady;
LOG(INFO) << "Successfully loaded servable version " << id_;
} else {
ErrorInternal(status);
}
}
return status;
}
Status LoaderHarness::UnloadRequested() {
mutex_lock l(mu_);
if (state_ != State::kReady) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(),
" cannot be transitioned to unload-requested. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kReady));
}
state_ = State::kUnloadRequested;
return Status::OK();
}
void LoaderHarness::set_cancel_load_retry(const bool value) {
mutex_lock l(mu_);
cancel_load_retry_ = value;
}
bool LoaderHarness::cancel_load_retry() {
mutex_lock l(mu_);
return cancel_load_retry_;
}
void LoaderHarness::Unload() {
{
mutex_lock l(mu_);
DCHECK_EQ(state_, State::kQuiesced);
state_ = State::kUnloading;
LOG(INFO) << "Unloading servable version " << id_;
}
loader_->Unload();
{
mutex_lock l(mu_);
DCHECK_EQ(state_, State::kUnloading);
state_ = State::kDisabled;
LOG(INFO) << "Done unloading servable version " << id_;
}
}
Status LoaderHarness::StartQuiescing() {
mutex_lock l(mu_);
if (state_ != State::kUnloadRequested) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(), " cannot be quiesced. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kUnloadRequested));
}
state_ = State::kQuiescing;
LOG(INFO) << "Quiescing servable version " << id_;
return Status::OK();
}
void LoaderHarness::DoneQuiescing() {
mutex_lock l(mu_);
DCHECK_EQ(state_, State::kQuiescing);
state_ = State::kQuiesced;
LOG(INFO) << "Done quiescing servable version " << id_;
}
void LoaderHarness::ErrorInternal(const Status status) {
state_ = State::kError;
status_ = status;
LOG(INFO) << "Encountered an error for servable version " << id_ << ": "
<< status_;
}
void LoaderHarness::Error(const Status status) {
mutex_lock l(mu_);
ErrorInternal(status);
}
Status LoaderHarness::status() const {
mutex_lock l(mu_);
return status_;
}
string LoaderHarness::StateDebugString(const State state) {
switch (state) {
case State::kNew:
return "new";
case State::kLoadRequested:
return "load-requested";
case State::kLoadApproved:
return "load-approved";
case State::kLoading:
return "loading";
case State::kReady:
return "ready";
case State::kUnloadRequested:
return "unload-requested";
case State::kQuiescing:
return "quiescing";
case State::kQuiesced:
return "quiesced";
case State::kUnloading:
return "unloading";
case State::kDisabled:
return "disabled";
case State::kError:
return "error";
}
}
} // namespace serving
} // namespace tensorflow
<commit_msg>Add logging to LoaderHarness. Change: 137854851<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved.
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 "tensorflow_serving/core/loader_harness.h"
#include <algorithm>
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/env.h"
namespace tensorflow {
namespace serving {
LoaderHarness::LoaderHarness(const ServableId& id,
std::unique_ptr<Loader> loader,
const Options& options)
: id_(id),
loader_(std::move(loader)),
additional_state_(nullptr),
options_(options) {
VLOG(1) << "Starting to manage servable version " << id_;
}
LoaderHarness::~LoaderHarness() {
mutex_lock l(mu_);
DCHECK(state_ == State::kNew || state_ == State::kDisabled ||
state_ == State::kError)
<< "Servable: " << id_ << " state: " << state_;
}
LoaderHarness::State LoaderHarness::state() const {
mutex_lock l(mu_);
return state_;
}
Status LoaderHarness::LoadRequested() {
mutex_lock l(mu_);
if (state_ != State::kNew) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(),
" cannot be transitioned to load-requested. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kNew));
}
state_ = State::kLoadRequested;
VLOG(1) << "Load requested for servable version " << id_;
return Status::OK();
}
Status LoaderHarness::LoadApproved() {
mutex_lock l(mu_);
if (state_ != State::kLoadRequested) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(),
" cannot be approved for loading. In state: ", StateDebugString(state_),
" instead of state: ", StateDebugString(State::kLoadRequested));
}
state_ = State::kLoadApproved;
LOG(INFO) << "Approving load for servable version " << id_;
return Status::OK();
}
Status LoaderHarness::Load(const ResourceAllocation& available_resources) {
{
mutex_lock l(mu_);
if (state_ != State::kLoadApproved) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(), " cannot be loaded. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kLoadApproved));
}
state_ = State::kLoading;
LOG(INFO) << "Loading servable version " << id_;
}
const Status status = [&]() {
Status load_status;
int num_tries = 0;
do {
if (num_tries > 0) {
if (cancel_load_retry()) {
LOG(INFO) << "Load retry cancelled for servable: " << id_;
break;
}
Env::Default()->SleepForMicroseconds(
options_.load_retry_interval_micros);
LOG(INFO) << "Retrying load on servable version: " << id_
<< " retry: " << num_tries;
}
load_status = loader_->Load(available_resources);
if (!load_status.ok()) {
LOG(ERROR) << "Servable: " << id_ << " load failure: " << load_status;
}
++num_tries;
} while (!cancel_load_retry() && !load_status.ok() &&
(num_tries - 1) < options_.max_num_load_retries);
return load_status;
}();
{
mutex_lock l(mu_);
DCHECK_EQ(State::kLoading, state_);
if (status.ok()) {
state_ = State::kReady;
LOG(INFO) << "Successfully loaded servable version " << id_;
} else {
ErrorInternal(status);
}
}
return status;
}
Status LoaderHarness::UnloadRequested() {
mutex_lock l(mu_);
if (state_ != State::kReady) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(),
" cannot be transitioned to unload-requested. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kReady));
}
state_ = State::kUnloadRequested;
return Status::OK();
}
void LoaderHarness::set_cancel_load_retry(const bool value) {
mutex_lock l(mu_);
cancel_load_retry_ = value;
}
bool LoaderHarness::cancel_load_retry() {
mutex_lock l(mu_);
return cancel_load_retry_;
}
void LoaderHarness::Unload() {
{
mutex_lock l(mu_);
DCHECK_EQ(state_, State::kQuiesced);
state_ = State::kUnloading;
LOG(INFO) << "Unloading servable version " << id_;
}
loader_->Unload();
{
mutex_lock l(mu_);
DCHECK_EQ(state_, State::kUnloading);
state_ = State::kDisabled;
LOG(INFO) << "Done unloading servable version " << id_;
}
}
Status LoaderHarness::StartQuiescing() {
mutex_lock l(mu_);
if (state_ != State::kUnloadRequested) {
return errors::FailedPrecondition(
"Servable: ", id_.DebugString(), " cannot be quiesced. In state: ",
StateDebugString(state_), " instead of state: ",
StateDebugString(State::kUnloadRequested));
}
state_ = State::kQuiescing;
LOG(INFO) << "Quiescing servable version " << id_;
return Status::OK();
}
void LoaderHarness::DoneQuiescing() {
mutex_lock l(mu_);
DCHECK_EQ(state_, State::kQuiescing);
state_ = State::kQuiesced;
LOG(INFO) << "Done quiescing servable version " << id_;
}
void LoaderHarness::ErrorInternal(const Status status) {
state_ = State::kError;
status_ = status;
LOG(INFO) << "Encountered an error for servable version " << id_ << ": "
<< status_;
}
void LoaderHarness::Error(const Status status) {
mutex_lock l(mu_);
ErrorInternal(status);
}
Status LoaderHarness::status() const {
mutex_lock l(mu_);
return status_;
}
string LoaderHarness::StateDebugString(const State state) {
switch (state) {
case State::kNew:
return "new";
case State::kLoadRequested:
return "load-requested";
case State::kLoadApproved:
return "load-approved";
case State::kLoading:
return "loading";
case State::kReady:
return "ready";
case State::kUnloadRequested:
return "unload-requested";
case State::kQuiescing:
return "quiescing";
case State::kQuiesced:
return "quiesced";
case State::kUnloading:
return "unloading";
case State::kDisabled:
return "disabled";
case State::kError:
return "error";
}
}
} // namespace serving
} // namespace tensorflow
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Desktop 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 2006-2007 Torsten Rahn <[email protected]>"
// Copyright 2007 Inge Wallin <[email protected]>"
//
#include "HttpFetchFile.h"
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtGui/QMessageBox>
#include <QtCore/QTemporaryFile>
#include "MarbleDirs.h"
HttpFetchFile::HttpFetchFile( QObject *parent )
: QObject( parent )
{
m_pHttp = new QHttp(this);
m_targetDirString = MarbleDirs::localPath() + "/cache/";
if ( QDir( m_targetDirString ).exists() == false )
( QDir::root() ).mkpath( m_targetDirString );
// What if we don't succeed in creating the path?
connect( m_pHttp, SIGNAL( requestFinished( int, bool ) ),
this, SLOT( httpRequestFinished( int, bool ) ) );
}
HttpFetchFile::~HttpFetchFile()
{
// qDebug() << "Deleting Temporary Files ...";
m_pHttp->disconnect();
QFile* jobTargetFile;
QMap<int, HttpJob*>::const_iterator i = m_pFileIdMap.constBegin();
while (i != m_pFileIdMap.constEnd()) {
// qDebug() << "Deleting Item";
HttpJob* job = i.value();
jobTargetFile = job->targetFile;
jobTargetFile->remove();
++i;
}
// qDebug() << "Done.";
}
void HttpFetchFile::executeJob( HttpJob* job )
{
QString localFileUrlString = job->targetDirString + job->relativeUrlString;
if ( QFile::exists( localFileUrlString ) ) {
qDebug( "File already exists" );
emit jobDone( job, 1 );
return;
}
QTemporaryFile* jobTargetFile = new QTemporaryFile( QDir::tempPath() + "marble-tile.XXXXXX" );
jobTargetFile->setAutoRemove( false );
job->targetFile = (QFile*) jobTargetFile;
if ( !jobTargetFile->open() ) {
emit statusMessage( tr( "Unable to save the file %1: %2." )
.arg( localFileUrlString ).arg( jobTargetFile->errorString() ) );
delete jobTargetFile;
jobTargetFile = 0;
return;
}
QUrl sourceUrl = QUrl( (job->serverUrl).toString() + job->relativeUrlString );
m_pHttp->setHost( sourceUrl.host(), sourceUrl.port() != -1 ? sourceUrl.port() : 80 );
if ( !sourceUrl.userName().isEmpty() )
m_pHttp->setUser( sourceUrl.userName(), sourceUrl.password() );
int httpGetId = m_pHttp->get( sourceUrl.path(), jobTargetFile );
// qDebug() << " job id: " << httpGetId << " source: " << sourceUrl.toString();
m_pFileIdMap.insert( httpGetId, job );
emit statusMessage( tr("Downloading data...") );
}
void HttpFetchFile::httpRequestFinished(int requestId, bool error)
{
if ( !m_pFileIdMap.contains( requestId ) )
return;
QHttpResponseHeader responseHeader = m_pHttp->lastResponse();
HttpJob* job = m_pFileIdMap[requestId];
QFile* jobTargetFile = job->targetFile;
if (responseHeader.statusCode() != 200) {
// qDebug() << QString( " response: %1" ).arg( responseHeader.statusCode() );
jobTargetFile->remove();
emit statusMessage( tr( "Download failed: %1." )
.arg( responseHeader.reasonPhrase() ) );
emit jobDone( m_pFileIdMap[requestId], 1 );
m_pFileIdMap.remove( requestId );
return;
}
if ( error != 0 ) {
// qDebug() << "An error occurred! The Temporary file will be REMOVED!";
jobTargetFile->remove();
emit statusMessage( tr( "Download failed: %1." )
.arg( m_pHttp->errorString() ) );
emit jobDone( m_pFileIdMap[requestId], error );
m_pFileIdMap.remove( requestId );
return;
}
jobTargetFile->close();
QString localFileUrlString = job->targetDirString + job->relativeUrlString;
QString localFilePath = localFileUrlString.section( QDir::separator(), 0, -2 );
// qDebug() << "Moving download to: " << localFileUrlString << " in: " << localFilePath;
if ( !QDir( localFilePath ).exists() )
( QDir::root() ).mkpath( localFilePath );
jobTargetFile->rename( localFileUrlString );
emit statusMessage( tr( "Download finished." ) );
emit jobDone( m_pFileIdMap[requestId], 0 );
m_pFileIdMap.remove( requestId );
delete jobTargetFile;
jobTargetFile = 0;
}
#include "HttpFetchFile.moc"
<commit_msg>Work properly on Windows. Never forget that Qt internally always separates paths with '/', regardless of the underlying OS. Also, using QDir we get a better impression on what we are actually doing.<commit_after>//
// This file is part of the Marble Desktop 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 2006-2007 Torsten Rahn <[email protected]>"
// Copyright 2007 Inge Wallin <[email protected]>"
//
#include "HttpFetchFile.h"
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtGui/QMessageBox>
#include <QtCore/QTemporaryFile>
#include "MarbleDirs.h"
HttpFetchFile::HttpFetchFile( QObject *parent )
: QObject( parent )
{
m_pHttp = new QHttp(this);
m_targetDirString = MarbleDirs::localPath() + "/cache/";
if ( QDir( m_targetDirString ).exists() == false )
( QDir::root() ).mkpath( m_targetDirString );
// What if we don't succeed in creating the path?
connect( m_pHttp, SIGNAL( requestFinished( int, bool ) ),
this, SLOT( httpRequestFinished( int, bool ) ) );
}
HttpFetchFile::~HttpFetchFile()
{
// qDebug() << "Deleting Temporary Files ...";
m_pHttp->disconnect();
QFile* jobTargetFile;
QMap<int, HttpJob*>::const_iterator i = m_pFileIdMap.constBegin();
while (i != m_pFileIdMap.constEnd()) {
// qDebug() << "Deleting Item";
HttpJob* job = i.value();
jobTargetFile = job->targetFile;
jobTargetFile->remove();
++i;
}
// qDebug() << "Done.";
}
void HttpFetchFile::executeJob( HttpJob* job )
{
QString localFileUrlString = job->targetDirString + job->relativeUrlString;
if ( QFile::exists( localFileUrlString ) ) {
qDebug( "File already exists" );
emit jobDone( job, 1 );
return;
}
QTemporaryFile* jobTargetFile = new QTemporaryFile( QDir::tempPath() + "marble-tile.XXXXXX" );
jobTargetFile->setAutoRemove( false );
job->targetFile = (QFile*) jobTargetFile;
if ( !jobTargetFile->open() ) {
emit statusMessage( tr( "Unable to save the file %1: %2." )
.arg( localFileUrlString ).arg( jobTargetFile->errorString() ) );
delete jobTargetFile;
jobTargetFile = 0;
return;
}
QUrl sourceUrl = QUrl( (job->serverUrl).toString() + job->relativeUrlString );
m_pHttp->setHost( sourceUrl.host(), sourceUrl.port() != -1 ? sourceUrl.port() : 80 );
if ( !sourceUrl.userName().isEmpty() )
m_pHttp->setUser( sourceUrl.userName(), sourceUrl.password() );
int httpGetId = m_pHttp->get( sourceUrl.path(), jobTargetFile );
// qDebug() << " job id: " << httpGetId << " source: " << sourceUrl.toString();
m_pFileIdMap.insert( httpGetId, job );
emit statusMessage( tr("Downloading data...") );
}
void HttpFetchFile::httpRequestFinished(int requestId, bool error)
{
if ( !m_pFileIdMap.contains( requestId ) )
return;
QHttpResponseHeader responseHeader = m_pHttp->lastResponse();
HttpJob* job = m_pFileIdMap[requestId];
QFile* jobTargetFile = job->targetFile;
if (responseHeader.statusCode() != 200) {
// qDebug() << QString( " response: %1" ).arg( responseHeader.statusCode() );
jobTargetFile->remove();
emit statusMessage( tr( "Download failed: %1." )
.arg( responseHeader.reasonPhrase() ) );
emit jobDone( m_pFileIdMap[requestId], 1 );
m_pFileIdMap.remove( requestId );
return;
}
if ( error != 0 ) {
// qDebug() << "An error occurred! The Temporary file will be REMOVED!";
jobTargetFile->remove();
emit statusMessage( tr( "Download failed: %1." )
.arg( m_pHttp->errorString() ) );
emit jobDone( m_pFileIdMap[requestId], error );
m_pFileIdMap.remove( requestId );
return;
}
jobTargetFile->close();
QString localFileUrlString = job->targetDirString + job->relativeUrlString;
QDir localFileDir(localFileUrlString);
localFileDir.cdUp();
localFileDir.cdUp();
QString localFilePath = localFileDir.absolutePath();
// qDebug() << "Moving download to: " << localFileUrlString << " in: " << localFilePath;
if ( !QDir( localFilePath ).exists() )
( QDir::root() ).mkpath( localFilePath );
jobTargetFile->rename( localFileUrlString );
emit statusMessage( tr( "Download finished." ) );
emit jobDone( m_pFileIdMap[requestId], 0 );
m_pFileIdMap.remove( requestId );
delete jobTargetFile;
jobTargetFile = 0;
}
#include "HttpFetchFile.moc"
<|endoftext|> |
<commit_before>#include "NumericPropertyTableBuilderStub.h"
#include <document-manager/Document.h>
#include <configuration-manager/GroupConfig.h>
#include <search-manager/NumericPropertyTable.h>
#include <glog/logging.h>
#include <cstring> // memcpy
namespace
{
using namespace sf1r;
template<typename T>
void* createPropertyData(
typename NumericPropertyTableBuilderStub::PropertyMap<T>::map_type& propMap,
const std::string& propName
)
{
typename NumericPropertyTableBuilderStub::PropertyMap<T>::table_type& propTable = propMap[propName];
std::size_t num = propTable.size();
void* data = new T[num];
memcpy(data, &propTable[0], num*sizeof(T));
return data;
}
template<typename T>
void insertPropertyMap(
const std::string& propName,
const PropertyValue* propValue,
typename NumericPropertyTableBuilderStub::PropertyMap<T>::map_type& propMap
)
{
T value = 0;
if (propValue)
value = propValue->get<T>();
propMap[propName].push_back(value);
}
}
namespace sf1r
{
NumericPropertyTableBuilderStub::NumericPropertyTableBuilderStub(const std::vector<GroupConfig>& groupConfigs)
: groupConfigs_(groupConfigs)
, lastDocId_(0)
{
// insert property value for doc id 0
for (std::vector<GroupConfig>::const_iterator it = groupConfigs_.begin();
it != groupConfigs_.end(); ++it)
{
const std::string& propName = it->propName;
PropertyDataType propType = it->propType;
insertProperty_(propName, propType, NULL);
}
}
PropertyDataType NumericPropertyTableBuilderStub::getPropertyType_(const std::string& prop) const
{
for (std::vector<GroupConfig>::const_iterator it = groupConfigs_.begin();
it != groupConfigs_.end(); ++it)
{
if (it->propName == prop)
return it->propType;
}
return UNKNOWN_DATA_PROPERTY_TYPE;
}
NumericPropertyTable* NumericPropertyTableBuilderStub::createPropertyTable(const std::string& propertyName)
{
PropertyDataType propType = getPropertyType_(propertyName);
void* data = NULL;
switch(propType)
{
case INT_PROPERTY_TYPE:
data = createPropertyData<int64_t>(intPropMap_, propertyName);
break;
case UNSIGNED_INT_PROPERTY_TYPE:
data = createPropertyData<uint64_t>(uintPropMap_, propertyName);
break;
case FLOAT_PROPERTY_TYPE:
data = createPropertyData<float>(floatPropMap_, propertyName);
break;
case DOUBLE_PROPERTY_TYPE:
data = createPropertyData<double>(doublePropMap_, propertyName);
break;
default:
LOG(ERROR) << "unsupported type " << propType
<< " for group property " << propertyName;
break;
}
if (data)
{
boost::shared_ptr<PropertyData> propData(new PropertyData(propType, data));
return new NumericPropertyTable(propertyName, propData);
}
return NULL;
}
bool NumericPropertyTableBuilderStub::insertDocument(const Document& doc)
{
if (doc.getId() != lastDocId_+1)
{
LOG(ERROR) << "failed to insert doc id " << doc.getId()
<< ", expect id " << (lastDocId_+1);
return false;
}
++lastDocId_;
for (std::vector<GroupConfig>::const_iterator it = groupConfigs_.begin();
it != groupConfigs_.end(); ++it)
{
const std::string& propName = it->propName;
PropertyDataType propType = it->propType;
const PropertyValue pv = doc.property(propName);
if (!insertProperty_(propName, propType, &pv))
return false;
}
return true;
}
bool NumericPropertyTableBuilderStub::insertProperty_(
const std::string& prop,
PropertyDataType type,
const PropertyValue* propValue
)
{
try
{
insertPropMap_(prop, type, propValue);
}catch(const boost::bad_get& e)
{
LOG(ERROR) << "failed in converting type: " << type
<< ", property: " << prop
<< ", exception: " << e.what();
return false;
}
return true;
}
void NumericPropertyTableBuilderStub::insertPropMap_(
const std::string& prop,
PropertyDataType type,
const PropertyValue* propValue
)
{
switch(type)
{
case INT_PROPERTY_TYPE:
insertPropertyMap<int64_t>(prop, propValue, intPropMap_);
break;
case UNSIGNED_INT_PROPERTY_TYPE:
insertPropertyMap<uint64_t>(prop, propValue, uintPropMap_);
break;
case FLOAT_PROPERTY_TYPE:
insertPropertyMap<float>(prop, propValue, floatPropMap_);
break;
case DOUBLE_PROPERTY_TYPE:
insertPropertyMap<double>(prop, propValue, doublePropMap_);
break;
default:
break;
}
}
}
<commit_msg>fix compile error as the parameter of PropertyData constructor changed.<commit_after>#include "NumericPropertyTableBuilderStub.h"
#include <document-manager/Document.h>
#include <configuration-manager/GroupConfig.h>
#include <search-manager/NumericPropertyTable.h>
#include <glog/logging.h>
#include <utility>
#include <cstring> // memcpy
namespace
{
using namespace sf1r;
template<typename T>
boost::shared_ptr<PropertyData> createPropertyData(
PropertyDataType type,
typename NumericPropertyTableBuilderStub::PropertyMap<T>::map_type& propMap,
const std::string& propName
)
{
typename NumericPropertyTableBuilderStub::PropertyMap<T>::table_type& propTable = propMap[propName];
std::size_t num = propTable.size();
void* data = new T[num];
size_t size = num*sizeof(T);
memcpy(data, &propTable[0], size);
boost::shared_ptr<PropertyData> propData(new PropertyData(type, data, size));
return propData;
}
template<typename T>
void insertPropertyMap(
const std::string& propName,
const PropertyValue* propValue,
typename NumericPropertyTableBuilderStub::PropertyMap<T>::map_type& propMap
)
{
T value = 0;
if (propValue)
value = propValue->get<T>();
propMap[propName].push_back(value);
}
}
namespace sf1r
{
NumericPropertyTableBuilderStub::NumericPropertyTableBuilderStub(const std::vector<GroupConfig>& groupConfigs)
: groupConfigs_(groupConfigs)
, lastDocId_(0)
{
// insert property value for doc id 0
for (std::vector<GroupConfig>::const_iterator it = groupConfigs_.begin();
it != groupConfigs_.end(); ++it)
{
const std::string& propName = it->propName;
PropertyDataType propType = it->propType;
insertProperty_(propName, propType, NULL);
}
}
PropertyDataType NumericPropertyTableBuilderStub::getPropertyType_(const std::string& prop) const
{
for (std::vector<GroupConfig>::const_iterator it = groupConfigs_.begin();
it != groupConfigs_.end(); ++it)
{
if (it->propName == prop)
return it->propType;
}
return UNKNOWN_DATA_PROPERTY_TYPE;
}
NumericPropertyTable* NumericPropertyTableBuilderStub::createPropertyTable(const std::string& propertyName)
{
PropertyDataType propType = getPropertyType_(propertyName);
boost::shared_ptr<PropertyData> propData;
switch(propType)
{
case INT_PROPERTY_TYPE:
propData = createPropertyData<int64_t>(INT_PROPERTY_TYPE, intPropMap_, propertyName);
break;
case UNSIGNED_INT_PROPERTY_TYPE:
propData = createPropertyData<uint64_t>(UNSIGNED_INT_PROPERTY_TYPE, uintPropMap_, propertyName);
break;
case FLOAT_PROPERTY_TYPE:
propData = createPropertyData<float>(FLOAT_PROPERTY_TYPE, floatPropMap_, propertyName);
break;
case DOUBLE_PROPERTY_TYPE:
propData = createPropertyData<double>(DOUBLE_PROPERTY_TYPE, doublePropMap_, propertyName);
break;
default:
LOG(ERROR) << "unsupported type " << propType
<< " for group property " << propertyName;
break;
}
if (propData)
{
return new NumericPropertyTable(propertyName, propData);
}
return NULL;
}
bool NumericPropertyTableBuilderStub::insertDocument(const Document& doc)
{
if (doc.getId() != lastDocId_+1)
{
LOG(ERROR) << "failed to insert doc id " << doc.getId()
<< ", expect id " << (lastDocId_+1);
return false;
}
++lastDocId_;
for (std::vector<GroupConfig>::const_iterator it = groupConfigs_.begin();
it != groupConfigs_.end(); ++it)
{
const std::string& propName = it->propName;
PropertyDataType propType = it->propType;
const PropertyValue pv = doc.property(propName);
if (!insertProperty_(propName, propType, &pv))
return false;
}
return true;
}
bool NumericPropertyTableBuilderStub::insertProperty_(
const std::string& prop,
PropertyDataType type,
const PropertyValue* propValue
)
{
try
{
insertPropMap_(prop, type, propValue);
}catch(const boost::bad_get& e)
{
LOG(ERROR) << "failed in converting type: " << type
<< ", property: " << prop
<< ", exception: " << e.what();
return false;
}
return true;
}
void NumericPropertyTableBuilderStub::insertPropMap_(
const std::string& prop,
PropertyDataType type,
const PropertyValue* propValue
)
{
switch(type)
{
case INT_PROPERTY_TYPE:
insertPropertyMap<int64_t>(prop, propValue, intPropMap_);
break;
case UNSIGNED_INT_PROPERTY_TYPE:
insertPropertyMap<uint64_t>(prop, propValue, uintPropMap_);
break;
case FLOAT_PROPERTY_TYPE:
insertPropertyMap<float>(prop, propValue, floatPropMap_);
break;
case DOUBLE_PROPERTY_TYPE:
insertPropertyMap<double>(prop, propValue, doublePropMap_);
break;
default:
break;
}
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee — CLIPP
*
* A CLI for IronBee.
*
* clipp is a framework for handling "inputs", which represent a connection
* and sequence of transactions within that connection. clipp attaches
* input generators to an input consumer. For example, modsec audit logs,
* to an internal IronBee engine. The primary purpose of clipp is to be
* extendible, allowing additional generators and consumers to be written.
*
* In the near future, clipp will also support transformations which take
* inputs and produce inputs. Transformations can be used to filter, modify,
* or aggregate inputs.
*
* To add a new generator:
* -# Write your generator. This should be a functional that takes a
* @c input_t& as a single argument, fills that argument with a new
* input, and returns true. If the input can not be produced, it should
* return false.
* -# Write a factory for your generator. This should be a functin(al) that
* takes a single string argument (the second half of the component) and
* returns a generator.
* -# Add documentation to help() below.
* -# Add your factory to the @c generator_factory_map at the top of main.
*
* To add a new consumer: Follow the directions above for generators, except
* that consumers take a @c const @c input_t& and return true if it is able
* to consume the input. It should also be added to the
* @c consumer_factory_map instead of the @c generator_factory_map.
*
* @author Christopher Alfeld <[email protected]>
*/
#include "input.hpp"
#include "modsec_audit_log_generator.hpp"
#include "raw_generator.hpp"
#include "ironbee_consumer.hpp"
#include "pb_consumer.hpp"
#include "pb_generator.hpp"
#include "view_consumer.hpp"
#include <boost/function.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <string>
using namespace std;
using namespace IronBee::CLIPP;
using IronBee::CLIPP::input_t;
using IronBee::CLIPP::buffer_t;
/**
* A generator of inputs.
*
* Should be a function that takes an input_p as an output argument. If
* input is available it should fill its argument and return true. If no
* more input is available, it should return false.
*
* Errors should be reported via exceptions. Exceptions will not halt
* processing, so generators should arrange to do nothing and return false if
* they are also unable to continue.
**/
typedef boost::function<bool(input_t&)> input_generator_t;
/**
* A consumer of inputs.
*
* Should take a const input_t as an input argument. Should return true if
* the input was accepted and false if it can not accept additional inputs.
*
* Exceptions are as per generators, i.e., use to report errors; does not
* halt processing.
**/
typedef boost::function<bool(const input_t&)> input_consumer_t;
//! A producer of input generators.
typedef boost::function<input_generator_t(const string&)> generator_factory_t;
//! A producer of input consumers.
typedef boost::function<input_consumer_t(const string&)> consumer_factory_t;
//! A map of command line argument to factory.
typedef map<string,generator_factory_t> generator_factory_map_t;
//! A map of command line argument to factory.
typedef map<string,consumer_factory_t> consumer_factory_map_t;
// Generators
input_generator_t init_modsec_generator(const string& arg);
input_generator_t init_raw_generator(const string& arg);
input_generator_t init_pb_generator(const string& arg);
// Consumers
input_consumer_t init_ironbee_consumer(const string& arg);
input_consumer_t init_pb_consumer(const string& arg);
input_consumer_t init_view_consumer(const string& arg);
bool on_error(const string& message);
void help()
{
cerr <<
"Usage: clipp [<flags>] <component>...\n"
"<component> := <name>:<parameters>\n"
"\n"
"Generator components produce inputs.\n"
"Consumer components consume inputs.\n"
"Consumer must be unique (and come last).\n"
"Generators are processed in order and fed to consumer.\n"
"\n"
"Flags:\n"
" --verbose,-v -- Output ID for each input.\n"
"\n"
"Generators:\n"
" pb:<path> -- Read <path> as protobuf.\n"
" modsec:<path> -- Read <path> as modsec audit log.\n"
" One transaction per connection.\n"
" raw:<in>,<out> -- Read <in>,<out> as raw data in and out.\n"
" Single transaction and connection.\n"
"\n"
"Consumers:\n"
" ironbee:<path> -- Internal IronBee using <path> as configuration.\n"
" writepb:<path> -- Output to protobuf file at <path>.\n"
" view: -- Output to stdout for human consumption.\n"
;
}
int main(int argc, char** argv)
{
if (argc == 1) {
help();
return 1;
}
list<string> args;
bool verbose = false;
// Declare generators.
generator_factory_map_t generator_factory_map;
generator_factory_map["modsec"] = &init_modsec_generator;
generator_factory_map["raw"] = &init_raw_generator;
generator_factory_map["pb"] = &init_pb_generator;
// Declare consumers.
consumer_factory_map_t consumer_factory_map;
consumer_factory_map["ironbee"] = &init_ironbee_consumer;
consumer_factory_map["writepb"] = &init_pb_consumer;
consumer_factory_map["view"] = &init_view_consumer;
// Convert argv to args.
for (int i = 1; i < argc; ++i) {
args.push_back(argv[i]);
}
// Parse flags.
if (args.front() == "--verbose" || args.front() == "-v") {
verbose = true;
args.pop_front();
}
// Convert argv into list of pairs of name, parameters.
typedef pair<string,string> component_t;
typedef list<component_t> components_t;
components_t components;
BOOST_FOREACH(const string& arg, args) {
size_t colon_i = arg.find_first_of(':');
if (colon_i == string::npos) {
cerr << "Component " << arg << " lacks :" << endl;
help();
return 1;
}
components.push_back(
make_pair(
arg.substr(0, colon_i),
arg.substr(colon_i + 1, string::npos)
)
);
}
// Last component must be consumer.
input_consumer_t consumer;
{
component_t consumer_component = components.back();
components.pop_back();
consumer_factory_map_t::const_iterator i =
consumer_factory_map.find(consumer_component.first);
if (i == consumer_factory_map.end()) {
cerr << "Final component must be consumer. "
<< components.back().first << " is not a consumer." << endl;
help();
return 1;
}
consumer = i->second(consumer_component.second);
}
// Generators can use significant memory, so delay instantiation.
// But do validate that they exist.
BOOST_FOREACH(const component_t& component, components) {
generator_factory_map_t::const_iterator i =
generator_factory_map.find(component.first);
if (i == generator_factory_map.end()) {
cerr << "Component " << component.first << " is not a generator."
<< endl;
help();
return 1;
}
}
// Loop through components, generating and processing input generators
// as needed to limit the scope of each input generator. As input
// generators can make use of significant memory, it is good to only have
// one around at a time.
BOOST_FOREACH(const component_t& component, components) {
input_generator_t generator;
try {
generator_factory_map_t::iterator i =
generator_factory_map.find(component.first);
if (i != generator_factory_map.end()) {
generator = i->second(component.second);
}
else {
cerr << "Insanity error: Validated component is invalid."
<< " Please report as bug."
<< endl;
return 1;
}
}
catch (const exception& e) {
cerr << "Error initializing "
<< component.first << ":" << component.second << ". "
<< "Message = " << e.what()
<< endl;
return 1;
}
// Process inputs.
input_t input;
bool generator_continue = true;
bool consumer_continue = true;
while (generator_continue && consumer_continue) {
try {
generator_continue = generator(input);
}
catch (const exception& e) {
cerr << "Error generating input: " << e.what() << endl;
continue;
}
if (! generator_continue) {
break;
}
if (verbose ) {
cout << input.id << endl;
}
try {
consumer_continue = consumer(input);
}
catch (const exception& e) {
cerr << "Error consuming input: " << e.what() << endl;
continue;
}
if (! consumer_continue) {
cerr << "Consumer refusing input." << endl;
}
}
}
return 0;
}
input_generator_t init_modsec_generator(const string& str)
{
return ModSecAuditLogGenerator(str, on_error);
}
input_generator_t init_raw_generator(const string& arg)
{
size_t comma_i = arg.find_first_of(',');
if (comma_i == string::npos) {
throw runtime_error("Raw inputs must be _request_,_response_.");
}
return RawGenerator(
arg.substr(0, comma_i),
arg.substr(comma_i+1)
);
}
input_consumer_t init_ironbee_consumer(const string& arg)
{
return IronBeeConsumer(arg);
}
input_generator_t init_pb_generator(const string& arg)
{
return PBGenerator(arg);
}
input_consumer_t init_pb_consumer(const string& arg)
{
return PBConsumer(arg);
}
input_consumer_t init_view_consumer(const string&)
{
return ViewConsumer();
}
bool on_error(const string& message)
{
cerr << "ERROR: " << message << endl;
return true;
}
<commit_msg>clipp: Catch and report exception in consumer construction.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee — CLIPP
*
* A CLI for IronBee.
*
* clipp is a framework for handling "inputs", which represent a connection
* and sequence of transactions within that connection. clipp attaches
* input generators to an input consumer. For example, modsec audit logs,
* to an internal IronBee engine. The primary purpose of clipp is to be
* extendible, allowing additional generators and consumers to be written.
*
* In the near future, clipp will also support transformations which take
* inputs and produce inputs. Transformations can be used to filter, modify,
* or aggregate inputs.
*
* To add a new generator:
* -# Write your generator. This should be a functional that takes a
* @c input_t& as a single argument, fills that argument with a new
* input, and returns true. If the input can not be produced, it should
* return false.
* -# Write a factory for your generator. This should be a functin(al) that
* takes a single string argument (the second half of the component) and
* returns a generator.
* -# Add documentation to help() below.
* -# Add your factory to the @c generator_factory_map at the top of main.
*
* To add a new consumer: Follow the directions above for generators, except
* that consumers take a @c const @c input_t& and return true if it is able
* to consume the input. It should also be added to the
* @c consumer_factory_map instead of the @c generator_factory_map.
*
* @author Christopher Alfeld <[email protected]>
*/
#include "input.hpp"
#include "modsec_audit_log_generator.hpp"
#include "raw_generator.hpp"
#include "ironbee_consumer.hpp"
#include "pb_consumer.hpp"
#include "pb_generator.hpp"
#include "view_consumer.hpp"
#include <boost/function.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <string>
using namespace std;
using namespace IronBee::CLIPP;
using IronBee::CLIPP::input_t;
using IronBee::CLIPP::buffer_t;
/**
* A generator of inputs.
*
* Should be a function that takes an input_p as an output argument. If
* input is available it should fill its argument and return true. If no
* more input is available, it should return false.
*
* Errors should be reported via exceptions. Exceptions will not halt
* processing, so generators should arrange to do nothing and return false if
* they are also unable to continue.
**/
typedef boost::function<bool(input_t&)> input_generator_t;
/**
* A consumer of inputs.
*
* Should take a const input_t as an input argument. Should return true if
* the input was accepted and false if it can not accept additional inputs.
*
* Exceptions are as per generators, i.e., use to report errors; does not
* halt processing.
**/
typedef boost::function<bool(const input_t&)> input_consumer_t;
//! A producer of input generators.
typedef boost::function<input_generator_t(const string&)> generator_factory_t;
//! A producer of input consumers.
typedef boost::function<input_consumer_t(const string&)> consumer_factory_t;
//! A map of command line argument to factory.
typedef map<string,generator_factory_t> generator_factory_map_t;
//! A map of command line argument to factory.
typedef map<string,consumer_factory_t> consumer_factory_map_t;
// Generators
input_generator_t init_modsec_generator(const string& arg);
input_generator_t init_raw_generator(const string& arg);
input_generator_t init_pb_generator(const string& arg);
// Consumers
input_consumer_t init_ironbee_consumer(const string& arg);
input_consumer_t init_pb_consumer(const string& arg);
input_consumer_t init_view_consumer(const string& arg);
bool on_error(const string& message);
void help()
{
cerr <<
"Usage: clipp [<flags>] <component>...\n"
"<component> := <name>:<parameters>\n"
"\n"
"Generator components produce inputs.\n"
"Consumer components consume inputs.\n"
"Consumer must be unique (and come last).\n"
"Generators are processed in order and fed to consumer.\n"
"\n"
"Flags:\n"
" --verbose,-v -- Output ID for each input.\n"
"\n"
"Generators:\n"
" pb:<path> -- Read <path> as protobuf.\n"
" modsec:<path> -- Read <path> as modsec audit log.\n"
" One transaction per connection.\n"
" raw:<in>,<out> -- Read <in>,<out> as raw data in and out.\n"
" Single transaction and connection.\n"
"\n"
"Consumers:\n"
" ironbee:<path> -- Internal IronBee using <path> as configuration.\n"
" writepb:<path> -- Output to protobuf file at <path>.\n"
" view: -- Output to stdout for human consumption.\n"
;
}
int main(int argc, char** argv)
{
if (argc == 1) {
help();
return 1;
}
list<string> args;
bool verbose = false;
// Declare generators.
generator_factory_map_t generator_factory_map;
generator_factory_map["modsec"] = &init_modsec_generator;
generator_factory_map["raw"] = &init_raw_generator;
generator_factory_map["pb"] = &init_pb_generator;
// Declare consumers.
consumer_factory_map_t consumer_factory_map;
consumer_factory_map["ironbee"] = &init_ironbee_consumer;
consumer_factory_map["writepb"] = &init_pb_consumer;
consumer_factory_map["view"] = &init_view_consumer;
// Convert argv to args.
for (int i = 1; i < argc; ++i) {
args.push_back(argv[i]);
}
// Parse flags.
if (args.front() == "--verbose" || args.front() == "-v") {
verbose = true;
args.pop_front();
}
// Convert argv into list of pairs of name, parameters.
typedef pair<string,string> component_t;
typedef list<component_t> components_t;
components_t components;
BOOST_FOREACH(const string& arg, args) {
size_t colon_i = arg.find_first_of(':');
if (colon_i == string::npos) {
cerr << "Component " << arg << " lacks :" << endl;
help();
return 1;
}
components.push_back(
make_pair(
arg.substr(0, colon_i),
arg.substr(colon_i + 1, string::npos)
)
);
}
// Last component must be consumer.
input_consumer_t consumer;
{
component_t consumer_component = components.back();
components.pop_back();
consumer_factory_map_t::const_iterator i =
consumer_factory_map.find(consumer_component.first);
if (i == consumer_factory_map.end()) {
cerr << "Final component must be consumer. "
<< components.back().first << " is not a consumer." << endl;
help();
return 1;
}
try {
consumer = i->second(consumer_component.second);
}
catch (const exception& e) {
cerr << "Error initializing consumer: " << e.what() << endl;
return 1;
}
}
// Generators can use significant memory, so delay instantiation.
// But do validate that they exist.
BOOST_FOREACH(const component_t& component, components) {
generator_factory_map_t::const_iterator i =
generator_factory_map.find(component.first);
if (i == generator_factory_map.end()) {
cerr << "Component " << component.first << " is not a generator."
<< endl;
help();
return 1;
}
}
// Loop through components, generating and processing input generators
// as needed to limit the scope of each input generator. As input
// generators can make use of significant memory, it is good to only have
// one around at a time.
BOOST_FOREACH(const component_t& component, components) {
input_generator_t generator;
try {
generator_factory_map_t::iterator i =
generator_factory_map.find(component.first);
if (i != generator_factory_map.end()) {
generator = i->second(component.second);
}
else {
cerr << "Insanity error: Validated component is invalid."
<< " Please report as bug."
<< endl;
return 1;
}
}
catch (const exception& e) {
cerr << "Error initializing "
<< component.first << ":" << component.second << ". "
<< "Message = " << e.what()
<< endl;
return 1;
}
// Process inputs.
input_t input;
bool generator_continue = true;
bool consumer_continue = true;
while (generator_continue && consumer_continue) {
try {
generator_continue = generator(input);
}
catch (const exception& e) {
cerr << "Error generating input: " << e.what() << endl;
continue;
}
if (! generator_continue) {
break;
}
if (verbose ) {
cout << input.id << endl;
}
try {
consumer_continue = consumer(input);
}
catch (const exception& e) {
cerr << "Error consuming input: " << e.what() << endl;
continue;
}
if (! consumer_continue) {
cerr << "Consumer refusing input." << endl;
}
}
}
return 0;
}
input_generator_t init_modsec_generator(const string& str)
{
return ModSecAuditLogGenerator(str, on_error);
}
input_generator_t init_raw_generator(const string& arg)
{
size_t comma_i = arg.find_first_of(',');
if (comma_i == string::npos) {
throw runtime_error("Raw inputs must be _request_,_response_.");
}
return RawGenerator(
arg.substr(0, comma_i),
arg.substr(comma_i+1)
);
}
input_consumer_t init_ironbee_consumer(const string& arg)
{
return IronBeeConsumer(arg);
}
input_generator_t init_pb_generator(const string& arg)
{
return PBGenerator(arg);
}
input_consumer_t init_pb_consumer(const string& arg)
{
return PBConsumer(arg);
}
input_consumer_t init_view_consumer(const string&)
{
return ViewConsumer();
}
bool on_error(const string& message)
{
cerr << "ERROR: " << message << endl;
return true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include "SimpleCertificateManager.hpp"
using namespace std;
using namespace certificate;
int main() {
#ifdef TEST_PRIVATE_KEY_IDENTIFIER_FILE
try {
ifstream file("rootca.key", ios::binary | ios::ate);
streamsize size = file.tellg();
file.seekg(0, ios::beg);
vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
// cout<<buffer.data();
Key key = Key(buffer.data());
cout << key.gerPrivateKeyIdentifier() << endl;
}
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_PRIVATE_KEY_IDENTIFIER_FILE
#ifdef TEST_PRIVATE_KEY_IDENTIFIER
// openssl pkcs8 -in rootca.key -inform PEM -outform DER -topk8 -nocrypt | openssl sha1 -c
try {
Key key = Key(2048);
cout << key.gerPrivateKeyIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_CERTIFICATE_KEY_IDENTIFIER
try {
ifstream file("test.crt", ios::binary | ios::ate);
streamsize size = file.tellg();
file.seekg(0, ios::beg);
vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
// cout<<buffer.data();
Key key = Key();
key.loadCertificate(buffer.data());
cout << key.getCertificatePrint() << endl;
cout << key.getCertificateKeyIdentifier() << endl;
cout << key.getPublicKeyIdentifier() << endl;
}
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_CERTIFICATE_KEY_IDENTIFIER
#ifdef TEST_KEY_PRINT
try {
Key key = Key(2048); // 2048 bit
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPublicKeyPrint() << endl;
const char* digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
key.genRequest(subject, digest);
string request = key.getRequestString();
cout << key.getRequestPrint() << endl;
key.signRequest("", "0", 365, digest);
cout << key.getCertificatePrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_EMPTY_SUBJECT_NAME
try {
Key key = Key(512);
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPublicKeyPrint() << endl;
key.genRequest();
string request = key.getRequestString();
cout << key.getRequestPrint() << endl;
key.signRequest();
cout << key.getCertificatePrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_LOAD_PUBLIC_KEY
try {
Key key = Key(2048); // 2048 bit
cout << key.getPublicKeyPrint() << endl;
Key test = Key();
test.loadPublicKey(key.getPublicKeyString().c_str());
cout << test.getPublicKeyPrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_LOAD_REQUEST
try {
string rootPrivate, rootPublic, rootRequest, rootCertificate;
Key root = Key(512);
rootPrivate = root.getPrivateKeyString();
rootPublic = root.getPublicKeyString();
const char* digest = "sha256";
const char* countryName = "US";
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
root.genRequest(subject, digest);
rootRequest = root.getRequestString();
cout << root.getRequestPrint() << endl;
Key key2 = Key(rootPrivate.c_str());
key2.loadRequest(rootRequest.c_str());
cout << key2.getRequestPrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
string rootPrivate, rootPublic, rootRequest, rootCertificate;
// generate new root certificate
try {
Key root = Key(2048); // 2048 bit
rootPrivate = root.getPrivateKeyString();
rootPublic = root.getPublicKeyString();
const char* digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com - 한中に";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
root.genRequest(subject, digest);
rootRequest = root.getRequestString();
// ROOTCA(self-signed). csr: null, serial : 0, days : 365, digest : sha256
rootCertificate = root.signRequest("", "0", 365, digest);
cout << root.getCertificatePrint() << endl;
cout << "Certificate Identifier : " << root.getCertificateIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
// load root from string and sign a cert.
string certPrivate, certPublic, certRequest, certCertificate;
try {
Key root = Key(rootPrivate.c_str());
root.loadCertificate(rootCertificate.c_str());
Key cert = Key(2048); // new key
certPrivate = cert.getPrivateKeyString();
certPublic = cert.getPublicKeyString();
const char* digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "CERT-ST";
const char* localityName = "CERT-L";
const char* organizationName = "CERT-O";
const char* organizationalUnitName = "CERT-OU";
const char* commonName = "www.example.org";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
cert.genRequest(subject, digest);
certRequest = cert.getRequestString();
// signed by root. digest : sha512, serial : 1, days : 7
certCertificate = root.signRequest(certRequest, "1", 7, digest);
} catch(std::exception const& e) {
cout << e.what();
}
// create a new csr by existing certificate.
string otherRequest, otherCertificate;
try {
Key root = Key(rootPrivate.c_str());
root.loadCertificate(rootCertificate.c_str());
Key other = Key(2048);
otherRequest = other.getRequestByCertificate(certCertificate.c_str());
// signed by root. digest : sha512, serial : 2, days : 14
otherCertificate = root.signRequest(otherRequest, "2", 14, "sha512");
} catch(std::exception const& e) {
cout << e.what();
}
// check by $ openssl x509 -in cert.crt -text -noout
// verify by $ openssl verify -CAfile root.crt cert.crt other.crt
cout << rootCertificate << endl;
cout << certCertificate << endl;
cout << otherCertificate << endl;
// check by $ openssl req -in other.csr -noout -text
cout << otherRequest <<endl;
return 0;
}<commit_msg>[example] use std::string instead of char*<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include "SimpleCertificateManager.hpp"
using namespace std;
using namespace certificate;
int main() {
#ifdef TEST_PRIVATE_KEY_IDENTIFIER_FILE
try {
ifstream file("rootca.key", ios::binary | ios::ate);
streamsize size = file.tellg();
file.seekg(0, ios::beg);
vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
// cout<<buffer.data();
Key key = Key(buffer.data());
cout << key.gerPrivateKeyIdentifier() << endl;
}
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_PRIVATE_KEY_IDENTIFIER_FILE
#ifdef TEST_PRIVATE_KEY_IDENTIFIER
// openssl pkcs8 -in rootca.key -inform PEM -outform DER -topk8 -nocrypt | openssl sha1 -c
try {
Key key = Key(2048);
cout << key.gerPrivateKeyIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_CERTIFICATE_KEY_IDENTIFIER
try {
ifstream file("test.crt", ios::binary | ios::ate);
streamsize size = file.tellg();
file.seekg(0, ios::beg);
vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
// cout<<buffer.data();
Key key = Key();
key.loadCertificate(buffer.data());
cout << key.getCertificatePrint() << endl;
cout << key.getCertificateKeyIdentifier() << endl;
cout << key.getPublicKeyIdentifier() << endl;
}
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_CERTIFICATE_KEY_IDENTIFIER
#ifdef TEST_KEY_PRINT
try {
Key key = Key(2048); // 2048 bit
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPublicKeyPrint() << endl;
const char* digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
key.genRequest(subject, digest);
string request = key.getRequestString();
cout << key.getRequestPrint() << endl;
key.signRequest("", "0", 365, digest);
cout << key.getCertificatePrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_EMPTY_SUBJECT_NAME
try {
Key key = Key(512);
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPublicKeyPrint() << endl;
key.genRequest();
string request = key.getRequestString();
cout << key.getRequestPrint() << endl;
key.signRequest();
cout << key.getCertificatePrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_LOAD_PUBLIC_KEY
try {
Key key = Key(2048); // 2048 bit
cout << key.getPublicKeyPrint() << endl;
Key test = Key();
test.loadPublicKey(key.getPublicKeyString());
cout << test.getPublicKeyPrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_LOAD_REQUEST
try {
string rootPrivate, rootPublic, rootRequest, rootCertificate;
Key root = Key(512);
rootPrivate = root.getPrivateKeyString();
rootPublic = root.getPublicKeyString();
const char* digest = "sha256";
const char* countryName = "US";
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
root.genRequest(subject, digest);
rootRequest = root.getRequestString();
cout << root.getRequestPrint() << endl;
Key key2 = Key(rootPrivate);
key2.loadRequest(rootRequest);
cout << key2.getRequestPrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
string rootPrivate, rootPublic, rootRequest, rootCertificate;
// generate new root certificate
try {
Key root = Key(2048); // 2048 bit
rootPrivate = root.getPrivateKeyString();
rootPublic = root.getPublicKeyString();
const char* digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com - 한中に";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
root.genRequest(subject, digest);
rootRequest = root.getRequestString();
// ROOTCA(self-signed). csr: null, serial : 0, days : 365, digest : sha256
rootCertificate = root.signRequest("", "0", 365, digest);
cout << root.getCertificatePrint() << endl;
cout << "Certificate Identifier : " << root.getCertificateIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
// load root from string and sign a cert.
string certPrivate, certPublic, certRequest, certCertificate;
try {
Key root = Key(rootPrivate);
root.loadCertificate(rootCertificate);
Key cert = Key(2048); // new key
certPrivate = cert.getPrivateKeyString();
certPublic = cert.getPublicKeyString();
string digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "CERT-ST";
const char* localityName = "CERT-L";
const char* organizationName = "CERT-O";
const char* organizationalUnitName = "CERT-OU";
const char* commonName = "www.example.org";
const char* emailAddress = "[email protected]";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
cert.genRequest(subject, digest);
certRequest = cert.getRequestString();
// signed by root. digest : sha512, serial : 1, days : 7
certCertificate = root.signRequest(certRequest, "1", 7, digest);
} catch(std::exception const& e) {
cout << e.what();
}
// create a new csr by existing certificate.
string otherRequest, otherCertificate;
try {
Key root = Key(rootPrivate);
root.loadCertificate(rootCertificate);
Key other = Key(2048);
otherRequest = other.getRequestByCertificate(certCertificate);
// signed by root. digest : sha512, serial : 2, days : 14
otherCertificate = root.signRequest(otherRequest, "2", 14, "sha512");
} catch(std::exception const& e) {
cout << e.what();
}
// check by $ openssl x509 -in cert.crt -text -noout
// verify by $ openssl verify -CAfile root.crt cert.crt other.crt
cout << rootCertificate << endl;
cout << certCertificate << endl;
cout << otherCertificate << endl;
// check by $ openssl req -in other.csr -noout -text
cout << otherRequest <<endl;
return 0;
}<|endoftext|> |
<commit_before><commit_msg>WaE: class has virtual functions, but destructor is not virtual<commit_after><|endoftext|> |
<commit_before>// See Fossen 2011, chapter 12.3.2
#include "lagrange_allocator.h"
#include <iostream>
template<typename Derived>
inline bool is_fucked(const Eigen::MatrixBase<Derived>& x)
{
return !((x.array() == x.array())).all() && !( (x - x).array() == (x - x).array()).all();
}
// Worlds worst print function :DDD
void printMatrix(Eigen::MatrixXd m){
for(int col = 0; col < 6; col++){
char buffer[512];
for(int row = 0; row < 6; row++){
snprintf( (buffer + (row*8) ), sizeof(buffer), " %f ", m(col, row));
}
ROS_INFO("%s", buffer);
}
}
LagrangeAllocator::LagrangeAllocator()
{
n = 6;
r = 6;
tauSub = nh.subscribe("controlForces", 1, &LagrangeAllocator::tauCallback, this);
uPub = nh.advertise<uranus_dp::ThrusterForces>("controlInputs", 1);
W.setIdentity(6,6); // Default to identity (i.e. no weights)
K.setIdentity(6,6); // Scaling is done on Arduino, so this can be identity
T << 0.7071 , 0.7071 , 0.7071 , 0.7071 , 1 , 1 ,
-0.7071 , 0.7071 , -0.7071 , 0.7071 , 0 , 0 ,
-0.01 , 0.01 , 0.01 , -0.01 , 0 , 0 , // Nonzero elements added to make matrix nonsingular
0.06718, -0.06718, 0.06718, -0.06718, 0 , 0 ,
0.06718, 0.06718, 0.06718, 0.06718, -0.210, -0.210,
0.4172 , 0.4172 , -0.4172 , -0.4172 , -0.165, 0.165;
printMatrix(T);
K_inverse = K.inverse();
computeGeneralizedInverse();
}
void LagrangeAllocator::tauCallback(const geometry_msgs::Wrench& tauMsg)
{
tau << tauMsg.force.x,
tauMsg.force.y,
tauMsg.force.z,
tauMsg.torque.x,
tauMsg.torque.y,
tauMsg.torque.z;
u = K_inverse * T_geninverse * tau;
if(is_fucked(K_inverse))
{
ROS_WARN("K is not invertible");
}
uranus_dp::ThrusterForces uMsg;
uMsg.F1 = u(0);
uMsg.F2 = u(1);
uMsg.F3 = u(2);
uMsg.F4 = u(3);
uMsg.F5 = u(4);
uMsg.F6 = u(5);
uPub.publish(uMsg);
}
void LagrangeAllocator::setWeights(const Eigen::MatrixXd &W_new)
{
bool correctDimensions = ( W_new.rows() == r && W_new.cols() == r );
// ROS_INFO("correctDimensions = %d\n", correctDimensions);
if (!correctDimensions)
{
ROS_WARN_STREAM("Attempt to set weight matrix in LagrangeAllocator with wrong dimensions " << W_new.rows() << "*" << W_new.cols() << ".\n");
return;
}
W = W_new; // I have checked that Eigen does a deep copy here
// New weights mean we must recompute the generalized inverse of the T matrix
computeGeneralizedInverse();
}
void LagrangeAllocator::computeGeneralizedInverse()
{
T_geninverse = W.inverse()*T.transpose() * (T*W.inverse()*T.transpose()).inverse();
if(is_fucked(T_geninverse))
{
ROS_WARN("T_geninverse NAN");
}
if(is_fucked( W.inverse() ))
{
ROS_WARN("W is not invertible");
}
if(is_fucked( (T*W.inverse()*T.transpose()).inverse() ) )
{
ROS_WARN("T * W_inv * T transposed is not invertible");
}
}
<commit_msg>improved matrix print formatting<commit_after>// See Fossen 2011, chapter 12.3.2
#include "lagrange_allocator.h"
#include <iostream>
template<typename Derived>
inline bool is_fucked(const Eigen::MatrixBase<Derived>& x)
{
return !((x.array() == x.array())).all() && !( (x - x).array() == (x - x).array()).all();
}
// Worlds worst print function :DDD
void printMatrix(Eigen::MatrixXd m){
ROS_INFO("----------------------------------");
for(int col = 0; col < 6; col++){
char buffer[512];
for(int row = 0; row < 6; row++){
snprintf( (buffer + (row*8) ), sizeof(buffer), " %f ", m(col, row));
}
ROS_INFO("%s", buffer);
}
ROS_INFO("----------------------------------\n");
}
LagrangeAllocator::LagrangeAllocator()
{
n = 6;
r = 6;
tauSub = nh.subscribe("controlForces", 1, &LagrangeAllocator::tauCallback, this);
uPub = nh.advertise<uranus_dp::ThrusterForces>("controlInputs", 1);
W.setIdentity(6,6); // Default to identity (i.e. no weights)
K.setIdentity(6,6); // Scaling is done on Arduino, so this can be identity
T << 0.7071 , 0.7071 , 0.7071 , 0.7071 , 1 , 1 ,
-0.7071 , 0.7071 , -0.7071 , 0.7071 , 0 , 0 ,
-0.01 , 0.01 , 0.01 , -0.01 , 0 , 0 , // Nonzero elements added to make matrix nonsingular
0.06718, -0.06718, 0.06718, -0.06718, 0 , 0 ,
0.06718, 0.06718, 0.06718, 0.06718, -0.210, -0.210,
0.4172 , 0.4172 , -0.4172 , -0.4172 , -0.165, 0.165;
printMatrix(T);
K_inverse = K.inverse();
computeGeneralizedInverse();
}
void LagrangeAllocator::tauCallback(const geometry_msgs::Wrench& tauMsg)
{
tau << tauMsg.force.x,
tauMsg.force.y,
tauMsg.force.z,
tauMsg.torque.x,
tauMsg.torque.y,
tauMsg.torque.z;
u = K_inverse * T_geninverse * tau;
if(is_fucked(K_inverse))
{
ROS_WARN("K is not invertible");
}
uranus_dp::ThrusterForces uMsg;
uMsg.F1 = u(0);
uMsg.F2 = u(1);
uMsg.F3 = u(2);
uMsg.F4 = u(3);
uMsg.F5 = u(4);
uMsg.F6 = u(5);
uPub.publish(uMsg);
}
void LagrangeAllocator::setWeights(const Eigen::MatrixXd &W_new)
{
bool correctDimensions = ( W_new.rows() == r && W_new.cols() == r );
// ROS_INFO("correctDimensions = %d\n", correctDimensions);
if (!correctDimensions)
{
ROS_WARN_STREAM("Attempt to set weight matrix in LagrangeAllocator with wrong dimensions " << W_new.rows() << "*" << W_new.cols() << ".\n");
return;
}
W = W_new; // I have checked that Eigen does a deep copy here
// New weights mean we must recompute the generalized inverse of the T matrix
computeGeneralizedInverse();
}
void LagrangeAllocator::computeGeneralizedInverse()
{
T_geninverse = W.inverse()*T.transpose() * (T*W.inverse()*T.transpose()).inverse();
printMatrix(T_geninverse);
printMatrix(W);
printMatrix(T);
printMatrix(K_inverse);
if(is_fucked(T_geninverse))
{
ROS_WARN("T_geninverse NAN");
}
if(is_fucked( W.inverse() ))
{
ROS_WARN("W is not invertible");
}
if(is_fucked( (T*W.inverse()*T.transpose()).inverse() ) )
{
ROS_WARN("T * W_inv * T transposed is not invertible");
}
}
<|endoftext|> |
<commit_before>/**
* @file src/ThreadManager.cpp
* @date Mar 2016
* @author PhRG - opticalp.fr
*/
/*
Copyright (c) 2016 Ph. Renaud-Goud / Opticalp
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 "ThreadManager.h"
#include "DataLogger.h"
#include "ModuleTask.h"
#include "Module.h"
#include "Poco/Observer.h"
#include "Poco/NumberFormatter.h"
#include "Poco/ThreadPool.h"
#include "Poco/AutoPtr.h"
using Poco::Observer;
ThreadManager::ThreadManager():
VerboseEntity(name()),
threadPool(2,32), // TODO set maxCapacity from config file
taskManager(threadPool),
cancellingAll(false)
{
taskManager.addObserver(
Observer<ThreadManager, TaskStartedNotification>(
*this, &ThreadManager::onStarted ) );
taskManager.addObserver(
Observer<ThreadManager, TaskFailedNotification>(
*this, &ThreadManager::onFailed ) );
taskManager.addObserver(
Observer<ThreadManager, TaskFinishedNotification>(
*this, &ThreadManager::onFinished ) );
taskManager.addObserver(
Observer<ThreadManager, TaskEnslavedNotification>(
*this, &ThreadManager::onEnslaved ) );
threadPool.addCapacity(32);
}
void ThreadManager::onStarted(TaskStartedNotification* pNf)
{
poco_information(logger(), pNf->task()->name() + " was started");
// TODO:
// - dispatch to a NotificationQueue
pNf->release();
}
void ThreadManager::onFailed(TaskFailedNotification* pNf)
{
Poco::Exception e(pNf->reason());
poco_error(logger(), pNf->task()->name()
+ ": " + e.displayText());
ModuleTask* modTask = dynamic_cast<ModuleTask*>(pNf->task());
if (modTask)
{
poco_information(logger(),
modTask->name() + ": module failed. Cancellation request");
modTask->moduleCancel();
}
// TODO:
// - dispatch to a NotificationQueue
pNf->release();
}
void ThreadManager::onFailedOnCancellation(TaskFailedNotification* pNf)
{
Poco::Exception e(pNf->reason());
poco_information(logger(), pNf->task()->name()
+ ": failed on cancellation request. " + e.displayText());
// TODO:
// - dispatch to a NotificationQueue
pNf->release();
}
void ThreadManager::onFinished(TaskFinishedNotification* pNf)
{
poco_information(logger(), pNf->task()->name() + " has stopped");
ModuleTask* modTask = dynamic_cast<ModuleTask*>(pNf->task());
if (modTask)
{
ModuleTaskPtr pTask(modTask,true);
unregisterModuleTask(pTask);
poco_information(logger(),
pTask->name() + " unregistered... ref count is "
+ Poco::NumberFormatter::format(pTask->referenceCount()));
taskListLock.readLock();
poco_information(logger(), "pending module tasks list size is: "
+ Poco::NumberFormatter::format(pendingModTasks.size()));
// if (pendingModTasks.size() == 1)
// {
// Poco::AutoPtr<ModuleTask> tmpTsk(*pendingModTasks.begin());
// poco_information(logger(),
// "remaining task is: " + tmpTsk->name());
// }
taskListLock.unlock();
poco_information(logger(), "TaskFinishednotification treated. ");
}
// else datalogger task ==> 06.06.16 datalogger does not run in a task any more?
// TODO:
// - dispatch to a NotificationQueue
pNf->release();
}
void ThreadManager::onEnslaved(TaskEnslavedNotification* pNf)
{
poco_information(logger(), pNf->task()->name()
+ " enslaved " + pNf->slave()->name() );
pNf->release();
}
void ThreadManager::startDataLogger(DataLogger* dataLogger)
{
try
{
threadPool.start(*dataLogger);
}
catch (Poco::NoThreadAvailableException& e)
{
// FIXME
poco_error(logger(), dataLogger->name() + " cannot be started, "
+ e.displayText());
}
}
void ThreadManager::startModuleTask(ModuleTaskPtr& pTask)
{
poco_information(logger(), "starting " + pTask->name());
try
{
if (cancellingAll)
{
// FIXME: cancel or not?
// pTask->cancel();
// directly throw exception, in order to not be relying on
// taskMan.start exception throw, based on task.setState while
// cancelling the task
throw Poco::RuntimeException("Cancelling all. "
"Can not start " + pTask->name());
}
taskManager.start(pTask);
}
catch (Poco::NoThreadAvailableException& e)
{
// FIXME
poco_error(logger(), pTask->name() + " cannot be started, "
+ e.displayText());
poco_bugcheck_msg("Poco::NoThreadAvailableException treatment not supported");
}
catch (...)
{
poco_information(logger(), pTask->name()
+ " failed to start");
if (pTask->triggingPort())
pTask->triggingPort()->releaseInputDataOnFailure();
unregisterModuleTask(pTask);
throw;
}
}
void ThreadManager::startSyncModuleTask(ModuleTaskPtr& pTask)
{
poco_information(logger(), "SYNC starting " + pTask->name());
try
{
if (cancellingAll)
{
// FIXME: cancel or not?
// pTask->cancel();
throw Poco::RuntimeException("Cancelling all. "
"Can not sync start " + pTask->name());
}
taskManager.startSync(pTask);
}
catch (...)
{
poco_information(logger(), pTask->name()
+ " failed to sync start");
if (pTask->triggingPort())
pTask->triggingPort()->releaseInputDataOnFailure();
unregisterModuleTask(pTask);
throw;
}
}
size_t ThreadManager::count()
{
Poco::ScopedReadRWLock lock(taskListLock);
return pendingModTasks.size();
}
#define TIME_LAPSE_WAIT_ALL 5
#include "ModuleManager.h"
void ThreadManager::waitAll()
{
bool stoppedOnCancel = false;
// joinAll does not work here,
// since it seems that it locks the recursive creation of new threads...
// We use an event instead.
while (count() || threadPool.used() || cancellingAll)
{
//Poco::TaskManager::TaskList list = taskManager.taskList();
//std::string nameList("\n");
//for (Poco::TaskManager::TaskList::iterator it = list.begin(),
// ite = list.end(); it != ite; it++)
// nameList += " - " + (*it)->name() + "\n";
//nameList.erase(nameList.end()-1);
//poco_information(logger(), "active threads are : " + nameList);
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
if (cancellingAll)
stoppedOnCancel = true;
}
if (stoppedOnCancel)
{
ModuleManager& modMan = Poco::Util::Application::instance().getSubsystem<ModuleManager>();
while (!modMan.allModuleReady())
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
throw Poco::RuntimeException("waitAll","Cancellation upon user request");
}
poco_information(logger(), "All threads have stopped. ");
}
void ThreadManager::registerNewModuleTask(ModuleTaskPtr& pTask)
{
if (cancellingAll)
throw Poco::RuntimeException("Cancelling, "
"can not register the new task: "
+ pTask->name());
Poco::ScopedWriteRWLock lock(taskListLock);
pendingModTasks.insert(pTask);
}
void ThreadManager::unregisterModuleTask(ModuleTaskPtr& pTask)
{
pTask->taskFinished();
Poco::ScopedWriteRWLock lock(taskListLock);
if (pendingModTasks.erase(pTask) < 1)
poco_warning(logger(), "Failed to erase the task " + pTask->name()
+ " from the thread manager");
poco_information(logger(), pTask->name() + " erased from the thread manager. "
"ref cnt is now: "
+ Poco::NumberFormatter::format(pTask->referenceCount()));
}
void ThreadManager::cancelAll()
{
if (cancellingAll)
return;
cancellingAll = true;
taskListLock.readLock();
std::set<ModuleTaskPtr> tempModTasks = pendingModTasks;
taskListLock.unlock();
poco_notice(logger(), "CancelAll: Dispatching cancel() to all active tasks");
for (std::set<ModuleTaskPtr>::iterator it = tempModTasks.begin(),
ite = tempModTasks.end(); it != ite; it++)
{
ModuleTaskPtr tsk(*it);
poco_information(logger(), "CancelAll: cancelling " + tsk->name());
tsk->cancel();
}
poco_information(logger(), "CancelAll: All active tasks cancelled. Wait for them to delete. ");
while (count() || threadPool.used())
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
poco_information(logger(), "No more pending task. Wait for all modules being ready... ");
ModuleManager& modMan = Poco::Util::Application::instance().getSubsystem<ModuleManager>();
while (!modMan.allModuleReady())
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
poco_information(logger(), "All modules ready. CancelAll done. ");
cancellingAll = false;
}
void ThreadManager::startModuleCancellationListener(Poco::Runnable& runnable)
{
threadPool.start(runnable);
}
<commit_msg>Remove pNf->release(); from observers<commit_after>/**
* @file src/ThreadManager.cpp
* @date Mar 2016
* @author PhRG - opticalp.fr
*/
/*
Copyright (c) 2016 Ph. Renaud-Goud / Opticalp
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 "ThreadManager.h"
#include "DataLogger.h"
#include "ModuleTask.h"
#include "Module.h"
#include "Poco/Observer.h"
#include "Poco/NumberFormatter.h"
#include "Poco/ThreadPool.h"
#include "Poco/AutoPtr.h"
using Poco::Observer;
ThreadManager::ThreadManager():
VerboseEntity(name()),
threadPool(2,32), // TODO set maxCapacity from config file
taskManager(threadPool),
cancellingAll(false)
{
taskManager.addObserver(
Observer<ThreadManager, TaskStartedNotification>(
*this, &ThreadManager::onStarted ) );
taskManager.addObserver(
Observer<ThreadManager, TaskFailedNotification>(
*this, &ThreadManager::onFailed ) );
taskManager.addObserver(
Observer<ThreadManager, TaskFinishedNotification>(
*this, &ThreadManager::onFinished ) );
taskManager.addObserver(
Observer<ThreadManager, TaskEnslavedNotification>(
*this, &ThreadManager::onEnslaved ) );
threadPool.addCapacity(32);
}
void ThreadManager::onStarted(TaskStartedNotification* pNf)
{
poco_information(logger(), pNf->task()->name() + " was started");
// TODO:
// - dispatch to a NotificationQueue
// pNf->release();
}
void ThreadManager::onFailed(TaskFailedNotification* pNf)
{
Poco::Exception e(pNf->reason());
poco_error(logger(), pNf->task()->name()
+ ": " + e.displayText());
ModuleTask* modTask = dynamic_cast<ModuleTask*>(pNf->task());
if (modTask)
{
poco_information(logger(),
modTask->name() + ": module failed. Cancellation request");
modTask->moduleCancel();
}
// TODO:
// - dispatch to a NotificationQueue
// pNf->release();
}
void ThreadManager::onFailedOnCancellation(TaskFailedNotification* pNf)
{
Poco::Exception e(pNf->reason());
poco_information(logger(), pNf->task()->name()
+ ": failed on cancellation request. " + e.displayText());
// TODO:
// - dispatch to a NotificationQueue
// pNf->release();
}
void ThreadManager::onFinished(TaskFinishedNotification* pNf)
{
poco_information(logger(), pNf->task()->name() + " has stopped");
ModuleTask* modTask = dynamic_cast<ModuleTask*>(pNf->task());
if (modTask)
{
ModuleTaskPtr pTask(modTask,true);
unregisterModuleTask(pTask);
poco_information(logger(),
pTask->name() + " unregistered... ref count is "
+ Poco::NumberFormatter::format(pTask->referenceCount()));
taskListLock.readLock();
poco_information(logger(), "pending module tasks list size is: "
+ Poco::NumberFormatter::format(pendingModTasks.size()));
// if (pendingModTasks.size() == 1)
// {
// Poco::AutoPtr<ModuleTask> tmpTsk(*pendingModTasks.begin());
// poco_information(logger(),
// "remaining task is: " + tmpTsk->name());
// }
taskListLock.unlock();
poco_information(logger(), "TaskFinishednotification treated. ");
}
// else datalogger task ==> 06.06.16 datalogger does not run in a task any more?
// TODO:
// - dispatch to a NotificationQueue
// pNf->release();
}
void ThreadManager::onEnslaved(TaskEnslavedNotification* pNf)
{
poco_information(logger(), pNf->task()->name()
+ " enslaved " + pNf->slave()->name() );
// pNf->release();
}
void ThreadManager::startDataLogger(DataLogger* dataLogger)
{
try
{
threadPool.start(*dataLogger);
}
catch (Poco::NoThreadAvailableException& e)
{
// FIXME
poco_error(logger(), dataLogger->name() + " cannot be started, "
+ e.displayText());
}
}
void ThreadManager::startModuleTask(ModuleTaskPtr& pTask)
{
poco_information(logger(), "starting " + pTask->name());
try
{
if (cancellingAll)
{
// FIXME: cancel or not?
// pTask->cancel();
// directly throw exception, in order to not be relying on
// taskMan.start exception throw, based on task.setState while
// cancelling the task
throw Poco::RuntimeException("Cancelling all. "
"Can not start " + pTask->name());
}
taskManager.start(pTask);
}
catch (Poco::NoThreadAvailableException& e)
{
// FIXME
poco_error(logger(), pTask->name() + " cannot be started, "
+ e.displayText());
poco_bugcheck_msg("Poco::NoThreadAvailableException treatment not supported");
}
catch (...)
{
poco_information(logger(), pTask->name()
+ " failed to start");
if (pTask->triggingPort())
pTask->triggingPort()->releaseInputDataOnFailure();
unregisterModuleTask(pTask);
throw;
}
}
void ThreadManager::startSyncModuleTask(ModuleTaskPtr& pTask)
{
poco_information(logger(), "SYNC starting " + pTask->name());
try
{
if (cancellingAll)
{
// FIXME: cancel or not?
// pTask->cancel();
throw Poco::RuntimeException("Cancelling all. "
"Can not sync start " + pTask->name());
}
taskManager.startSync(pTask);
}
catch (...)
{
poco_information(logger(), pTask->name()
+ " failed to sync start");
if (pTask->triggingPort())
pTask->triggingPort()->releaseInputDataOnFailure();
unregisterModuleTask(pTask);
throw;
}
}
size_t ThreadManager::count()
{
Poco::ScopedReadRWLock lock(taskListLock);
return pendingModTasks.size();
}
#define TIME_LAPSE_WAIT_ALL 5
#include "ModuleManager.h"
void ThreadManager::waitAll()
{
bool stoppedOnCancel = false;
// joinAll does not work here,
// since it seems that it locks the recursive creation of new threads...
// We use an event instead.
while (count() || threadPool.used() || cancellingAll)
{
//Poco::TaskManager::TaskList list = taskManager.taskList();
//std::string nameList("\n");
//for (Poco::TaskManager::TaskList::iterator it = list.begin(),
// ite = list.end(); it != ite; it++)
// nameList += " - " + (*it)->name() + "\n";
//nameList.erase(nameList.end()-1);
//poco_information(logger(), "active threads are : " + nameList);
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
if (cancellingAll)
stoppedOnCancel = true;
}
if (stoppedOnCancel)
{
ModuleManager& modMan = Poco::Util::Application::instance().getSubsystem<ModuleManager>();
while (!modMan.allModuleReady())
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
throw Poco::RuntimeException("waitAll","Cancellation upon user request");
}
poco_information(logger(), "All threads have stopped. ");
}
void ThreadManager::registerNewModuleTask(ModuleTaskPtr& pTask)
{
if (cancellingAll)
throw Poco::RuntimeException("Cancelling, "
"can not register the new task: "
+ pTask->name());
Poco::ScopedWriteRWLock lock(taskListLock);
pendingModTasks.insert(pTask);
}
void ThreadManager::unregisterModuleTask(ModuleTaskPtr& pTask)
{
pTask->taskFinished();
Poco::ScopedWriteRWLock lock(taskListLock);
if (pendingModTasks.erase(pTask) < 1)
poco_warning(logger(), "Failed to erase the task " + pTask->name()
+ " from the thread manager");
poco_information(logger(), pTask->name() + " erased from the thread manager. "
"ref cnt is now: "
+ Poco::NumberFormatter::format(pTask->referenceCount()));
}
void ThreadManager::cancelAll()
{
if (cancellingAll)
return;
cancellingAll = true;
taskListLock.readLock();
std::set<ModuleTaskPtr> tempModTasks = pendingModTasks;
taskListLock.unlock();
poco_notice(logger(), "CancelAll: Dispatching cancel() to all active tasks");
for (std::set<ModuleTaskPtr>::iterator it = tempModTasks.begin(),
ite = tempModTasks.end(); it != ite; it++)
{
ModuleTaskPtr tsk(*it);
poco_information(logger(), "CancelAll: cancelling " + tsk->name());
tsk->cancel();
}
poco_information(logger(), "CancelAll: All active tasks cancelled. Wait for them to delete. ");
while (count() || threadPool.used())
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
poco_information(logger(), "No more pending task. Wait for all modules being ready... ");
ModuleManager& modMan = Poco::Util::Application::instance().getSubsystem<ModuleManager>();
while (!modMan.allModuleReady())
Poco::Thread::sleep(TIME_LAPSE_WAIT_ALL);
poco_information(logger(), "All modules ready. CancelAll done. ");
cancellingAll = false;
}
void ThreadManager::startModuleCancellationListener(Poco::Runnable& runnable)
{
threadPool.start(runnable);
}
<|endoftext|> |
<commit_before>/// \author A0112054Y
#include "stdafx.h"
#include "internal/controller.h"
#include "internal/action/add_task.h"
#include "internal/action/update_task.h"
#include "internal/action/delete_task.h"
#include "internal/action/get_task.h"
#include "internal/action/delete_task.h"
#include "internal/action/update_task.h"
#include "internal/model.h"
#include "api.h"
namespace You {
namespace QueryEngine {
const std::wstring Query::logCategory = L"[QE]";
std::unique_ptr<Query>
QueryEngine::AddTask(Task::Description description, Task::Time deadline,
Task::Priority priority, Task::Dependencies dependencies) {
using AddTask = Internal::Action::AddTask;
return std::unique_ptr<Query>(new AddTask(description, deadline,
priority, dependencies));
}
std::unique_ptr<Query>
QueryEngine::GetTask(const Filter& filter) {
using GetTask = Internal::Action::GetTask;
return std::unique_ptr<Query>(new GetTask(filter));
}
std::unique_ptr<Query>
QueryEngine::GetTask(const Filter& filter,
const Comparator& comparator) {
using GetTask = Internal::Action::GetTask;
return std::unique_ptr<Query>(new GetTask(filter, comparator));
}
std::unique_ptr<Query>
QueryEngine::DeleteTask(Task::ID id) {
using DeleteTask = Internal::Action::DeleteTask;
return std::unique_ptr<Query>(new DeleteTask(id));
}
std::unique_ptr<Query>
QueryEngine::UpdateTask(Task::ID id, Task::Description description,
Task::Time deadline, Task::Priority priority, Task::Dependencies dependencies) {
using UpdateTask = Internal::Action::UpdateTask;
return std::unique_ptr<Query>(new UpdateTask(id,
description, deadline, priority, dependencies));
}
std::unique_ptr<Query>
QueryEngine::UpdateTask(Task::ID id, bool completed) {
using UpdateTask = Internal::Action::UpdateTask;
return std::unique_ptr<Query>(new UpdateTask(id, completed));
}
Response QueryEngine::executeQuery(std::unique_ptr<Query> query) {
return query->execute(Internal::State::get());
}
} // namespace QueryEngine
} // namespace You
<commit_msg>Add API for Undo<commit_after>/// \author A0112054Y
#include "stdafx.h"
#include "internal/controller.h"
#include "internal/action/add_task.h"
#include "internal/action/update_task.h"
#include "internal/action/delete_task.h"
#include "internal/action/get_task.h"
#include "internal/action/delete_task.h"
#include "internal/action/update_task.h"
#include "internal/action/undo.h"
#include "internal/model.h"
#include "api.h"
namespace You {
namespace QueryEngine {
const std::wstring Query::logCategory = L"[QE]";
std::unique_ptr<Query>
QueryEngine::AddTask(Task::Description description, Task::Time deadline,
Task::Priority priority, Task::Dependencies dependencies) {
using AddTask = Internal::Action::AddTask;
return std::unique_ptr<Query>(new AddTask(description, deadline,
priority, dependencies));
}
std::unique_ptr<Query>
QueryEngine::GetTask(const Filter& filter) {
using GetTask = Internal::Action::GetTask;
return std::unique_ptr<Query>(new GetTask(filter));
}
std::unique_ptr<Query>
QueryEngine::GetTask(const Filter& filter,
const Comparator& comparator) {
using GetTask = Internal::Action::GetTask;
return std::unique_ptr<Query>(new GetTask(filter, comparator));
}
std::unique_ptr<Query>
QueryEngine::DeleteTask(Task::ID id) {
using DeleteTask = Internal::Action::DeleteTask;
return std::unique_ptr<Query>(new DeleteTask(id));
}
std::unique_ptr<Query>
QueryEngine::UpdateTask(Task::ID id, Task::Description description,
Task::Time deadline, Task::Priority priority, Task::Dependencies dependencies) {
using UpdateTask = Internal::Action::UpdateTask;
return std::unique_ptr<Query>(new UpdateTask(id,
description, deadline, priority, dependencies));
}
std::unique_ptr<Query>
QueryEngine::UpdateTask(Task::ID id, bool completed) {
using UpdateTask = Internal::Action::UpdateTask;
return std::unique_ptr<Query>(new UpdateTask(id, completed));
}
std::unique_ptr<Query>
QueryEngine::Undo() {
using Undo = Internal::Action::Undo;
return std::unique_ptr<Query>(new Undo());
}
Response QueryEngine::executeQuery(std::unique_ptr<Query> query) {
return query->execute(Internal::State::get());
}
} // namespace QueryEngine
} // namespace You
<|endoftext|> |
<commit_before>/* Tower-Defence
*
* Author: Jukka Vatjus-Anttila <[email protected]>
*
* For conditions of distribution and use, see copyright notice in LICENSE.txt
*/
#include <iostream>
#include <cstdlib>
#include <sstream>
#include "GameLogic/cGameEntity.h"
#include "GameLogic/cMapper.h"
#include "GameLogic/entityEnums.h"
#include "Renderer/cRenderer.h"
//#include "EventHandler/cEventHandler.h"
#include <SFML/System.hpp>
#include "common.h"
bool appRunning;
int main(int argc, char** argv)
{
std::cout << "Hello tower defense - experimental branch on github - v0.1.0!\n";
appRunning = true;
// Initialize variables for gameloop timer logic
sf::Clock clock;
const int framerate = 60;
float framestartTime = 0;
float difference = 0;
float sleepTime = 0;
float frameBudget = 1/(float)framerate;
// Singletons
renderer::cRenderer *render;
gamelogic::cMapper *mapper;
//IOHandling::cEventHandler *InputOutput;
try {
render = renderer::cRenderer::getInstance();
mapper = gamelogic::cMapper::getInstance();
//InputOutput = IOHandling::cEventHandler::getInstance();
} catch (std::bad_alloc& e) {
std::cout << "Initial memory allocation for mapper and renderer failed! " << e.what() << "\n";
return EXIT_FAILURE;
}
// Start running the clock just before gameloop
clock.Reset();
// Gameloop
while(appRunning)
{
// Get current framestart time
framestartTime = clock.GetElapsedTime();
// Update game logic and renderer instance.
mapper->update(framestartTime);
render->update(framestartTime);
//InputOutput->update();
// Get time elapsed in game logic update
difference = clock.GetElapsedTime() - framestartTime;
// If difference is smaller than budgeted, rest until next frame
if (difference < frameBudget)
{
// Rendering budgets:
// 60fps = 16,667ms
// 30fps = 33,333ms
// 10fps = 100ms
// 5fps = 200ms
sleepTime = frameBudget - difference;
// Sleep for rest of the frame
sf::Sleep(sleepTime);
}
}
// End of gameloop. Destroy mapper.
//delete InputOutput;
delete render;
delete mapper;
return EXIT_SUCCESS;
}
<commit_msg>Included eventHandling back to the project.<commit_after>/* Tower-Defence
*
* Author: Jukka Vatjus-Anttila <[email protected]>
*
* For conditions of distribution and use, see copyright notice in LICENSE.txt
*/
#include <iostream>
#include <cstdlib>
#include <sstream>
#include "GameLogic/cGameEntity.h"
#include "GameLogic/cMapper.h"
#include "GameLogic/entityEnums.h"
#include "Renderer/cRenderer.h"
#include "EventHandler/cEventHandler.h"
#include <SFML/System.hpp>
#include "common.h"
bool appRunning;
void print() { ; }
int main(int argc, char** argv)
{
std::cout << "Hello tower defense - experimental branch on github - v0.1.0!\n";
appRunning = true;
// Initialize variables for gameloop timer logic
sf::Clock clock;
const int framerate = 60;
float framestartTime = 0;
float difference = 0;
float sleepTime = 0;
float frameBudget = 1/(float)framerate;
// Singletons
renderer::cRenderer *render;
gamelogic::cMapper *mapper;
IOHandling::cEventHandler *eventHandler;
try {
render = renderer::cRenderer::getInstance();
mapper = gamelogic::cMapper::getInstance();
eventHandler = IOHandling::cEventHandler::getInstance();
} catch (std::bad_alloc& e) {
std::cout << "Initial memory allocation for mapper and renderer failed! " << e.what() << "\n";
return EXIT_FAILURE;
}
// Start running the clock just before gameloop
clock.Reset();
// Gameloop
while(appRunning)
{
// Get current framestart time
framestartTime = clock.GetElapsedTime();
// Update game logic and renderer instance.
mapper->update(framestartTime);
render->update(framestartTime);
if (eventHandler->hasPendingEvents())
eventHandler->update();
// Get time elapsed in game logic update
difference = clock.GetElapsedTime() - framestartTime;
// If difference is smaller than budgeted, rest until next frame
if (difference < frameBudget)
{
// Rendering budgets:
// 60fps = 16,667ms
// 30fps = 33,333ms
// 10fps = 100ms
// 5fps = 200ms
sleepTime = frameBudget - difference;
// Sleep for rest of the frame
sf::Sleep(sleepTime);
}
}
// End of gameloop. Destroy mapper.
delete eventHandler;
delete render;
delete mapper;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "UniquePathsII.hpp"
int UniquePathsII::uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid)
{
int m = obstacleGrid.size();
if (m == 0)
return 0;
int n = obstacleGrid[0].size();
if (n == 0)
return 0;
vector<int> dp(n, 1);
dp[0] = (obstacleGrid[0][0] == 1) ? 0 : 1;
for (int j = 1; j < n; j++) {
if (dp[j - 1] == 0 || obstacleGrid[0][j] == 1)
dp[j] = 0;
else
dp[j] = 1;
}
for (int i = 1; i < m; i++) {
if (dp[0] == 0 || obstacleGrid[i][0] == 1)
dp[0] = 0;
else
dp[0] = 1;
for (int j = 1; j < n; j++) {
int up = 0;
if (dp[j] != 0 && obstacleGrid[i][j] != 1)
up = dp[j];
int left = 0;
if (dp[j - 1] != 0 && obstacleGrid[i][j] != 1)
left = dp[j - 1];
dp[j] = up + left;
}
}
return dp[n - 1];
}
<commit_msg>Refine Problem 63. Unique Paths II<commit_after>#include "UniquePathsII.hpp"
int UniquePathsII::uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid)
{
int m = obstacleGrid.size();
if (m == 0) return 0;
int n = obstacleGrid[0].size();
if (n == 0) return 0;
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = (obstacleGrid[0][0] == 0) ? 1 : 0;
for (int i = 1; i < m; i++)
dp[i][0] = (dp[i - 1][0] && obstacleGrid[i][0] == 0) ? 1 : 0;
for (int j = 1; j < n; j++)
dp[0][j] = (dp[0][j - 1] && obstacleGrid[0][j] == 0) ? 1 : 0;
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
dp[i][j] = (obstacleGrid[i][j] == 1) ? 0 : dp[i - 1][j] + dp[i][j - 1];
return dp[m - 1][n - 1];
}
<|endoftext|> |
<commit_before>#include <mitkClaronInterface.h>
#include <string>
#include <MTC.h>
#include <math.h>
#include <mitkVector.h>
mitk::ClaronInterface::ClaronInterface(std::string calibrationDir, std::string toolFilesDir)
{
sprintf(this->calibrationDir, calibrationDir.c_str());
sprintf(this->markerDir,toolFilesDir.c_str());
}
bool mitk::ClaronInterface::StartTracking()
{
isTracking = false;
MTC( Cameras_AttachAvailableCameras(calibrationDir) ); //Connect to camera
if (Cameras_Count() < 1)
{
printf("No camera found!\n");
return false;
}
try
{
//Step 1: initialize cameras
MTC(Cameras_HistogramEqualizeImagesSet(true)); //set the histogram equalizing
MTC( Cameras_ItemGet(0, &CurrCamera) ); //Obtain a handle to the first/only camera in the array
//Step 2: Load the marker templates
MTC( Markers_LoadTemplates(markerDir) ); //Path to directory where the marker templates are
printf("Loaded %d marker templates\n",Markers_TemplatesCount());
//Step 3: Wait a 20 frames
for (int i=0; i<20; i++)//the first 20 frames are auto-adjustment frames, we ignore them
{
MTC( Cameras_GrabFrame(NULL) ); //Grab a frame (all cameras together)
MTC( Markers_ProcessFrame(NULL) ); //Proces the frame(s) to obtain measurements
}
//Step 4: Initialize IdentifiedMarkers and PoseXf
IdentifiedMarkers = Collection_New();
PoseXf = Xform3D_New();
//now we are tracking...
/* MTHome is not in use. The following code has to be activated if you want to use MTHome!
//Initialize MTHome
if ( getMTHome (MTHome, sizeof(MTHome)) < 0 )
{
// No Environment
printf("MTHome environment variable is not set!\n");
}*/
}
catch(...)
{
Cameras_Detach();
printf(" Error while connecting MicronTracker!\n -------------------------------");
return false;
}
isTracking = true;
return true;
}
bool mitk::ClaronInterface::StopTracking()
{
if (isTracking)
{
//free up the resources
Collection_Free(IdentifiedMarkers);
Xform3D_Free(PoseXf);
//stop the camera
Cameras_Detach();
//now tracking is stopped
isTracking = false;
return true;
}
else
{
return false;
}
}
std::vector<mitk::claronToolHandle> mitk::ClaronInterface::GetAllActiveTools()
{
//Set returnvalue
std::vector<claronToolHandle> returnValue;
//Here, MTC internally maintains the measurement results.
//Those results can be accessed until the next call to Markers_ProcessFrame, when they
//are updated to reflect the next frame's content.
//First, we will obtain the collection of the markers that were identified.
MTC( Markers_IdentifiedMarkersGet(NULL, IdentifiedMarkers) );
//Now we iterate on the identified markers and add them to the returnvalue
for (int j=1; j<=Collection_Count(IdentifiedMarkers); j++)
{
// Obtain the marker's handle, and use it to obtain the pose in the current camera's space
// using our Xform3D object, PoseXf.
mtHandle Marker = Collection_Int(IdentifiedMarkers, j);
returnValue.push_back(Marker);
}
return returnValue;
}
void mitk::ClaronInterface::GrabFrame()
{
MTC( Cameras_GrabFrame(NULL) ); //Grab a frame
MTC( Markers_ProcessFrame(NULL) ); //Process the frame(s)
}
std::vector<double> mitk::ClaronInterface::GetTipPosition(mitk::claronToolHandle c)
{
std::vector<double> returnValue;
double Position[3];
mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle
mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle
mtHandle m2c = Xform3D_New(); // marker to camera xform handle
//Get m2c
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) );
//Get t2m
MTC( Marker_Tooltip2MarkerXfGet (c, t2m ));
//Transform both to t2c
MTC(Xform3D_Concatenate(t2m,m2c,t2c));
//Get position
MTC( Xform3D_ShiftGet(t2c, Position) );
// Here we have to negate the X- and Y-coordinates because of a bug of the
// MTC-library.
returnValue.push_back(-Position[0]);
returnValue.push_back(-Position[1]);
returnValue.push_back(Position[2]);
return returnValue;
}
std::vector<double> mitk::ClaronInterface::GetPosition(claronToolHandle c)
{
std::vector<double> returnValue;
double Position[3];
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) );
MTC( Xform3D_ShiftGet(PoseXf, Position) );
// Here we have to negate the X- and Y-coordinates because of a bug of the
// MTC-library.
returnValue.push_back(-Position[0]);
returnValue.push_back(-Position[1]);
returnValue.push_back(Position[2]);
return returnValue;
}
std::vector<double> mitk::ClaronInterface::GetTipQuaternions(claronToolHandle c)
{
std::vector<double> returnValue;
mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle
mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle
mtHandle m2c = Xform3D_New(); // marker to camera xform handle
//Get m2c
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) );
//Get t2m
MTC( Marker_Tooltip2MarkerXfGet (c, t2m ));
//Transform both to t2c
MTC(Xform3D_Concatenate(t2m,m2c,t2c));
//get the Claron-Quaternion
double Quarternions[4];
MTC( Xform3D_RotQuaternionsGet(t2c, Quarternions) );
mitk::Quaternion claronQuaternion;
//note: claron quarternion has different order than the mitk quarternion
claronQuaternion[3] = Quarternions[0];
claronQuaternion[0] = Quarternions[1];
claronQuaternion[1] = Quarternions[2];
claronQuaternion[2] = Quarternions[3];
// Here we have to make a -90-turn around the Y-axis because of a bug of the
// MTC-library.
mitk::Quaternion minusNinetyDegreeY;
minusNinetyDegreeY[3] = sqrt(2.0)/2.0;
minusNinetyDegreeY[0] = 0;
minusNinetyDegreeY[1] = -1.0/(sqrt(2.0));
minusNinetyDegreeY[2] = 0;
//calculate the result...
mitk::Quaternion erg = (minusNinetyDegreeY*claronQuaternion);
returnValue.push_back(erg[3]);
returnValue.push_back(erg[0]);
returnValue.push_back(erg[1]);
returnValue.push_back(erg[2]);
return returnValue;
}
std::vector<double> mitk::ClaronInterface::GetQuaternions(claronToolHandle c)
{
std::vector<double> returnValue;
//TODO by Alfred 3.3.2009: I'm afraid we have a bug here. Look at the method
// GetTipQuaternions... the same has to be done here
// to compensate the bug in the MTC-lib.
double Quarternions[4];
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) );
MTC( Xform3D_RotQuaternionsGet(PoseXf, Quarternions) );
for (int i = 0; i<4; i++) returnValue.push_back(Quarternions[i]);
return returnValue;
}
const char* mitk::ClaronInterface::GetName(claronToolHandle c)
{
char MarkerName[MT_MAX_STRING_LENGTH];
MTC( Marker_NameGet(c, MarkerName, MT_MAX_STRING_LENGTH, 0) );
std::string returnValue = std::string(MarkerName);
return MarkerName;
}
bool mitk::ClaronInterface::IsTracking()
{
return this->isTracking;
}
bool mitk::ClaronInterface::IsMicronTrackerInstalled()
{
return true;
}
<commit_msg>FIX (#1972): Now a heap pointer ist returned instead of a stack pointer in method GetName().<commit_after>#include <mitkClaronInterface.h>
#include <string>
#include <MTC.h>
#include <math.h>
#include <mitkVector.h>
mitk::ClaronInterface::ClaronInterface(std::string calibrationDir, std::string toolFilesDir)
{
sprintf(this->calibrationDir, calibrationDir.c_str());
sprintf(this->markerDir,toolFilesDir.c_str());
}
bool mitk::ClaronInterface::StartTracking()
{
isTracking = false;
MTC( Cameras_AttachAvailableCameras(calibrationDir) ); //Connect to camera
if (Cameras_Count() < 1)
{
printf("No camera found!\n");
return false;
}
try
{
//Step 1: initialize cameras
MTC(Cameras_HistogramEqualizeImagesSet(true)); //set the histogram equalizing
MTC( Cameras_ItemGet(0, &CurrCamera) ); //Obtain a handle to the first/only camera in the array
//Step 2: Load the marker templates
MTC( Markers_LoadTemplates(markerDir) ); //Path to directory where the marker templates are
printf("Loaded %d marker templates\n",Markers_TemplatesCount());
//Step 3: Wait a 20 frames
for (int i=0; i<20; i++)//the first 20 frames are auto-adjustment frames, we ignore them
{
MTC( Cameras_GrabFrame(NULL) ); //Grab a frame (all cameras together)
MTC( Markers_ProcessFrame(NULL) ); //Proces the frame(s) to obtain measurements
}
//Step 4: Initialize IdentifiedMarkers and PoseXf
IdentifiedMarkers = Collection_New();
PoseXf = Xform3D_New();
//now we are tracking...
/* MTHome is not in use. The following code has to be activated if you want to use MTHome!
//Initialize MTHome
if ( getMTHome (MTHome, sizeof(MTHome)) < 0 )
{
// No Environment
printf("MTHome environment variable is not set!\n");
}*/
}
catch(...)
{
Cameras_Detach();
printf(" Error while connecting MicronTracker!\n -------------------------------");
return false;
}
isTracking = true;
return true;
}
bool mitk::ClaronInterface::StopTracking()
{
if (isTracking)
{
//free up the resources
Collection_Free(IdentifiedMarkers);
Xform3D_Free(PoseXf);
//stop the camera
Cameras_Detach();
//now tracking is stopped
isTracking = false;
return true;
}
else
{
return false;
}
}
std::vector<mitk::claronToolHandle> mitk::ClaronInterface::GetAllActiveTools()
{
//Set returnvalue
std::vector<claronToolHandle> returnValue;
//Here, MTC internally maintains the measurement results.
//Those results can be accessed until the next call to Markers_ProcessFrame, when they
//are updated to reflect the next frame's content.
//First, we will obtain the collection of the markers that were identified.
MTC( Markers_IdentifiedMarkersGet(NULL, IdentifiedMarkers) );
//Now we iterate on the identified markers and add them to the returnvalue
for (int j=1; j<=Collection_Count(IdentifiedMarkers); j++)
{
// Obtain the marker's handle, and use it to obtain the pose in the current camera's space
// using our Xform3D object, PoseXf.
mtHandle Marker = Collection_Int(IdentifiedMarkers, j);
returnValue.push_back(Marker);
}
return returnValue;
}
void mitk::ClaronInterface::GrabFrame()
{
MTC( Cameras_GrabFrame(NULL) ); //Grab a frame
MTC( Markers_ProcessFrame(NULL) ); //Process the frame(s)
}
std::vector<double> mitk::ClaronInterface::GetTipPosition(mitk::claronToolHandle c)
{
std::vector<double> returnValue;
double Position[3];
mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle
mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle
mtHandle m2c = Xform3D_New(); // marker to camera xform handle
//Get m2c
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) );
//Get t2m
MTC( Marker_Tooltip2MarkerXfGet (c, t2m ));
//Transform both to t2c
MTC(Xform3D_Concatenate(t2m,m2c,t2c));
//Get position
MTC( Xform3D_ShiftGet(t2c, Position) );
// Here we have to negate the X- and Y-coordinates because of a bug of the
// MTC-library.
returnValue.push_back(-Position[0]);
returnValue.push_back(-Position[1]);
returnValue.push_back(Position[2]);
return returnValue;
}
std::vector<double> mitk::ClaronInterface::GetPosition(claronToolHandle c)
{
std::vector<double> returnValue;
double Position[3];
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) );
MTC( Xform3D_ShiftGet(PoseXf, Position) );
// Here we have to negate the X- and Y-coordinates because of a bug of the
// MTC-library.
returnValue.push_back(-Position[0]);
returnValue.push_back(-Position[1]);
returnValue.push_back(Position[2]);
return returnValue;
}
std::vector<double> mitk::ClaronInterface::GetTipQuaternions(claronToolHandle c)
{
std::vector<double> returnValue;
mtHandle t2m = Xform3D_New(); // tooltip to marker xform handle
mtHandle t2c = Xform3D_New(); // tooltip to camera xform handle
mtHandle m2c = Xform3D_New(); // marker to camera xform handle
//Get m2c
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, m2c, &IdentifyingCamera) );
//Get t2m
MTC( Marker_Tooltip2MarkerXfGet (c, t2m ));
//Transform both to t2c
MTC(Xform3D_Concatenate(t2m,m2c,t2c));
//get the Claron-Quaternion
double Quarternions[4];
MTC( Xform3D_RotQuaternionsGet(t2c, Quarternions) );
mitk::Quaternion claronQuaternion;
//note: claron quarternion has different order than the mitk quarternion
claronQuaternion[3] = Quarternions[0];
claronQuaternion[0] = Quarternions[1];
claronQuaternion[1] = Quarternions[2];
claronQuaternion[2] = Quarternions[3];
// Here we have to make a -90-turn around the Y-axis because of a bug of the
// MTC-library.
mitk::Quaternion minusNinetyDegreeY;
minusNinetyDegreeY[3] = sqrt(2.0)/2.0;
minusNinetyDegreeY[0] = 0;
minusNinetyDegreeY[1] = -1.0/(sqrt(2.0));
minusNinetyDegreeY[2] = 0;
//calculate the result...
mitk::Quaternion erg = (minusNinetyDegreeY*claronQuaternion);
returnValue.push_back(erg[3]);
returnValue.push_back(erg[0]);
returnValue.push_back(erg[1]);
returnValue.push_back(erg[2]);
return returnValue;
}
std::vector<double> mitk::ClaronInterface::GetQuaternions(claronToolHandle c)
{
std::vector<double> returnValue;
//TODO by Alfred 3.3.2009: I'm afraid we have a bug here. Look at the method
// GetTipQuaternions... the same has to be done here
// to compensate the bug in the MTC-lib.
double Quarternions[4];
MTC( Marker_Marker2CameraXfGet (c, CurrCamera, PoseXf, &IdentifyingCamera) );
MTC( Xform3D_RotQuaternionsGet(PoseXf, Quarternions) );
for (int i = 0; i<4; i++) returnValue.push_back(Quarternions[i]);
return returnValue;
}
const char* mitk::ClaronInterface::GetName(claronToolHandle c)
{
char MarkerName[MT_MAX_STRING_LENGTH];
MTC( Marker_NameGet(c, MarkerName, MT_MAX_STRING_LENGTH, 0) );
std::string* returnValue = new std::string(MarkerName);
return returnValue->c_str();
}
bool mitk::ClaronInterface::IsTracking()
{
return this->isTracking;
}
bool mitk::ClaronInterface::IsMicronTrackerInstalled()
{
return true;
}
<|endoftext|> |
<commit_before>//
// This file is part of khmer, http://github.com/ged-lab/khmer/, and is
// Copyright (C) Michigan State University, 2009-2013. It is licensed under
// the three-clause BSD license; see doc/LICENSE.txt. Contact: [email protected]
//
#include "hllcounter.hh"
#include <math.h>
#include <algorithm>
#include <numeric>
#include <inttypes.h>
#include "khmer.hh"
#include "kmer_hash.hh"
#include "read_parsers.hh"
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#define omp_get_num_threads() 1
#endif
#define arr_len(a) (a + sizeof a / sizeof a[0])
using namespace std;
using namespace khmer;
std::map<int, std::vector<double> > rawEstimateData;
std::map<int, std::vector<double> > biasData;
double get_alpha(const int p)
{
if ((p < 4) or (p > 16)) {
return 0; // TODO: treat error
}
switch (p) {
case 4:
return 0.673;
case 5:
return 0.697;
case 6:
return 0.709;
default:
return 0.7213 / (1.0 + 1.079 / (1 << p));
}
}
void init_raw_estimate_data() {
if (rawEstimateData.empty()) {
for(int i=4; i <= 18; i++) {
vector<double> v;
switch(i) {
case 4:
v.assign(RAW_ESTIMATE_DATA_4, arr_len(RAW_ESTIMATE_DATA_4));
break;
case 5:
v.assign(RAW_ESTIMATE_DATA_5, arr_len(RAW_ESTIMATE_DATA_5));
break;
case 6:
v.assign(RAW_ESTIMATE_DATA_6, arr_len(RAW_ESTIMATE_DATA_6));
break;
case 7:
v.assign(RAW_ESTIMATE_DATA_7, arr_len(RAW_ESTIMATE_DATA_7));
break;
case 8:
v.assign(RAW_ESTIMATE_DATA_8, arr_len(RAW_ESTIMATE_DATA_8));
break;
case 9:
v.assign(RAW_ESTIMATE_DATA_9, arr_len(RAW_ESTIMATE_DATA_9));
break;
case 10:
v.assign(RAW_ESTIMATE_DATA_10, arr_len(RAW_ESTIMATE_DATA_10));
break;
case 11:
v.assign(RAW_ESTIMATE_DATA_11, arr_len(RAW_ESTIMATE_DATA_11));
break;
case 12:
v.assign(RAW_ESTIMATE_DATA_12, arr_len(RAW_ESTIMATE_DATA_12));
break;
case 13:
v.assign(RAW_ESTIMATE_DATA_13, arr_len(RAW_ESTIMATE_DATA_13));
break;
case 14:
v.assign(RAW_ESTIMATE_DATA_14, arr_len(RAW_ESTIMATE_DATA_14));
break;
case 15:
v.assign(RAW_ESTIMATE_DATA_15, arr_len(RAW_ESTIMATE_DATA_15));
break;
case 16:
v.assign(RAW_ESTIMATE_DATA_16, arr_len(RAW_ESTIMATE_DATA_16));
break;
case 17:
v.assign(RAW_ESTIMATE_DATA_17, arr_len(RAW_ESTIMATE_DATA_17));
break;
case 18:
v.assign(RAW_ESTIMATE_DATA_18, arr_len(RAW_ESTIMATE_DATA_18));
break;
}
rawEstimateData[i] = v;
}
}
}
void init_bias_data() {
if (biasData.empty()) {
for(int i=4; i <= 18; i++) {
vector<double> v;
switch(i) {
case 4:
v.assign(RAW_BIAS_DATA_4, arr_len(RAW_BIAS_DATA_4));
break;
case 5:
v.assign(RAW_BIAS_DATA_5, arr_len(RAW_BIAS_DATA_5));
break;
case 6:
v.assign(RAW_BIAS_DATA_6, arr_len(RAW_BIAS_DATA_6));
break;
case 7:
v.assign(RAW_BIAS_DATA_7, arr_len(RAW_BIAS_DATA_7));
break;
case 8:
v.assign(RAW_BIAS_DATA_8, arr_len(RAW_BIAS_DATA_8));
break;
case 9:
v.assign(RAW_BIAS_DATA_9, arr_len(RAW_BIAS_DATA_9));
break;
case 10:
v.assign(RAW_BIAS_DATA_10, arr_len(RAW_BIAS_DATA_10));
break;
case 11:
v.assign(RAW_BIAS_DATA_11, arr_len(RAW_BIAS_DATA_11));
break;
case 12:
v.assign(RAW_BIAS_DATA_12, arr_len(RAW_BIAS_DATA_12));
break;
case 13:
v.assign(RAW_BIAS_DATA_13, arr_len(RAW_BIAS_DATA_13));
break;
case 14:
v.assign(RAW_BIAS_DATA_14, arr_len(RAW_BIAS_DATA_14));
break;
case 15:
v.assign(RAW_BIAS_DATA_15, arr_len(RAW_BIAS_DATA_15));
break;
case 16:
v.assign(RAW_BIAS_DATA_16, arr_len(RAW_BIAS_DATA_16));
break;
case 17:
v.assign(RAW_BIAS_DATA_17, arr_len(RAW_BIAS_DATA_17));
break;
case 18:
v.assign(RAW_BIAS_DATA_18, arr_len(RAW_BIAS_DATA_18));
break;
}
biasData[i] = v;
}
}
}
double get_threshold(int p)
{
return THRESHOLD_DATA[p - 4];
}
vector<int> get_nearest_neighbors(double E, vector<double> estimate)
{
vector< pair<double,int> > distance_map;
vector<int> nearest;
int i = 0;
for (vector<double>::iterator it = estimate.begin();
it != estimate.end();
++it) {
std::pair<double, int> p(pow(E - *it, 2.0), i);
distance_map.push_back(p);
i++;
}
sort(distance_map.begin(), distance_map.end());
for(int k=0; k < 6; k++) {
nearest.push_back(distance_map[k].second);
}
return nearest;
}
double estimate_bias(double E, int p)
{
vector<double> bias = biasData[p];
vector<double> raw_estimate = rawEstimateData[p];
vector<int> nearest = get_nearest_neighbors(E, raw_estimate);
double estimate = 0.0;
for (vector<int>::iterator it = nearest.begin();
it != nearest.end();
++it) {
estimate += bias[*it];
}
return estimate / nearest.size();
}
double ep_sum(double acc, int b)
{
return acc += pow(2.0, float(-b));
}
int get_rho(HashIntoType w, int max_width)
{
int rho = max_width - floor(log2(w)); /* TODO find last bit set */
if (rho <= 0) {
return -1; // TODO: treat error, w overflow
}
return rho;
}
HLLCounter::HLLCounter(double error_rate, WordLength ksize)
{
// TODO: check if 0 < error_rate < 1
int p = ceil(log2(pow(1.04 / error_rate, 2)));
this->init(p, ksize);
}
HLLCounter::HLLCounter(int p, WordLength ksize) {
this->init(p, ksize);
}
void HLLCounter::init(int p, WordLength ksize) {
int m = 1 << p;
vector<int> M(m, 0.0);
this->alpha = get_alpha(p);
this->p = p;
this->m = 1 << p;
this->M = M;
this->_ksize = ksize;
init_raw_estimate_data();
init_bias_data();
}
double HLLCounter::_Ep()
{
double sum = accumulate(this->M.begin(), this->M.end(), 0.0, ep_sum);
double E = this->alpha * pow(this->m, 2.0) / sum;
if (E <= (5 * (double)this->m))
return E - estimate_bias(E, this->p);
return E;
}
HashIntoType HLLCounter::estimate_cardinality()
{
double H;
int V = count(this->M.begin(), this->M.end(), 0);
if (V > 0) {
H = this->m * log((double)this->m / V);
if (H <= get_threshold(this->p)) {
return H;
}
}
return this->_Ep();
}
void HLLCounter::add(const string &value)
{
//HashIntoType x = khmer::_hash(value.c_str(), value.size());
//HashIntoType x = khmer::_hash_forward(value.c_str(), value.size());
//HashIntoType x = khmer::_hash_murmur_forward(value);
//HashIntoType x = khmer::_hash_sha1(value);
//HashIntoType x = khmer::_hash_sha1_forward(value);
HashIntoType x = khmer::_hash_murmur(value);
HashIntoType j = x & (this->m - 1);
this->M[j] = max(this->M[j], get_rho(x >> this->p, 64 - this->p));
}
unsigned int HLLCounter::consume_string(const std::string &s) {
unsigned int n_consumed = 0;
std::string kmer = "";
for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) {
kmer.push_back(*it);
if (kmer.size() < _ksize) {
continue;
}
this->add(kmer);
kmer.erase(0, 1);
n_consumed++;
}
return n_consumed;
}
void HLLCounter::consume_fasta(
std::string const &filename,
unsigned int &total_reads,
unsigned long long &n_consumed,
CallbackFn callback,
void * callback_data) {
read_parsers::IParser * parser = read_parsers::IParser::get_parser(filename);
consume_fasta(
parser,
total_reads, n_consumed,
callback, callback_data);
delete parser;
}
void HLLCounter::consume_fasta(
read_parsers::IParser *parser,
unsigned int & total_reads,
unsigned long long & n_consumed,
CallbackFn callback,
void * callback_data) {
read_parsers::Read read;
HLLCounter** counters;
unsigned int *n_consumed_partial;
unsigned int *total_reads_partial;
n_consumed = 0;
#pragma omp parallel
{
#pragma omp single
{
counters = (HLLCounter**)calloc(omp_get_num_threads(),
sizeof(HLLCounter*));
n_consumed_partial = (unsigned int*)calloc(omp_get_num_threads(),
sizeof(unsigned int));
total_reads_partial = (unsigned int*)calloc(omp_get_num_threads(),
sizeof(unsigned int));
for (int i=0; i < omp_get_num_threads(); i++) {
HLLCounter *newc = new HLLCounter(this->p, this->_ksize);
counters[i] = newc;
}
}
#pragma omp single
{
while (!parser->is_complete()) {
// Iterate through the reads and consume their k-mers.
try {
read = parser->get_next_read();
#pragma omp task default(none) firstprivate(read) \
shared(counters, n_consumed_partial, total_reads_partial)
{
bool is_valid;
int n, t = omp_get_thread_num();
n = counters[t]->check_and_process_read(read.sequence,
is_valid);
n_consumed_partial[t] += n;
if (is_valid)
total_reads_partial[t] += 1;
}
} catch (read_parsers::NoMoreReadsAvailable) {
}
} // while reads left for parser
}
#pragma omp taskwait
#pragma omp single
{
for (int i=0; i < omp_get_num_threads(); ++i) {
this->merge(*counters[i]);
delete counters[i];
n_consumed += n_consumed_partial[i];
total_reads += total_reads_partial[i];;
}
free(counters);
free(n_consumed_partial);
free(total_reads_partial);
}
}
}
unsigned int HLLCounter::check_and_process_read(std::string &read,
bool &is_valid) {
is_valid = check_and_normalize_read(read);
if (!is_valid) {
return 0;
}
return consume_string(read);
}
bool HLLCounter::check_and_normalize_read(std::string &read) const {
bool is_valid = true;
if (read.length() < this->_ksize) {
return false;
}
for (unsigned int i = 0; i < read.length(); i++) {
read[ i ] &= 0xdf; // toupper - knock out the "lowercase bit"
if (!is_valid_dna( read[ i ] )) {
is_valid = false;
break;
}
}
return is_valid;
}
void HLLCounter::merge(HLLCounter &other) {
std::transform(this->M.begin(), this->M.end(),
other.M.begin(),
this->M.begin(),
std::max<int>);
/*
for(unsigned int i=0; i < this->M.size(); ++i) {
this->M[i] = std::max(other.M[i], this->M[i]);
}
*/
}
<commit_msg>No need for this<commit_after>//
// This file is part of khmer, http://github.com/ged-lab/khmer/, and is
// Copyright (C) Michigan State University, 2009-2013. It is licensed under
// the three-clause BSD license; see doc/LICENSE.txt. Contact: [email protected]
//
#include "hllcounter.hh"
#include <math.h>
#include <algorithm>
#include <numeric>
#include <inttypes.h>
#include "khmer.hh"
#include "kmer_hash.hh"
#include "read_parsers.hh"
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#define omp_get_num_threads() 1
#endif
#define arr_len(a) (a + sizeof a / sizeof a[0])
using namespace std;
using namespace khmer;
std::map<int, std::vector<double> > rawEstimateData;
std::map<int, std::vector<double> > biasData;
double get_alpha(const int p)
{
if ((p < 4) or (p > 16)) {
return 0; // TODO: treat error
}
switch (p) {
case 4:
return 0.673;
case 5:
return 0.697;
case 6:
return 0.709;
default:
return 0.7213 / (1.0 + 1.079 / (1 << p));
}
}
void init_raw_estimate_data() {
if (rawEstimateData.empty()) {
for(int i=4; i <= 18; i++) {
vector<double> v;
switch(i) {
case 4:
v.assign(RAW_ESTIMATE_DATA_4, arr_len(RAW_ESTIMATE_DATA_4));
break;
case 5:
v.assign(RAW_ESTIMATE_DATA_5, arr_len(RAW_ESTIMATE_DATA_5));
break;
case 6:
v.assign(RAW_ESTIMATE_DATA_6, arr_len(RAW_ESTIMATE_DATA_6));
break;
case 7:
v.assign(RAW_ESTIMATE_DATA_7, arr_len(RAW_ESTIMATE_DATA_7));
break;
case 8:
v.assign(RAW_ESTIMATE_DATA_8, arr_len(RAW_ESTIMATE_DATA_8));
break;
case 9:
v.assign(RAW_ESTIMATE_DATA_9, arr_len(RAW_ESTIMATE_DATA_9));
break;
case 10:
v.assign(RAW_ESTIMATE_DATA_10, arr_len(RAW_ESTIMATE_DATA_10));
break;
case 11:
v.assign(RAW_ESTIMATE_DATA_11, arr_len(RAW_ESTIMATE_DATA_11));
break;
case 12:
v.assign(RAW_ESTIMATE_DATA_12, arr_len(RAW_ESTIMATE_DATA_12));
break;
case 13:
v.assign(RAW_ESTIMATE_DATA_13, arr_len(RAW_ESTIMATE_DATA_13));
break;
case 14:
v.assign(RAW_ESTIMATE_DATA_14, arr_len(RAW_ESTIMATE_DATA_14));
break;
case 15:
v.assign(RAW_ESTIMATE_DATA_15, arr_len(RAW_ESTIMATE_DATA_15));
break;
case 16:
v.assign(RAW_ESTIMATE_DATA_16, arr_len(RAW_ESTIMATE_DATA_16));
break;
case 17:
v.assign(RAW_ESTIMATE_DATA_17, arr_len(RAW_ESTIMATE_DATA_17));
break;
case 18:
v.assign(RAW_ESTIMATE_DATA_18, arr_len(RAW_ESTIMATE_DATA_18));
break;
}
rawEstimateData[i] = v;
}
}
}
void init_bias_data() {
if (biasData.empty()) {
for(int i=4; i <= 18; i++) {
vector<double> v;
switch(i) {
case 4:
v.assign(RAW_BIAS_DATA_4, arr_len(RAW_BIAS_DATA_4));
break;
case 5:
v.assign(RAW_BIAS_DATA_5, arr_len(RAW_BIAS_DATA_5));
break;
case 6:
v.assign(RAW_BIAS_DATA_6, arr_len(RAW_BIAS_DATA_6));
break;
case 7:
v.assign(RAW_BIAS_DATA_7, arr_len(RAW_BIAS_DATA_7));
break;
case 8:
v.assign(RAW_BIAS_DATA_8, arr_len(RAW_BIAS_DATA_8));
break;
case 9:
v.assign(RAW_BIAS_DATA_9, arr_len(RAW_BIAS_DATA_9));
break;
case 10:
v.assign(RAW_BIAS_DATA_10, arr_len(RAW_BIAS_DATA_10));
break;
case 11:
v.assign(RAW_BIAS_DATA_11, arr_len(RAW_BIAS_DATA_11));
break;
case 12:
v.assign(RAW_BIAS_DATA_12, arr_len(RAW_BIAS_DATA_12));
break;
case 13:
v.assign(RAW_BIAS_DATA_13, arr_len(RAW_BIAS_DATA_13));
break;
case 14:
v.assign(RAW_BIAS_DATA_14, arr_len(RAW_BIAS_DATA_14));
break;
case 15:
v.assign(RAW_BIAS_DATA_15, arr_len(RAW_BIAS_DATA_15));
break;
case 16:
v.assign(RAW_BIAS_DATA_16, arr_len(RAW_BIAS_DATA_16));
break;
case 17:
v.assign(RAW_BIAS_DATA_17, arr_len(RAW_BIAS_DATA_17));
break;
case 18:
v.assign(RAW_BIAS_DATA_18, arr_len(RAW_BIAS_DATA_18));
break;
}
biasData[i] = v;
}
}
}
double get_threshold(int p)
{
return THRESHOLD_DATA[p - 4];
}
vector<int> get_nearest_neighbors(double E, vector<double> estimate)
{
vector< pair<double,int> > distance_map;
vector<int> nearest;
int i = 0;
for (vector<double>::iterator it = estimate.begin();
it != estimate.end();
++it) {
std::pair<double, int> p(pow(E - *it, 2.0), i);
distance_map.push_back(p);
i++;
}
sort(distance_map.begin(), distance_map.end());
for(int k=0; k < 6; k++) {
nearest.push_back(distance_map[k].second);
}
return nearest;
}
double estimate_bias(double E, int p)
{
vector<double> bias = biasData[p];
vector<double> raw_estimate = rawEstimateData[p];
vector<int> nearest = get_nearest_neighbors(E, raw_estimate);
double estimate = 0.0;
for (vector<int>::iterator it = nearest.begin();
it != nearest.end();
++it) {
estimate += bias[*it];
}
return estimate / nearest.size();
}
double ep_sum(double acc, int b)
{
return acc += pow(2.0, float(-b));
}
int get_rho(HashIntoType w, int max_width)
{
int rho = max_width - floor(log2(w)); /* TODO find last bit set */
if (rho <= 0) {
return -1; // TODO: treat error, w overflow
}
return rho;
}
HLLCounter::HLLCounter(double error_rate, WordLength ksize)
{
// TODO: check if 0 < error_rate < 1
int p = ceil(log2(pow(1.04 / error_rate, 2)));
this->init(p, ksize);
}
HLLCounter::HLLCounter(int p, WordLength ksize) {
this->init(p, ksize);
}
void HLLCounter::init(int p, WordLength ksize) {
int m = 1 << p;
vector<int> M(m, 0.0);
this->alpha = get_alpha(p);
this->p = p;
this->m = 1 << p;
this->M = M;
this->_ksize = ksize;
init_raw_estimate_data();
init_bias_data();
}
double HLLCounter::_Ep()
{
double sum = accumulate(this->M.begin(), this->M.end(), 0.0, ep_sum);
double E = this->alpha * pow(this->m, 2.0) / sum;
if (E <= (5 * (double)this->m))
return E - estimate_bias(E, this->p);
return E;
}
HashIntoType HLLCounter::estimate_cardinality()
{
double H;
int V = count(this->M.begin(), this->M.end(), 0);
if (V > 0) {
H = this->m * log((double)this->m / V);
if (H <= get_threshold(this->p)) {
return H;
}
}
return this->_Ep();
}
void HLLCounter::add(const string &value)
{
//HashIntoType x = khmer::_hash(value.c_str(), value.size());
//HashIntoType x = khmer::_hash_forward(value.c_str(), value.size());
//HashIntoType x = khmer::_hash_murmur_forward(value);
//HashIntoType x = khmer::_hash_sha1(value);
//HashIntoType x = khmer::_hash_sha1_forward(value);
HashIntoType x = khmer::_hash_murmur(value);
HashIntoType j = x & (this->m - 1);
this->M[j] = max(this->M[j], get_rho(x >> this->p, 64 - this->p));
}
unsigned int HLLCounter::consume_string(const std::string &s) {
unsigned int n_consumed = 0;
std::string kmer = "";
for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) {
kmer.push_back(*it);
if (kmer.size() < _ksize) {
continue;
}
this->add(kmer);
kmer.erase(0, 1);
n_consumed++;
}
return n_consumed;
}
void HLLCounter::consume_fasta(
std::string const &filename,
unsigned int &total_reads,
unsigned long long &n_consumed,
CallbackFn callback,
void * callback_data) {
read_parsers::IParser * parser = read_parsers::IParser::get_parser(filename);
consume_fasta(
parser,
total_reads, n_consumed,
callback, callback_data);
delete parser;
}
void HLLCounter::consume_fasta(
read_parsers::IParser *parser,
unsigned int & total_reads,
unsigned long long & n_consumed,
CallbackFn callback,
void * callback_data) {
read_parsers::Read read;
HLLCounter** counters;
unsigned int *n_consumed_partial;
unsigned int *total_reads_partial;
n_consumed = 0;
#pragma omp parallel
{
#pragma omp single
{
counters = (HLLCounter**)calloc(omp_get_num_threads(),
sizeof(HLLCounter*));
n_consumed_partial = (unsigned int*)calloc(omp_get_num_threads(),
sizeof(unsigned int));
total_reads_partial = (unsigned int*)calloc(omp_get_num_threads(),
sizeof(unsigned int));
for (int i=0; i < omp_get_num_threads(); i++) {
HLLCounter *newc = new HLLCounter(this->p, this->_ksize);
counters[i] = newc;
}
while (!parser->is_complete()) {
// Iterate through the reads and consume their k-mers.
try {
read = parser->get_next_read();
#pragma omp task default(none) firstprivate(read) \
shared(counters, n_consumed_partial, total_reads_partial)
{
bool is_valid;
int n, t = omp_get_thread_num();
n = counters[t]->check_and_process_read(read.sequence,
is_valid);
n_consumed_partial[t] += n;
if (is_valid)
total_reads_partial[t] += 1;
}
} catch (read_parsers::NoMoreReadsAvailable) {
}
} // while reads left for parser
}
#pragma omp taskwait
#pragma omp single
{
for (int i=0; i < omp_get_num_threads(); ++i) {
this->merge(*counters[i]);
delete counters[i];
n_consumed += n_consumed_partial[i];
total_reads += total_reads_partial[i];;
}
free(counters);
free(n_consumed_partial);
free(total_reads_partial);
}
}
}
unsigned int HLLCounter::check_and_process_read(std::string &read,
bool &is_valid) {
is_valid = check_and_normalize_read(read);
if (!is_valid) {
return 0;
}
return consume_string(read);
}
bool HLLCounter::check_and_normalize_read(std::string &read) const {
bool is_valid = true;
if (read.length() < this->_ksize) {
return false;
}
for (unsigned int i = 0; i < read.length(); i++) {
read[ i ] &= 0xdf; // toupper - knock out the "lowercase bit"
if (!is_valid_dna( read[ i ] )) {
is_valid = false;
break;
}
}
return is_valid;
}
void HLLCounter::merge(HLLCounter &other) {
std::transform(this->M.begin(), this->M.end(),
other.M.begin(),
this->M.begin(),
std::max<int>);
/*
for(unsigned int i=0; i < this->M.size(); ++i) {
this->M[i] = std::max(other.M[i], this->M[i]);
}
*/
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Radu Serban
// =============================================================================
//
// ChronoParallel test program for settling process of granular material.
//
// The global reference frame has Z up.
// All units SI (CGS, i.e., centimeter - gram - second)
//
// =============================================================================
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <valarray>
#include <vector>
#include "chrono/ChConfig.h"
#include "chrono/core/ChTimer.h"
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/utils/ChUtilsGenerators.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_parallel/physics/ChSystemParallel.h"
#ifdef CHRONO_OPENGL
#include "chrono_opengl/ChOpenGLWindow.h"
#endif
using namespace chrono;
// --------------------------------------------------------------------------
void TimingHeader() {
printf(" TIME |");
printf(" STEP |");
printf(" BROAD |");
printf(" NARROW |");
printf(" SOLVER |");
printf(" UPDATE |");
printf("# BODIES |");
printf("# CONTACT|");
printf(" # ITERS |");
printf(" RESID |");
printf("\n\n");
}
void TimingOutput(chrono::ChSystem* mSys) {
double TIME = mSys->GetChTime();
double STEP = mSys->GetTimerStep();
double BROD = mSys->GetTimerCollisionBroad();
double NARR = mSys->GetTimerCollisionNarrow();
double SOLVER = mSys->GetTimerSolver();
double UPDT = mSys->GetTimerUpdate();
double RESID = 0;
int REQ_ITS = 0;
int BODS = mSys->GetNbodies();
int CNTC = mSys->GetNcontacts();
if (chrono::ChSystemParallel* parallel_sys = dynamic_cast<chrono::ChSystemParallel*>(mSys)) {
RESID = ((chrono::ChIterativeSolverParallel*)(mSys->GetSolverSpeed()))->GetResidual();
REQ_ITS = ((chrono::ChIterativeSolverParallel*)(mSys->GetSolverSpeed()))->GetTotalIterations();
BODS = parallel_sys->GetNbodies();
CNTC = parallel_sys->GetNcontacts();
}
printf(" %8.5f | %7.4f | %7.4f | %7.4f | %7.4f | %7.4f | %7d | %7d | %7d | %7.4f |\n", TIME, STEP, BROD, NARR, SOLVER,
UPDT, BODS, CNTC, REQ_ITS, RESID);
}
// --------------------------------------------------------------------------
int main(int argc, char** argv) {
int num_threads = 4;
ChMaterialSurfaceBase::ContactMethod method = ChMaterialSurfaceBase::DEM;
bool use_mat_properties = true;
bool render = false;
// Get number of threads from arguments (if specified)
if (argc > 1) {
num_threads = std::stoi(argv[1]);
}
std::cout << "Requested number of threads: " << num_threads << std::endl;
// ----------------
// Model parameters
// ----------------
// Container dimensions
double hdimX = 5.0;
double hdimY = 0.25;
double hdimZ = 0.5;
double hthick = 0.25;
// Granular material properties
double radius_g = 0.006;
int Id_g = 10000;
double rho_g = 2500;
double vol_g = (4.0 / 3) * CH_C_PI * radius_g * radius_g * radius_g;
double mass_g = rho_g * vol_g;
ChVector<> inertia_g = 0.4 * mass_g * radius_g * radius_g * ChVector<>(1, 1, 1);
int num_layers = 10;
// Terrain contact properties
float friction_terrain = 0.9f;
float restitution_terrain = 0.0f;
float Y_terrain = 8e5f;
float nu_terrain = 0.3f;
float kn_terrain = 1.0e7f;
float gn_terrain = 1.0e3f;
float kt_terrain = 2.86e6f;
float gt_terrain = 1.0e3f;
// Estimates for number of bins for broad-phase
int factor = 2;
int binsX = (int)std::ceil(hdimX / radius_g) / factor;
int binsY = (int)std::ceil(hdimY / radius_g) / factor;
int binsZ = 1;
std::cout << "Broad-phase bins: " << binsX << " x " << binsY << " x " << binsZ << std::endl;
// --------------------------
// Create the parallel system
// --------------------------
// Create system and set method-specific solver settings
chrono::ChSystemParallel* system;
switch (method) {
case ChMaterialSurfaceBase::DEM: {
ChSystemParallelDEM* sys = new ChSystemParallelDEM;
sys->GetSettings()->solver.contact_force_model = ChSystemDEM::Hooke;
sys->GetSettings()->solver.tangential_displ_mode = ChSystemDEM::TangentialDisplacementModel::OneStep;
sys->GetSettings()->solver.use_material_properties = use_mat_properties;
system = sys;
break;
}
case ChMaterialSurfaceBase::DVI: {
ChSystemParallelDVI* sys = new ChSystemParallelDVI;
sys->GetSettings()->solver.solver_mode = SLIDING;
sys->GetSettings()->solver.max_iteration_normal = 0;
sys->GetSettings()->solver.max_iteration_sliding = 200;
sys->GetSettings()->solver.max_iteration_spinning = 0;
sys->GetSettings()->solver.alpha = 0;
sys->GetSettings()->solver.contact_recovery_speed = -1;
sys->GetSettings()->collision.collision_envelope = 0.1 * radius_g;
sys->ChangeSolverType(APGD);
system = sys;
break;
}
}
system->Set_G_acc(ChVector<>(0, 0, -9.81));
system->GetSettings()->perform_thread_tuning = false;
system->GetSettings()->solver.use_full_inertia_tensor = false;
system->GetSettings()->solver.tolerance = 0.1;
system->GetSettings()->solver.max_iteration_bilateral = 100;
system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;
system->GetSettings()->collision.bins_per_axis = I3(binsX, binsY, binsZ);
// Set number of threads
system->SetParallelThreadNumber(num_threads);
CHOMPfunctions::SetNumThreads(num_threads);
// Sanity check: print number of threads in a parallel region
#pragma omp parallel
#pragma omp master
{ std::cout << "Actual number of OpenMP threads: " << omp_get_num_threads() << std::endl; }
// ---------------------
// Create terrain bodies
// ---------------------
// Create contact material for terrain
std::shared_ptr<ChMaterialSurfaceBase> material_terrain;
switch (method) {
case ChMaterialSurfaceBase::DEM: {
auto mat_ter = std::make_shared<ChMaterialSurfaceDEM>();
mat_ter->SetFriction(friction_terrain);
mat_ter->SetRestitution(restitution_terrain);
mat_ter->SetYoungModulus(Y_terrain);
mat_ter->SetPoissonRatio(nu_terrain);
mat_ter->SetAdhesion(100.0f); // TODO
mat_ter->SetKn(kn_terrain);
mat_ter->SetGn(gn_terrain);
mat_ter->SetKt(kt_terrain);
mat_ter->SetGt(gt_terrain);
material_terrain = mat_ter;
break;
}
case ChMaterialSurfaceBase::DVI: {
auto mat_ter = std::make_shared<ChMaterialSurface>();
mat_ter->SetFriction(friction_terrain);
mat_ter->SetRestitution(restitution_terrain);
material_terrain = mat_ter;
break;
}
}
// Create container body
auto container = std::shared_ptr<ChBody>(system->NewBody());
system->AddBody(container);
container->SetIdentifier(-1);
container->SetMass(1);
container->SetBodyFixed(true);
container->SetCollide(true);
container->SetMaterialSurface(material_terrain);
container->GetCollisionModel()->ClearModel();
// Bottom box
utils::AddBoxGeometry(container.get(), ChVector<>(hdimX, hdimY, hthick), ChVector<>(0, 0, -hthick),
ChQuaternion<>(1, 0, 0, 0), true);
// Front box
utils::AddBoxGeometry(container.get(), ChVector<>(hthick, hdimY, hdimZ + hthick),
ChVector<>(hdimX + hthick, 0, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
// Rear box
utils::AddBoxGeometry(container.get(), ChVector<>(hthick, hdimY, hdimZ + hthick),
ChVector<>(-hdimX - hthick, 0, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
// Left box
utils::AddBoxGeometry(container.get(), ChVector<>(hdimX, hthick, hdimZ + hthick),
ChVector<>(0, hdimY + hthick, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
// Right box
utils::AddBoxGeometry(container.get(), ChVector<>(hdimX, hthick, hdimZ + hthick),
ChVector<>(0, -hdimY - hthick, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
container->GetCollisionModel()->BuildModel();
// ----------------
// Create particles
// ----------------
// Create a particle generator and a mixture entirely made out of spheres
utils::Generator gen(system);
std::shared_ptr<utils::MixtureIngredient> m1 = gen.AddMixtureIngredient(utils::SPHERE, 1.0);
m1->setDefaultMaterial(material_terrain);
m1->setDefaultDensity(rho_g);
m1->setDefaultSize(radius_g);
// Set starting value for body identifiers
gen.setBodyIdentifier(Id_g);
// Create particles in layers until reaching the desired number of particles
double r = 1.01 * radius_g;
ChVector<> hdims(hdimX - r, hdimY - r, 0);
ChVector<> center(0, 0, 2 * r);
for (int il = 0; il < num_layers; il++) {
gen.createObjectsBox(utils::POISSON_DISK, 2 * r, center, hdims);
center.z += 2 * r;
}
unsigned int num_particles = gen.getTotalNumBodies();
std::cout << "Generated particles: " << num_particles << std::endl;
// -------------------------------
// Create the visualization window
// -------------------------------
#ifdef CHRONO_OPENGL
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "Settling test", system);
gl_window.SetCamera(ChVector<>(0, -1, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 0.05f);
gl_window.SetRenderMode(opengl::WIREFRAME);
}
#endif
// ---------------
// Simulate system
// ---------------
ChTimer<double> timer;
double cumm_sim_time = 0;
double time_end = 0.4;
double time_step = 1e-4;
TimingHeader();
while (system->GetChTime() < time_end) {
////timer.reset();
////timer.start();
system->DoStepDynamics(time_step);
TimingOutput(system);
////timer.stop();
////cumm_sim_time += timer();
////std::cout << std::fixed << std::setprecision(6) << system->GetChTime() << " [" << timer.GetTimeSeconds() << "]"
//// << std::endl;
#ifdef CHRONO_OPENGL
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
if (gl_window.Active()) {
gl_window.Render();
} else {
return 1;
}
}
#endif
}
return 0;
}<commit_msg>Add tracking of a single granule in the parallel settling test<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Radu Serban
// =============================================================================
//
// ChronoParallel test program for settling process of granular material.
//
// The global reference frame has Z up.
// All units SI (CGS, i.e., centimeter - gram - second)
//
// =============================================================================
#include <cmath>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <valarray>
#include <vector>
#include "chrono/ChConfig.h"
#include "chrono/core/ChTimer.h"
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/utils/ChUtilsGenerators.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_parallel/physics/ChSystemParallel.h"
#ifdef CHRONO_OPENGL
#include "chrono_opengl/ChOpenGLWindow.h"
#endif
using namespace chrono;
// --------------------------------------------------------------------------
void TimingHeader() {
printf(" TIME |");
printf(" STEP |");
printf(" BROAD |");
printf(" NARROW |");
printf(" SOLVER |");
printf(" UPDATE |");
printf("# BODIES |");
printf("# CONTACT|");
printf(" # ITERS |");
printf(" RESID |");
printf("\n\n");
}
void TimingOutput(chrono::ChSystem* mSys) {
double TIME = mSys->GetChTime();
double STEP = mSys->GetTimerStep();
double BROD = mSys->GetTimerCollisionBroad();
double NARR = mSys->GetTimerCollisionNarrow();
double SOLVER = mSys->GetTimerSolver();
double UPDT = mSys->GetTimerUpdate();
double RESID = 0;
int REQ_ITS = 0;
int BODS = mSys->GetNbodies();
int CNTC = mSys->GetNcontacts();
if (chrono::ChSystemParallel* parallel_sys = dynamic_cast<chrono::ChSystemParallel*>(mSys)) {
RESID = ((chrono::ChIterativeSolverParallel*)(mSys->GetSolverSpeed()))->GetResidual();
REQ_ITS = ((chrono::ChIterativeSolverParallel*)(mSys->GetSolverSpeed()))->GetTotalIterations();
}
printf(" %8.5f | %7.4f | %7.4f | %7.4f | %7.4f | %7.4f | %7d | %7d | %7d | %7.4f |\n", TIME, STEP, BROD, NARR, SOLVER,
UPDT, BODS, CNTC, REQ_ITS, RESID);
}
// --------------------------------------------------------------------------
int main(int argc, char** argv) {
int num_threads = 4;
ChMaterialSurfaceBase::ContactMethod method = ChMaterialSurfaceBase::DEM;
bool use_mat_properties = true;
bool render = false;
bool track_granule = false;
// Get number of threads from arguments (if specified)
if (argc > 1) {
num_threads = std::stoi(argv[1]);
}
std::cout << "Requested number of threads: " << num_threads << std::endl;
// ----------------
// Model parameters
// ----------------
// Container dimensions
double hdimX = 5.0;
double hdimY = 0.25;
double hdimZ = 0.5;
double hthick = 0.25;
// Granular material properties
double radius_g = 0.006;
int Id_g = 10000;
double rho_g = 2500;
double vol_g = (4.0 / 3) * CH_C_PI * radius_g * radius_g * radius_g;
double mass_g = rho_g * vol_g;
ChVector<> inertia_g = 0.4 * mass_g * radius_g * radius_g * ChVector<>(1, 1, 1);
int num_layers = 10;
// Terrain contact properties
float friction_terrain = 0.9f;
float restitution_terrain = 0.0f;
float Y_terrain = 8e5f;
float nu_terrain = 0.3f;
float kn_terrain = 1.0e7f;
float gn_terrain = 1.0e3f;
float kt_terrain = 2.86e6f;
float gt_terrain = 1.0e3f;
float coh_pressure_terrain = 0e3f;
float coh_force_terrain = (float)(CH_C_PI * radius_g * radius_g) * coh_pressure_terrain;
// Estimates for number of bins for broad-phase
int factor = 2;
int binsX = (int)std::ceil(hdimX / radius_g) / factor;
int binsY = (int)std::ceil(hdimY / radius_g) / factor;
int binsZ = 1;
std::cout << "Broad-phase bins: " << binsX << " x " << binsY << " x " << binsZ << std::endl;
// --------------------------
// Create the parallel system
// --------------------------
// Create system and set method-specific solver settings
chrono::ChSystemParallel* system;
switch (method) {
case ChMaterialSurfaceBase::DEM: {
ChSystemParallelDEM* sys = new ChSystemParallelDEM;
sys->GetSettings()->solver.contact_force_model = ChSystemDEM::Hertz;
sys->GetSettings()->solver.tangential_displ_mode = ChSystemDEM::TangentialDisplacementModel::OneStep;
sys->GetSettings()->solver.use_material_properties = use_mat_properties;
system = sys;
break;
}
case ChMaterialSurfaceBase::DVI: {
ChSystemParallelDVI* sys = new ChSystemParallelDVI;
sys->GetSettings()->solver.solver_mode = SLIDING;
sys->GetSettings()->solver.max_iteration_normal = 0;
sys->GetSettings()->solver.max_iteration_sliding = 200;
sys->GetSettings()->solver.max_iteration_spinning = 0;
sys->GetSettings()->solver.alpha = 0;
sys->GetSettings()->solver.contact_recovery_speed = -1;
sys->GetSettings()->collision.collision_envelope = 0.1 * radius_g;
sys->ChangeSolverType(APGD);
system = sys;
break;
}
}
system->Set_G_acc(ChVector<>(0, 0, -9.81));
system->GetSettings()->perform_thread_tuning = false;
system->GetSettings()->solver.use_full_inertia_tensor = false;
system->GetSettings()->solver.tolerance = 0.1;
system->GetSettings()->solver.max_iteration_bilateral = 100;
system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;
system->GetSettings()->collision.bins_per_axis = I3(binsX, binsY, binsZ);
// Set number of threads
system->SetParallelThreadNumber(num_threads);
CHOMPfunctions::SetNumThreads(num_threads);
// Sanity check: print number of threads in a parallel region
#pragma omp parallel
#pragma omp master
{ std::cout << "Actual number of OpenMP threads: " << omp_get_num_threads() << std::endl; }
// ---------------------
// Create terrain bodies
// ---------------------
// Create contact material for terrain
std::shared_ptr<ChMaterialSurfaceBase> material_terrain;
switch (method) {
case ChMaterialSurfaceBase::DEM: {
auto mat_ter = std::make_shared<ChMaterialSurfaceDEM>();
mat_ter->SetFriction(friction_terrain);
mat_ter->SetRestitution(restitution_terrain);
mat_ter->SetYoungModulus(Y_terrain);
mat_ter->SetPoissonRatio(nu_terrain);
mat_ter->SetAdhesion(coh_force_terrain);
mat_ter->SetKn(kn_terrain);
mat_ter->SetGn(gn_terrain);
mat_ter->SetKt(kt_terrain);
mat_ter->SetGt(gt_terrain);
material_terrain = mat_ter;
break;
}
case ChMaterialSurfaceBase::DVI: {
auto mat_ter = std::make_shared<ChMaterialSurface>();
mat_ter->SetFriction(friction_terrain);
mat_ter->SetRestitution(restitution_terrain);
mat_ter->SetCohesion(coh_force_terrain);
material_terrain = mat_ter;
break;
}
}
// Create container body
auto container = std::shared_ptr<ChBody>(system->NewBody());
system->AddBody(container);
container->SetIdentifier(-1);
container->SetMass(1);
container->SetBodyFixed(true);
container->SetCollide(true);
container->SetMaterialSurface(material_terrain);
container->GetCollisionModel()->ClearModel();
// Bottom box
utils::AddBoxGeometry(container.get(), ChVector<>(hdimX, hdimY, hthick), ChVector<>(0, 0, -hthick),
ChQuaternion<>(1, 0, 0, 0), true);
// Front box
utils::AddBoxGeometry(container.get(), ChVector<>(hthick, hdimY, hdimZ + hthick),
ChVector<>(hdimX + hthick, 0, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
// Rear box
utils::AddBoxGeometry(container.get(), ChVector<>(hthick, hdimY, hdimZ + hthick),
ChVector<>(-hdimX - hthick, 0, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
// Left box
utils::AddBoxGeometry(container.get(), ChVector<>(hdimX, hthick, hdimZ + hthick),
ChVector<>(0, hdimY + hthick, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
// Right box
utils::AddBoxGeometry(container.get(), ChVector<>(hdimX, hthick, hdimZ + hthick),
ChVector<>(0, -hdimY - hthick, hdimZ - hthick), ChQuaternion<>(1, 0, 0, 0), false);
container->GetCollisionModel()->BuildModel();
// ----------------
// Create particles
// ----------------
// Create a particle generator and a mixture entirely made out of spheres
utils::Generator gen(system);
std::shared_ptr<utils::MixtureIngredient> m1 = gen.AddMixtureIngredient(utils::SPHERE, 1.0);
m1->setDefaultMaterial(material_terrain);
m1->setDefaultDensity(rho_g);
m1->setDefaultSize(radius_g);
// Set starting value for body identifiers
gen.setBodyIdentifier(Id_g);
// Create particles in layers until reaching the desired number of particles
double r = 1.01 * radius_g;
ChVector<> hdims(hdimX - r, hdimY - r, 0);
ChVector<> center(0, 0, 2 * r);
for (int il = 0; il < num_layers; il++) {
gen.createObjectsBox(utils::POISSON_DISK, 2 * r, center, hdims);
center.z += 2 * r;
}
unsigned int num_particles = gen.getTotalNumBodies();
std::cout << "Generated particles: " << num_particles << std::endl;
// If tracking a granule (roughly in the "middle of the pack"),
// grab a pointer to the tracked body and open an output file.
std::shared_ptr<ChBody> granule; // tracked granule
std::ofstream outf; // output file stream
if (track_granule) {
int id = Id_g + num_particles / 2;
auto bodies = system->Get_bodylist();
for (auto body = bodies->begin(); body != bodies->end(); ++body) {
if ((*body)->GetIdentifier() == id) {
granule = *body;
break;
}
}
outf.open("../settling_granule.dat", std::ios::out);
outf.precision(7);
outf << std::scientific;
}
#ifdef CHRONO_OPENGL
// -------------------------------
// Create the visualization window
// -------------------------------
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "Settling test", system);
gl_window.SetCamera(ChVector<>(0, -1, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 0.05f);
gl_window.SetRenderMode(opengl::WIREFRAME);
}
#endif
// ---------------
// Simulate system
// ---------------
ChTimer<double> timer;
double cumm_sim_time = 0;
double time_end = 0.4;
double time_step = 1e-4;
TimingHeader();
while (system->GetChTime() < time_end) {
////timer.reset();
////timer.start();
system->DoStepDynamics(time_step);
TimingOutput(system);
////timer.stop();
////cumm_sim_time += timer();
////std::cout << std::fixed << std::setprecision(6) << system->GetChTime() << " [" << timer.GetTimeSeconds() << "]"
//// << std::endl;
if (track_granule) {
assert(outf.is_open());
assert(granule);
const ChVector<>& pos = granule->GetPos();
const ChVector<>& vel = granule->GetPos_dt();
outf << system->GetChTime() << " ";
outf << system->GetNbodies() << " " << system->GetNcontacts() << " ";
outf << pos.x << " " << pos.y << " " << pos.z << " ";
outf << vel.x << " " << vel.y << " " << vel.z;
outf << std::endl << std::flush;
}
#ifdef CHRONO_OPENGL
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
if (gl_window.Active()) {
gl_window.Render();
} else {
return 1;
}
}
#endif
}
return 0;
}<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.