text stringlengths 54 60.6k |
|---|
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _SRC_BOUNDOBJECT_HPP_
#define _SRC_BOUNDOBJECT_HPP_
#include <string>
#include <set>
#include <boost/thread/mutex.hpp>
#include <qimessaging/api.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/transportserver.hpp>
#include <qi/atomic.hpp>
namespace qi {
class GenericObject;
class ServiceDirectoryClient;
// (service, linkId)
struct RemoteLink
{
RemoteLink()
: localLinkId(0)
, event(0)
{}
RemoteLink(unsigned int localLinkId, unsigned int event)
: localLinkId(localLinkId)
, event(event) {}
unsigned int localLinkId;
unsigned int event;
};
class BoundObject {
public:
//Server Interface
virtual void onMessage(const qi::Message &msg, TransportSocketPtr socket) = 0;
virtual void onSocketDisconnected(qi::TransportSocketPtr socket, int error) = 0;
};
//Bound Object, represent an object bound on a server
// this is not an object..
class ServiceBoundObject : public BoundObject {
public:
ServiceBoundObject(unsigned int serviceId, qi::ObjectPtr obj, qi::MetaCallType mct = qi::MetaCallType_Queued);
virtual ~ServiceBoundObject();
public:
//PUBLIC BOUND METHODS
unsigned int registerEvent(unsigned int serviceId, unsigned int eventId, unsigned int linkId);
void unregisterEvent(unsigned int serviceId, unsigned int eventId, unsigned int linkId);
qi::MetaObject metaObject(unsigned int serviceId);
public:
inline qi::TransportSocketPtr currentSocket() const {
#ifndef NDEBUG
if (_callType != MetaCallType_Direct)
qiLogWarning("qi.boundobject") << " currentSocket() used but callType is not direct";
#endif
return _currentSocket;
}
public:
//BoundObject Interface
virtual void onMessage(const qi::Message &msg, TransportSocketPtr socket);
virtual void onSocketDisconnected(qi::TransportSocketPtr socket, int error);
private:
qi::ObjectPtr createServiceBoundObjectType(ServiceBoundObject *self);
private:
// remote link id -> local link id
typedef std::map<unsigned int, RemoteLink> ServiceLinks;
typedef std::map<qi::TransportSocketPtr, ServiceLinks> BySocketServiceLinks;
//Event handling (no lock needed)
BySocketServiceLinks _links;
private:
qi::TransportSocketPtr _currentSocket;
unsigned int _serviceId;
qi::ObjectPtr _object;
qi::ObjectPtr _self;
qi::MetaCallType _callType;
boost::mutex _mutex; // prevent parallel onMessage on self execution
};
typedef boost::shared_ptr<BoundObject> BoundObjectPtr;
qi::BoundObjectPtr makeServiceBoundObjectPtr(unsigned int serviceId, qi::ObjectPtr object, qi::MetaCallType mct = qi::MetaCallType_Auto);
}
QI_TYPE_NOT_CONSTRUCTIBLE(qi::ServiceBoundObject);
#endif // _SRC_SESSIONSERVER_HPP_
<commit_msg>BoundObject: mark as not clonable.<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _SRC_BOUNDOBJECT_HPP_
#define _SRC_BOUNDOBJECT_HPP_
#include <string>
#include <set>
#include <boost/thread/mutex.hpp>
#include <qimessaging/api.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/transportserver.hpp>
#include <qi/atomic.hpp>
namespace qi {
class GenericObject;
class ServiceDirectoryClient;
// (service, linkId)
struct RemoteLink
{
RemoteLink()
: localLinkId(0)
, event(0)
{}
RemoteLink(unsigned int localLinkId, unsigned int event)
: localLinkId(localLinkId)
, event(event) {}
unsigned int localLinkId;
unsigned int event;
};
class BoundObject {
public:
//Server Interface
virtual void onMessage(const qi::Message &msg, TransportSocketPtr socket) = 0;
virtual void onSocketDisconnected(qi::TransportSocketPtr socket, int error) = 0;
};
//Bound Object, represent an object bound on a server
// this is not an object..
class ServiceBoundObject : public BoundObject {
public:
ServiceBoundObject(unsigned int serviceId, qi::ObjectPtr obj, qi::MetaCallType mct = qi::MetaCallType_Queued);
virtual ~ServiceBoundObject();
public:
//PUBLIC BOUND METHODS
unsigned int registerEvent(unsigned int serviceId, unsigned int eventId, unsigned int linkId);
void unregisterEvent(unsigned int serviceId, unsigned int eventId, unsigned int linkId);
qi::MetaObject metaObject(unsigned int serviceId);
public:
inline qi::TransportSocketPtr currentSocket() const {
#ifndef NDEBUG
if (_callType != MetaCallType_Direct)
qiLogWarning("qi.boundobject") << " currentSocket() used but callType is not direct";
#endif
return _currentSocket;
}
public:
//BoundObject Interface
virtual void onMessage(const qi::Message &msg, TransportSocketPtr socket);
virtual void onSocketDisconnected(qi::TransportSocketPtr socket, int error);
private:
qi::ObjectPtr createServiceBoundObjectType(ServiceBoundObject *self);
private:
// remote link id -> local link id
typedef std::map<unsigned int, RemoteLink> ServiceLinks;
typedef std::map<qi::TransportSocketPtr, ServiceLinks> BySocketServiceLinks;
//Event handling (no lock needed)
BySocketServiceLinks _links;
private:
qi::TransportSocketPtr _currentSocket;
unsigned int _serviceId;
qi::ObjectPtr _object;
qi::ObjectPtr _self;
qi::MetaCallType _callType;
boost::mutex _mutex; // prevent parallel onMessage on self execution
};
typedef boost::shared_ptr<BoundObject> BoundObjectPtr;
qi::BoundObjectPtr makeServiceBoundObjectPtr(unsigned int serviceId, qi::ObjectPtr object, qi::MetaCallType mct = qi::MetaCallType_Auto);
}
QI_TYPE_NOT_CLONABLE(qi::ServiceBoundObject);
#endif // _SRC_SESSIONSERVER_HPP_
<|endoftext|> |
<commit_before>#include "buffer_utils.hh"
#include "buffer_manager.hh"
#include "event_manager.hh"
#include "file.hh"
#include "selection.hh"
#include <unistd.h>
#if defined(__APPLE__)
#define st_mtim st_mtimespec
#endif
namespace Kakoune
{
ColumnCount get_column(const Buffer& buffer,
ColumnCount tabstop, BufferCoord coord)
{
auto line = buffer[coord.line];
auto col = 0_col;
for (auto it = line.begin();
it != line.end() and coord.column > (int)(it - line.begin()); )
{
if (*it == '\t')
{
col = (col / tabstop + 1) * tabstop;
++it;
}
else
col += codepoint_width(utf8::read_codepoint(it, line.end()));
}
return col;
}
ColumnCount column_length(const Buffer& buffer, ColumnCount tabstop, LineCount line)
{
return get_column(buffer, tabstop, BufferCoord{line, ByteCount{INT_MAX}});
}
ByteCount get_byte_to_column(const Buffer& buffer, ColumnCount tabstop, DisplayCoord coord)
{
auto line = buffer[coord.line];
auto col = 0_col;
auto it = line.begin();
while (it != line.end() and coord.column > col)
{
if (*it == '\t')
{
col = (col / tabstop + 1) * tabstop;
if (col > coord.column) // the target column was in the tab
break;
++it;
}
else
{
auto next = it;
col += codepoint_width(utf8::read_codepoint(next, line.end()));
if (col > coord.column) // the target column was in the char
break;
it = next;
}
}
return (int)(it - line.begin());
}
Buffer* open_file_buffer(StringView filename, Buffer::Flags flags)
{
MappedFile file_data{parse_filename(filename)};
return BufferManager::instance().create_buffer(
filename.str(), Buffer::Flags::File | flags, file_data, file_data.st.st_mtim);
}
Buffer* open_or_create_file_buffer(StringView filename, Buffer::Flags flags)
{
auto& buffer_manager = BufferManager::instance();
auto path = parse_filename(filename);
if (file_exists(path))
{
MappedFile file_data{path};
return buffer_manager.create_buffer(filename.str(), Buffer::Flags::File | flags,
file_data, file_data.st.st_mtim);
}
return buffer_manager.create_buffer(
filename.str(), Buffer::Flags::File | Buffer::Flags::New,
{}, InvalidTime);
}
void reload_file_buffer(Buffer& buffer)
{
kak_assert(buffer.flags() & Buffer::Flags::File);
MappedFile file_data{buffer.name()};
buffer.reload(file_data, file_data.st.st_mtim);
buffer.flags() &= ~Buffer::Flags::New;
}
Buffer* create_fifo_buffer(String name, int fd, Buffer::Flags flags, bool scroll)
{
static ValueId s_fifo_watcher_id = get_free_value_id();
auto& buffer_manager = BufferManager::instance();
Buffer* buffer = buffer_manager.get_buffer_ifp(name);
if (buffer)
{
buffer->flags() |= Buffer::Flags::NoUndo | flags;
buffer->reload({}, InvalidTime);
}
else
buffer = buffer_manager.create_buffer(
std::move(name), flags | Buffer::Flags::Fifo | Buffer::Flags::NoUndo);
auto watcher_deleter = [buffer](FDWatcher* watcher) {
kak_assert(buffer->flags() & Buffer::Flags::Fifo);
watcher->close_fd();
buffer->run_hook_in_own_context(Hook::BufCloseFifo, "");
buffer->flags() &= ~(Buffer::Flags::Fifo | Buffer::Flags::NoUndo);
delete watcher;
};
// capture a non static one to silence a warning.
ValueId fifo_watcher_id = s_fifo_watcher_id;
std::unique_ptr<FDWatcher, decltype(watcher_deleter)> watcher(
new FDWatcher(fd, FdEvents::Read,
[buffer, scroll, fifo_watcher_id](FDWatcher& watcher, FdEvents, EventMode mode) {
if (mode != EventMode::Normal)
return;
kak_assert(buffer->flags() & Buffer::Flags::Fifo);
constexpr size_t buffer_size = 2048;
// if we read data slower than it arrives in the fifo, limiting the
// iteration number allows us to go back go back to the event loop and
// handle other events sources (such as input)
constexpr size_t max_loop = 16;
bool closed = false;
size_t loop = 0;
char data[buffer_size];
BufferCoord insert_coord = buffer->back_coord();
const int fifo = watcher.fd();
do
{
const ssize_t count = ::read(fifo, data, buffer_size);
if (count <= 0)
{
closed = true;
break;
}
auto pos = buffer->back_coord();
const bool prevent_scrolling = pos == BufferCoord{0,0} and not scroll;
if (prevent_scrolling)
pos = buffer->next(pos);
buffer->insert(pos, StringView(data, data+count));
if (prevent_scrolling)
{
buffer->erase({0,0}, buffer->next({0,0}));
// in the other case, the buffer will have automatically
// inserted a \n to guarantee its invariant.
if (data[count-1] == '\n')
buffer->insert(buffer->end_coord(), "\n");
}
}
while (++loop < max_loop and fd_readable(fifo));
if (insert_coord != buffer->back_coord())
{
buffer->run_hook_in_own_context(
Hook::BufReadFifo,
selection_to_string(ColumnType::Byte, *buffer, {insert_coord, buffer->back_coord()}));
}
if (closed)
buffer->values().erase(fifo_watcher_id); // will delete this
}), std::move(watcher_deleter));
buffer->values()[fifo_watcher_id] = Value(std::move(watcher));
buffer->flags() = flags | Buffer::Flags::Fifo | Buffer::Flags::NoUndo;
buffer->run_hook_in_own_context(Hook::BufOpenFifo, buffer->name());
return buffer;
}
void write_to_debug_buffer(StringView str)
{
if (not BufferManager::has_instance())
{
write(2, str);
write(2, "\n");
return;
}
constexpr StringView debug_buffer_name = "*debug*";
// Try to ensure we keep an empty line at the end of the debug buffer
// where the user can put its cursor to scroll with new messages
const bool eol_back = not str.empty() and str.back() == '\n';
if (Buffer* buffer = BufferManager::instance().get_buffer_ifp(debug_buffer_name))
{
buffer->flags() &= ~Buffer::Flags::ReadOnly;
auto restore = on_scope_end([buffer] { buffer->flags() |= Buffer::Flags::ReadOnly; });
buffer->insert(buffer->back_coord(), eol_back ? str : str + "\n");
}
else
{
String line = str + (eol_back ? "\n" : "\n\n");
BufferManager::instance().create_buffer(
debug_buffer_name.str(), Buffer::Flags::NoUndo | Buffer::Flags::Debug | Buffer::Flags::ReadOnly,
line, InvalidTime);
}
}
}
<commit_msg>Refactor fifo buffer reader code<commit_after>#include "buffer_utils.hh"
#include "buffer_manager.hh"
#include "event_manager.hh"
#include "file.hh"
#include "selection.hh"
#include <unistd.h>
#if defined(__APPLE__)
#define st_mtim st_mtimespec
#endif
namespace Kakoune
{
ColumnCount get_column(const Buffer& buffer,
ColumnCount tabstop, BufferCoord coord)
{
auto line = buffer[coord.line];
auto col = 0_col;
for (auto it = line.begin();
it != line.end() and coord.column > (int)(it - line.begin()); )
{
if (*it == '\t')
{
col = (col / tabstop + 1) * tabstop;
++it;
}
else
col += codepoint_width(utf8::read_codepoint(it, line.end()));
}
return col;
}
ColumnCount column_length(const Buffer& buffer, ColumnCount tabstop, LineCount line)
{
return get_column(buffer, tabstop, BufferCoord{line, ByteCount{INT_MAX}});
}
ByteCount get_byte_to_column(const Buffer& buffer, ColumnCount tabstop, DisplayCoord coord)
{
auto line = buffer[coord.line];
auto col = 0_col;
auto it = line.begin();
while (it != line.end() and coord.column > col)
{
if (*it == '\t')
{
col = (col / tabstop + 1) * tabstop;
if (col > coord.column) // the target column was in the tab
break;
++it;
}
else
{
auto next = it;
col += codepoint_width(utf8::read_codepoint(next, line.end()));
if (col > coord.column) // the target column was in the char
break;
it = next;
}
}
return (int)(it - line.begin());
}
Buffer* open_file_buffer(StringView filename, Buffer::Flags flags)
{
MappedFile file_data{parse_filename(filename)};
return BufferManager::instance().create_buffer(
filename.str(), Buffer::Flags::File | flags, file_data, file_data.st.st_mtim);
}
Buffer* open_or_create_file_buffer(StringView filename, Buffer::Flags flags)
{
auto& buffer_manager = BufferManager::instance();
auto path = parse_filename(filename);
if (file_exists(path))
{
MappedFile file_data{path};
return buffer_manager.create_buffer(filename.str(), Buffer::Flags::File | flags,
file_data, file_data.st.st_mtim);
}
return buffer_manager.create_buffer(
filename.str(), Buffer::Flags::File | Buffer::Flags::New,
{}, InvalidTime);
}
void reload_file_buffer(Buffer& buffer)
{
kak_assert(buffer.flags() & Buffer::Flags::File);
MappedFile file_data{buffer.name()};
buffer.reload(file_data, file_data.st.st_mtim);
buffer.flags() &= ~Buffer::Flags::New;
}
Buffer* create_fifo_buffer(String name, int fd, Buffer::Flags flags, bool scroll)
{
static ValueId fifo_watcher_id = get_free_value_id();
auto& buffer_manager = BufferManager::instance();
Buffer* buffer = buffer_manager.get_buffer_ifp(name);
if (buffer)
{
buffer->flags() |= Buffer::Flags::NoUndo | flags;
buffer->reload({}, InvalidTime);
}
else
buffer = buffer_manager.create_buffer(
std::move(name), flags | Buffer::Flags::Fifo | Buffer::Flags::NoUndo);
struct FifoWatcher : FDWatcher
{
FifoWatcher(int fd, Buffer& buffer, bool scroll)
: FDWatcher(fd, FdEvents::Read,
[](FDWatcher& watcher, FdEvents, EventMode mode) {
if (mode == EventMode::Normal)
static_cast<FifoWatcher&>(watcher).read_fifo();
}),
m_buffer(buffer), m_scroll(scroll)
{}
~FifoWatcher()
{
kak_assert(m_buffer.flags() & Buffer::Flags::Fifo);
close_fd();
m_buffer.run_hook_in_own_context(Hook::BufCloseFifo, "");
m_buffer.flags() &= ~(Buffer::Flags::Fifo | Buffer::Flags::NoUndo);
}
void read_fifo() const
{
kak_assert(m_buffer.flags() & Buffer::Flags::Fifo);
constexpr size_t buffer_size = 2048;
// if we read data slower than it arrives in the fifo, limiting the
// iteration number allows us to go back go back to the event loop and
// handle other events sources (such as input)
constexpr size_t max_loop = 16;
bool closed = false;
size_t loop = 0;
char data[buffer_size];
BufferCoord insert_coord = m_buffer.back_coord();
const int fifo = fd();
do
{
const ssize_t count = ::read(fifo, data, buffer_size);
if (count <= 0)
{
closed = true;
break;
}
auto pos = m_buffer.back_coord();
const bool prevent_scrolling = pos == BufferCoord{0,0} and not m_scroll;
if (prevent_scrolling)
pos = m_buffer.next(pos);
m_buffer.insert(pos, StringView(data, data+count));
if (prevent_scrolling)
{
m_buffer.erase({0,0}, m_buffer.next({0,0}));
// in the other case, the buffer will have automatically
// inserted a \n to guarantee its invariant.
if (data[count-1] == '\n')
m_buffer.insert(m_buffer.end_coord(), "\n");
}
}
while (++loop < max_loop and fd_readable(fifo));
if (insert_coord != m_buffer.back_coord())
m_buffer.run_hook_in_own_context(
Hook::BufReadFifo,
selection_to_string(ColumnType::Byte, m_buffer, {insert_coord, m_buffer.back_coord()}));
if (closed)
m_buffer.values().erase(fifo_watcher_id); // will delete this
}
Buffer& m_buffer;
bool m_scroll;
};
buffer->values()[fifo_watcher_id] = Value(std::make_unique<FifoWatcher>(fd, *buffer, scroll));
buffer->flags() = flags | Buffer::Flags::Fifo | Buffer::Flags::NoUndo;
buffer->run_hook_in_own_context(Hook::BufOpenFifo, buffer->name());
return buffer;
}
void write_to_debug_buffer(StringView str)
{
if (not BufferManager::has_instance())
{
write(2, str);
write(2, "\n");
return;
}
constexpr StringView debug_buffer_name = "*debug*";
// Try to ensure we keep an empty line at the end of the debug buffer
// where the user can put its cursor to scroll with new messages
const bool eol_back = not str.empty() and str.back() == '\n';
if (Buffer* buffer = BufferManager::instance().get_buffer_ifp(debug_buffer_name))
{
buffer->flags() &= ~Buffer::Flags::ReadOnly;
auto restore = on_scope_end([buffer] { buffer->flags() |= Buffer::Flags::ReadOnly; });
buffer->insert(buffer->back_coord(), eol_back ? str : str + "\n");
}
else
{
String line = str + (eol_back ? "\n" : "\n\n");
BufferManager::instance().create_buffer(
debug_buffer_name.str(), Buffer::Flags::NoUndo | Buffer::Flags::Debug | Buffer::Flags::ReadOnly,
line, InvalidTime);
}
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "WiimoteFactory.h"
WiimoteFactory::WiimoteFactory()
:DeviceIndex(0), DeviceInfoSet(NULL), OpenDevice(INVALID_HANDLE_VALUE)
{
HidD_GetHidGuid(&HidGuid);
ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
}
WiimoteFactory::~WiimoteFactory()
{
if (DeviceInfoSet)
{
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
DeviceInfoSet = NULL;
}
}
WiimoteDeviceVector WiimoteFactory::GetWiimoteDevices()
{
DeviceInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (!DeviceInfoSet)
{
std::cout << "No HID Devices Found!" << std::endl;
return WiimoteDevices;
}
while (SetupDiEnumDeviceInterfaces(DeviceInfoSet, NULL, &HidGuid, DeviceIndex, &DeviceInterfaceData))
{
std::cout << "--- New Device ---" << std::endl;
CheckEnumeratedDeviceInterface();
DeviceIndex++;
std::cout << "------------------" << std::endl;
}
if (DeviceIndex == 0)
{
std::cout << "No Device Enumerated!" << std::endl;
}
return WiimoteDevices;
}
void WiimoteFactory::CheckEnumeratedDeviceInterface()
{
BOOL Result;
DWORD RequiredSize;
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, NULL, 0, &RequiredSize, NULL);
PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, DeviceInterfaceDetailData, RequiredSize, NULL, &DeviceInfoData);
BOOL IsWiimote = CheckDevice(DeviceInterfaceDetailData->DevicePath);
if (IsWiimote)
{
WiimoteDevices.push_back(WiimoteDevice(OpenDevice));
}
else
{
CloseHandle(OpenDevice);
}
OpenDevice = INVALID_HANDLE_VALUE;
free(DeviceInterfaceDetailData);
}
BOOL WiimoteFactory::CheckDevice(LPCTSTR DevicePath)
{
OpenDevice = CreateFile(DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (OpenDevice == INVALID_HANDLE_VALUE)
{
std::cout << "Failed to open Device." << std::endl;
return FALSE;
}
std::cout << "Device Handle: \t0x" << std::hex << OpenDevice << std::endl;
HIDD_ATTRIBUTES HidAttributes;
HidAttributes.Size = sizeof(HidAttributes);
BOOL Result = HidD_GetAttributes(OpenDevice, &HidAttributes);
if (!Result)
{
std::cout << "Failed to get hid attributes" << std::endl;
return FALSE;
}
std::cout << "VID&PID: \t" << HidAttributes.VendorID << " - " << HidAttributes.ProductID << std::endl;
TCHAR ProductName[255];
if (HidD_GetProductString(OpenDevice, ProductName, 255))
{
std::wcout << "HID Name: \t" << ProductName << std::endl;
}
PrintDeviceName(DeviceInfoSet, &DeviceInfoData);
PrintDriverInfo(DeviceInfoSet, &DeviceInfoData);
return (HidAttributes.VendorID == 0x057e) && ((HidAttributes.ProductID == 0x0306) || (HidAttributes.ProductID == 0x0330));
}
void WiimoteFactory::PrintDeviceName(HDEVINFO & DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData)
{
DWORD RequiredSize = 0;
DEVPROPTYPE DevicePropertyType;
SetupDiGetDeviceProperty(DeviceInfoSet, DeviceInfoData, &DEVPKEY_NAME, &DevicePropertyType, NULL, 0, &RequiredSize, 0);
PBYTE Buffer = (PBYTE)malloc(RequiredSize);
ZeroMemory(Buffer, RequiredSize);
BOOL Result = SetupDiGetDeviceProperty(DeviceInfoSet, DeviceInfoData, &DEVPKEY_NAME, &DevicePropertyType, Buffer, RequiredSize, NULL, 0);
if (!Result)
{
std::cout << "Error getting Device Name property: 0x" << std::hex << GetLastError() << std::endl;
}
else
{
std::wcout << "Device Name: \t" << (PWCHAR) Buffer << std::endl;
}
free(Buffer);
}
void WiimoteFactory::PrintDriverInfo(HDEVINFO & DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData)
{
SP_DRVINFO_DATA DriverInfo;
ZeroMemory(&DriverInfo, sizeof(SP_DRVINFO_DATA));
DriverInfo.cbSize = sizeof(SP_DRVINFO_DATA);
BOOL Result = SetupDiGetSelectedDriver(DeviceInfoSet, DeviceInfoData, &DriverInfo);
if (Result)
{
std::cout << "Driver Type: \t" << ((DriverInfo.DriverType == SPDIT_CLASSDRIVER) ? "Class Driver" : "Compatible Driver") << std::endl;
std::cout << "Description: \t" << DriverInfo.Description << std::endl;
std::cout << "MfgName: \t" << DriverInfo.MfgName << std::endl;
std::cout << "ProviderName: \t" << DriverInfo.ProviderName << std::endl;
}
else
{
DWORD Error = GetLastError();
if (Error == ERROR_NO_DRIVER_SELECTED)
{
std::cout << "No driver for the device" << std::endl;
}
else
{
std::cout << "Error getting Driver Info 0x" << std::hex << Error << std::endl;
}
}
}<commit_msg>Fix print out on Toshiba Stack<commit_after>#include "stdafx.h"
#include "WiimoteFactory.h"
WiimoteFactory::WiimoteFactory()
:DeviceIndex(0), DeviceInfoSet(NULL), OpenDevice(INVALID_HANDLE_VALUE)
{
HidD_GetHidGuid(&HidGuid);
ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
}
WiimoteFactory::~WiimoteFactory()
{
if (DeviceInfoSet)
{
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
DeviceInfoSet = NULL;
}
}
WiimoteDeviceVector WiimoteFactory::GetWiimoteDevices()
{
DeviceInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (!DeviceInfoSet)
{
std::cout << "No HID Devices Found!" << std::endl;
return WiimoteDevices;
}
while (SetupDiEnumDeviceInterfaces(DeviceInfoSet, NULL, &HidGuid, DeviceIndex, &DeviceInterfaceData))
{
std::cout << "--- New Device ---" << std::endl;
CheckEnumeratedDeviceInterface();
DeviceIndex++;
std::cout << "------------------" << std::endl;
}
if (DeviceIndex == 0)
{
std::cout << "No Device Enumerated!" << std::endl;
}
return WiimoteDevices;
}
void WiimoteFactory::CheckEnumeratedDeviceInterface()
{
BOOL Result;
DWORD RequiredSize;
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, NULL, 0, &RequiredSize, NULL);
PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, DeviceInterfaceDetailData, RequiredSize, NULL, &DeviceInfoData);
BOOL IsWiimote = CheckDevice(DeviceInterfaceDetailData->DevicePath);
if (IsWiimote)
{
WiimoteDevices.push_back(WiimoteDevice(OpenDevice));
}
else
{
CloseHandle(OpenDevice);
}
OpenDevice = INVALID_HANDLE_VALUE;
free(DeviceInterfaceDetailData);
}
BOOL WiimoteFactory::CheckDevice(LPCTSTR DevicePath)
{
OpenDevice = CreateFile(DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (OpenDevice == INVALID_HANDLE_VALUE)
{
std::cout << "Failed to open Device." << std::endl;
return FALSE;
}
std::cout << "Device Handle: \t0x" << std::hex << OpenDevice << std::endl;
HIDD_ATTRIBUTES HidAttributes;
HidAttributes.Size = sizeof(HidAttributes);
BOOL Result = HidD_GetAttributes(OpenDevice, &HidAttributes);
if (!Result)
{
std::cout << "Failed to get hid attributes" << std::endl;
return FALSE;
}
std::cout << "VID&PID: \t" << HidAttributes.VendorID << " - " << HidAttributes.ProductID << std::endl;
WCHAR ProductName[255];
ZeroMemory(ProductName, sizeof(ProductName));
if (HidD_GetProductString(OpenDevice, ProductName, 255))
{
std::wcout << "HID Name: \t" << ProductName << std::endl;
}
PrintDeviceName(DeviceInfoSet, &DeviceInfoData);
PrintDriverInfo(DeviceInfoSet, &DeviceInfoData);
return (HidAttributes.VendorID == 0x057e) && ((HidAttributes.ProductID == 0x0306) || (HidAttributes.ProductID == 0x0330));
}
void WiimoteFactory::PrintDeviceName(HDEVINFO & DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData)
{
DWORD RequiredSize = 0;
DEVPROPTYPE DevicePropertyType;
SetupDiGetDeviceProperty(DeviceInfoSet, DeviceInfoData, &DEVPKEY_NAME, &DevicePropertyType, NULL, 0, &RequiredSize, 0);
PBYTE Buffer = (PBYTE)malloc(RequiredSize);
ZeroMemory(Buffer, RequiredSize);
BOOL Result = SetupDiGetDeviceProperty(DeviceInfoSet, DeviceInfoData, &DEVPKEY_NAME, &DevicePropertyType, Buffer, RequiredSize, NULL, 0);
if (!Result)
{
std::cout << "Error getting Device Name property: 0x" << std::hex << GetLastError() << std::endl;
}
else
{
std::wcout << "Device Name: \t" << (PWCHAR) Buffer << std::endl;
}
free(Buffer);
}
void WiimoteFactory::PrintDriverInfo(HDEVINFO & DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData)
{
SP_DRVINFO_DATA DriverInfo;
ZeroMemory(&DriverInfo, sizeof(SP_DRVINFO_DATA));
DriverInfo.cbSize = sizeof(SP_DRVINFO_DATA);
BOOL Result = SetupDiGetSelectedDriver(DeviceInfoSet, DeviceInfoData, &DriverInfo);
if (Result)
{
std::cout << "Driver Type: \t" << ((DriverInfo.DriverType == SPDIT_CLASSDRIVER) ? "Class Driver" : "Compatible Driver") << std::endl;
std::cout << "Description: \t" << DriverInfo.Description << std::endl;
std::cout << "MfgName: \t" << DriverInfo.MfgName << std::endl;
std::cout << "ProviderName: \t" << DriverInfo.ProviderName << std::endl;
}
else
{
DWORD Error = GetLastError();
if (Error == ERROR_NO_DRIVER_SELECTED)
{
std::cout << "No driver for the device" << std::endl;
}
else
{
std::cout << "Error getting Driver Info 0x" << std::hex << Error << std::endl;
}
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hierarchyprovider.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 18:07:11 $
*
* 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 _HIERARCHYPROVIDER_HXX
#define _HIERARCHYPROVIDER_HXX
#include <hash_map>
#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
namespace com { namespace sun { namespace star {
namespace container {
class XHierarchicalNameAccess;
}
namespace util {
class XOfficeInstallationDirectories;
}
} } }
namespace hierarchy_ucp {
//=========================================================================
#define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME \
"com.sun.star.ucb.HierarchyContentProvider"
#define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 41
#define HIERARCHY_URL_SCHEME \
"vnd.sun.star.hier"
#define HIERARCHY_URL_SCHEME_LENGTH 17
#define HIERARCHY_FOLDER_CONTENT_TYPE \
"application/" HIERARCHY_URL_SCHEME "-folder"
#define HIERARCHY_LINK_CONTENT_TYPE \
"application/" HIERARCHY_URL_SCHEME "-link"
//=========================================================================
struct ConfigProviderMapEntry
{
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory > xConfigProvider;
com::sun::star::uno::Reference<
com::sun::star::container::XHierarchicalNameAccess > xRootReadAccess;
bool bTriedToGetRootReadAccess; // #82494#
ConfigProviderMapEntry() : bTriedToGetRootReadAccess( false ) {}
};
struct equalString
{
bool operator()(
const rtl::OUString& rKey1, const rtl::OUString& rKey2 ) const
{
return !!( rKey1 == rKey2 );
}
};
struct hashString
{
size_t operator()( const rtl::OUString & rName ) const
{
return rName.hashCode();
}
};
typedef std::hash_map
<
rtl::OUString, // servcie specifier
ConfigProviderMapEntry,
hashString,
equalString
>
ConfigProviderMap;
//=========================================================================
class HierarchyContentProvider : public ::ucbhelper::ContentProviderImplHelper,
public com::sun::star::lang::XInitialization
{
ConfigProviderMap m_aConfigProviderMap;
com::sun::star::uno::Reference<
com::sun::star::util::XOfficeInstallationDirectories > m_xOfficeInstDirs;
public:
HierarchyContentProvider(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rXSMgr );
virtual ~HierarchyContentProvider();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
XSERVICEINFO_DECL()
// XContentProvider
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContent > SAL_CALL
queryContent( const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier )
throw( com::sun::star::ucb::IllegalIdentifierException,
com::sun::star::uno::RuntimeException );
// XInitialization
virtual void SAL_CALL
initialize( const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Any >& aArguments )
throw( ::com::sun::star::uno::Exception,
::com::sun::star::uno::RuntimeException );
// Non-Interface methods
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >
getConfigProvider( const rtl::OUString & rServiceSpecifier );
com::sun::star::uno::Reference<
com::sun::star::container::XHierarchicalNameAccess >
getRootConfigReadNameAccess( const rtl::OUString & rServiceSpecifier );
// Note: may retrun an empty reference.
com::sun::star::uno::Reference<
com::sun::star::util::XOfficeInstallationDirectories >
getOfficeInstallationDirectories();
};
} // namespace hierarchy_ucp
#endif /* !_HIERARCHYPROVIDER_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.8.72); FILE MERGED 2008/04/01 16:02:20 thb 1.8.72.3: #i85898# Stripping all external header guards 2008/04/01 12:58:18 thb 1.8.72.2: #i85898# Stripping all external header guards 2008/03/31 15:30:24 rt 1.8.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hierarchyprovider.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _HIERARCHYPROVIDER_HXX
#define _HIERARCHYPROVIDER_HXX
#include <hash_map>
#include <ucbhelper/providerhelper.hxx>
#include <com/sun/star/lang/XInitialization.hpp>
namespace com { namespace sun { namespace star {
namespace container {
class XHierarchicalNameAccess;
}
namespace util {
class XOfficeInstallationDirectories;
}
} } }
namespace hierarchy_ucp {
//=========================================================================
#define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME \
"com.sun.star.ucb.HierarchyContentProvider"
#define HIERARCHY_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 41
#define HIERARCHY_URL_SCHEME \
"vnd.sun.star.hier"
#define HIERARCHY_URL_SCHEME_LENGTH 17
#define HIERARCHY_FOLDER_CONTENT_TYPE \
"application/" HIERARCHY_URL_SCHEME "-folder"
#define HIERARCHY_LINK_CONTENT_TYPE \
"application/" HIERARCHY_URL_SCHEME "-link"
//=========================================================================
struct ConfigProviderMapEntry
{
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory > xConfigProvider;
com::sun::star::uno::Reference<
com::sun::star::container::XHierarchicalNameAccess > xRootReadAccess;
bool bTriedToGetRootReadAccess; // #82494#
ConfigProviderMapEntry() : bTriedToGetRootReadAccess( false ) {}
};
struct equalString
{
bool operator()(
const rtl::OUString& rKey1, const rtl::OUString& rKey2 ) const
{
return !!( rKey1 == rKey2 );
}
};
struct hashString
{
size_t operator()( const rtl::OUString & rName ) const
{
return rName.hashCode();
}
};
typedef std::hash_map
<
rtl::OUString, // servcie specifier
ConfigProviderMapEntry,
hashString,
equalString
>
ConfigProviderMap;
//=========================================================================
class HierarchyContentProvider : public ::ucbhelper::ContentProviderImplHelper,
public com::sun::star::lang::XInitialization
{
ConfigProviderMap m_aConfigProviderMap;
com::sun::star::uno::Reference<
com::sun::star::util::XOfficeInstallationDirectories > m_xOfficeInstDirs;
public:
HierarchyContentProvider(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rXSMgr );
virtual ~HierarchyContentProvider();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
XSERVICEINFO_DECL()
// XContentProvider
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContent > SAL_CALL
queryContent( const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier )
throw( com::sun::star::ucb::IllegalIdentifierException,
com::sun::star::uno::RuntimeException );
// XInitialization
virtual void SAL_CALL
initialize( const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Any >& aArguments )
throw( ::com::sun::star::uno::Exception,
::com::sun::star::uno::RuntimeException );
// Non-Interface methods
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >
getConfigProvider( const rtl::OUString & rServiceSpecifier );
com::sun::star::uno::Reference<
com::sun::star::container::XHierarchicalNameAccess >
getRootConfigReadNameAccess( const rtl::OUString & rServiceSpecifier );
// Note: may retrun an empty reference.
com::sun::star::uno::Reference<
com::sun::star::util::XOfficeInstallationDirectories >
getOfficeInstallationDirectories();
};
} // namespace hierarchy_ucp
#endif /* !_HIERARCHYPROVIDER_HXX */
<|endoftext|> |
<commit_before>#ifndef _CCTAG_MARKERS_TYPES_HPP_
#define _CCTAG_MARKERS_TYPES_HPP_
#include <memory>
#include <new>
#include <stdexcept>
#include <cctag/EdgePoint.hpp>
namespace cctag {
class EdgePointCollection
{
using link_pair = std::tuple<int, int>; // 0: before, 1: after
static_assert(sizeof(link_pair)==8, "int_pair not packed");
static constexpr size_t MAX_POINTS = size_t(1) << 20;
static constexpr size_t MAX_RESOLUTION = 2048;
static constexpr size_t CUDA_OFFSET = 1024; // 4 kB, one page
static constexpr size_t MAX_VOTERLIST_SIZE = 16*MAX_POINTS;
public:
using int_vector = std::vector<int>;
using voter_list = std::pair<const int*, const int*>;
private:
std::unique_ptr<int[]> _edgeMap;
std::unique_ptr<EdgePoint[]> _edgeList;
std::unique_ptr<link_pair[]> _linkList;
std::unique_ptr<int[]> _votersIndex; // with CUDA_OFFSET; [0] is point count
std::unique_ptr<int[]> _votersList;
size_t _edgeMapShape[2];
int& point_count() { return _votersIndex[0]; }
int point_count() const { return _votersIndex[0]; }
size_t map_index(int x, int y) const { return x + y * _edgeMapShape[0]; }
public:
EdgePointCollection() = default;
EdgePointCollection(const EdgePointCollection&) = delete;
EdgePointCollection& operator=(const EdgePointCollection&) = delete;
EdgePointCollection(size_t w, size_t h) :
_edgeMap(new int[MAX_RESOLUTION*MAX_RESOLUTION]),
_edgeList(new EdgePoint[MAX_POINTS]),
_linkList(new link_pair[MAX_POINTS]),
_votersIndex(new int[MAX_POINTS+CUDA_OFFSET]),
_votersList(new int[MAX_VOTERLIST_SIZE])
{
if (w > MAX_RESOLUTION || h > MAX_RESOLUTION)
throw std::length_error("EdgePointCollection::set_frame_size: dimension too large");
point_count() = 0;
_edgeMapShape[0] = w; _edgeMapShape[1] = h;
memset(&_edgeMap[0], -1, w*h*sizeof(int));
}
void add_point(int vx, int vy, float vdx, float vdy)
{
if (vx < 0 || vx >= _edgeMapShape[0] || vy < 0 || vy >= _edgeMapShape[1])
throw std::out_of_range("EdgePointCollection::add_point: coordinate out of range");
size_t imap = map_index(vx, vy);
if (_edgeMap[imap] != -1)
throw std::logic_error("EdgePointCollection::add_point: point already exists");
// XXX@stian: new() below is technically UB, but the class has no defined dtors
// so it's safe to re-new it in place w/o calling the dtor firs.
size_t ipoint = point_count()++;
_edgeMap[imap] = ipoint;
new (&_edgeList[ipoint]) EdgePoint(vx, vy, vdx, vdy);
_linkList[ipoint] = std::make_tuple(-1, -1);
// voter lists must be constructed afterwards
}
int get_point_count()
{
return point_count();
}
const size_t* shape() const { return _edgeMapShape; }
EdgePoint* operator()(int i) { return i >= 0 ? &_edgeList[i] : nullptr; }
EdgePoint* operator()(int i) const { return i >= 0 ? const_cast<EdgePoint*>(&_edgeList[i]) : nullptr; }
EdgePoint* operator()(int x, int y) const { return (*this)(_edgeMap[map_index(x,y)]); }
int operator()(const EdgePoint* p) const
{
if (!p)
return -1;
if (p < _edgeList.get())
throw std::logic_error("EdgePointCollection::index: invalid pointer (1)");
int i = p - _edgeList.get();
if (i >= point_count())
throw std::logic_error("EdgePointCollection::index: invalid pointer (2)");
return i;
}
void create_voter_lists(const std::vector<std::vector<int>>& voter_lists);
voter_list voters(const EdgePoint* p) const
{
int i = (*this)(p);
int b = _votersIndex[i+CUDA_OFFSET], e = _votersIndex[i+1+CUDA_OFFSET];
return std::make_pair(&_votersList[0]+b, &_votersList[0]+e);
}
int voters_size(const EdgePoint* p) const
{
int i = (*this)(p);
int b = _votersIndex[i+CUDA_OFFSET], e = _votersIndex[i+1+CUDA_OFFSET];
return e - b;
}
EdgePoint* before(EdgePoint* p) const
{
int i = (*this)(p);
return (*this)(std::get<0>(_linkList[i]));
}
void set_before(EdgePoint* p, int link)
{
int i = (*this)(p);
std::get<0>(_linkList[i]) = link;
}
EdgePoint* after(EdgePoint* p) const
{
int i = (*this)(p);
return (*this)(std::get<1>(_linkList[i]));
}
void set_after(EdgePoint* p, int link)
{
int i = (*this)(p);
std::get<1>(_linkList[i]) = link;
}
};
} // namespace cctag
#endif
<commit_msg>Replaced std::tuple by int[] of double length.<commit_after>#ifndef _CCTAG_MARKERS_TYPES_HPP_
#define _CCTAG_MARKERS_TYPES_HPP_
#include <memory>
#include <new>
#include <stdexcept>
#include <cctag/EdgePoint.hpp>
namespace cctag {
class EdgePointCollection
{
static constexpr size_t MAX_POINTS = size_t(1) << 20;
static constexpr size_t MAX_RESOLUTION = 2048;
static constexpr size_t CUDA_OFFSET = 1024; // 4 kB, one page
static constexpr size_t MAX_VOTERLIST_SIZE = 16*MAX_POINTS;
public:
using int_vector = std::vector<int>;
using voter_list = std::pair<const int*, const int*>;
private:
std::unique_ptr<int[]> _edgeMap;
std::unique_ptr<EdgePoint[]> _edgeList;
std::unique_ptr<int[]> _linkList; // even idx: before, odd: after
std::unique_ptr<int[]> _votersIndex; // with CUDA_OFFSET; [0] is point count
std::unique_ptr<int[]> _votersList;
size_t _edgeMapShape[2];
int& point_count() { return _votersIndex[0]; }
int point_count() const { return _votersIndex[0]; }
size_t map_index(int x, int y) const { return x + y * _edgeMapShape[0]; }
public:
EdgePointCollection() = default;
EdgePointCollection(const EdgePointCollection&) = delete;
EdgePointCollection& operator=(const EdgePointCollection&) = delete;
EdgePointCollection(size_t w, size_t h) :
_edgeMap(new int[MAX_RESOLUTION*MAX_RESOLUTION]),
_edgeList(new EdgePoint[MAX_POINTS]),
_linkList(new int[2*MAX_POINTS]),
_votersIndex(new int[MAX_POINTS+CUDA_OFFSET]),
_votersList(new int[MAX_VOTERLIST_SIZE])
{
if (w > MAX_RESOLUTION || h > MAX_RESOLUTION)
throw std::length_error("EdgePointCollection::set_frame_size: dimension too large");
point_count() = 0;
_edgeMapShape[0] = w; _edgeMapShape[1] = h;
memset(&_edgeMap[0], -1, w*h*sizeof(int)); // XXX@stian: unnecessary for CUDA
}
void add_point(int vx, int vy, float vdx, float vdy)
{
if (vx < 0 || vx >= _edgeMapShape[0] || vy < 0 || vy >= _edgeMapShape[1])
throw std::out_of_range("EdgePointCollection::add_point: coordinate out of range");
size_t imap = map_index(vx, vy);
if (_edgeMap[imap] != -1)
throw std::logic_error("EdgePointCollection::add_point: point already exists");
// XXX@stian: new() below is technically UB, but the class has no defined dtors
// so it's safe to re-new it in place w/o calling the dtor firs.
size_t ipoint = point_count()++;
_edgeMap[imap] = ipoint;
new (&_edgeList[ipoint]) EdgePoint(vx, vy, vdx, vdy);
_linkList[2*ipoint+0] = -1;
_linkList[2*ipoint+1] = -1;
// voter lists must be constructed afterwards
}
int get_point_count()
{
return point_count();
}
const size_t* shape() const { return _edgeMapShape; }
EdgePoint* operator()(int i) { return i >= 0 ? &_edgeList[i] : nullptr; }
EdgePoint* operator()(int i) const { return i >= 0 ? const_cast<EdgePoint*>(&_edgeList[i]) : nullptr; }
EdgePoint* operator()(int x, int y) const { return (*this)(_edgeMap[map_index(x,y)]); }
int operator()(const EdgePoint* p) const
{
if (!p)
return -1;
if (p < _edgeList.get())
throw std::logic_error("EdgePointCollection::index: invalid pointer (1)");
int i = p - _edgeList.get();
if (i >= point_count())
throw std::logic_error("EdgePointCollection::index: invalid pointer (2)");
return i;
}
void create_voter_lists(const std::vector<std::vector<int>>& voter_lists);
voter_list voters(const EdgePoint* p) const
{
int i = (*this)(p);
int b = _votersIndex[i+CUDA_OFFSET], e = _votersIndex[i+1+CUDA_OFFSET];
return std::make_pair(&_votersList[0]+b, &_votersList[0]+e);
}
int voters_size(const EdgePoint* p) const
{
int i = (*this)(p);
int b = _votersIndex[i+CUDA_OFFSET], e = _votersIndex[i+1+CUDA_OFFSET];
return e - b;
}
EdgePoint* before(EdgePoint* p) const
{
int i = (*this)(p);
return (*this)(_linkList[2*i+0]);
}
void set_before(EdgePoint* p, int link)
{
int i = (*this)(p);
_linkList[2*i+0] = link;
}
EdgePoint* after(EdgePoint* p) const
{
int i = (*this)(p);
return (*this)(_linkList[2*i+1]);
}
void set_after(EdgePoint* p, int link)
{
int i = (*this)(p);
_linkList[2*i+1] = link;
}
};
} // namespace cctag
#endif
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(h)
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
// Iterative solution.
class Solution {
public:
NestedInteger deserialize(string s) {
if (s.empty()) {
return NestedInteger();
}
if (s[0] != '[') {
return NestedInteger(stoi(s));
}
stack<NestedInteger> stk;
for (int i = 0, j = 0; j < s.length(); ++j) {
if (s[j] == '[') {
stk.emplace(NestedInteger());
i = j + 1;
} else if (s[j] == ',' || s[j] == ']'){
if (isdigit(s[j - 1])) {
stk.top().add(NestedInteger(stoi(s.substr(i, j - i))));
}
if (s[j] == ']' && stk.size() > 1) {
NestedInteger cur = stk.top();
stk.pop();
stk.top().add(cur);
}
i = j + 1;
}
}
return stk.top();
}
};
// Time: O(n)
// Space: O(h)
// Recursive solution.
class Solution2 {
public:
NestedInteger deserialize(string s) {
if (s.empty()) {
return NestedInteger();
}
int i = 0;
return deserializeHelper(s, &i);
}
private:
NestedInteger deserializeHelper(const string& s, int *i) {
NestedInteger result;
if (s[*i] != '[') {
int j = *i;
while (j < s.length() && (s[j] == '-' || isdigit(s[j]))) {
++j;
}
result.setInteger(stoi(s.substr(*i, j - *i + 1)));
*i = j;
} else {
++(*i);
while (*i < s.length() && s[*i] != ']') {
result.add(deserializeHelper(s, i));
if (*i < s.length() && s[*i] == ',') {
++(*i);
}
}
++(*i);
}
return result;
}
};
// Time: O(n)
// Space: O(n)
// Recursive solution.
class Solution3 {
public:
NestedInteger deserialize(string s) {
if (s.empty()) {
return NestedInteger();
}
istringstream in(s); // copy string: extra O(n) space
return deserializeHelper(in);
}
private:
NestedInteger deserializeHelper(istringstream &in) {
NestedInteger result;
int num = 0;
if (in >> num) {
result.setInteger(num);
} else {
in.clear();
in.get();
while (in.peek() != ']') {
result.add(deserializeHelper(in));
if (in.peek() == ',') {
in.get();
}
}
in.get();
}
return result;
}
};
<commit_msg>Update mini-parser.cpp<commit_after>// Time: O(n)
// Space: O(h)
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
// Iterative solution.
class Solution {
public:
NestedInteger deserialize(string s) {
if (s.empty()) {
return NestedInteger();
}
if (s[0] != '[') {
return NestedInteger(stoi(s));
}
stack<NestedInteger> stk;
for (int i = 0, j = 0; j < s.length(); ++j) {
if (s[j] == '[') {
stk.emplace(NestedInteger());
i = j + 1;
} else if (s[j] == ',' || s[j] == ']') {
if (isdigit(s[j - 1])) {
stk.top().add(NestedInteger(stoi(s.substr(i, j - i))));
}
if (s[j] == ']' && stk.size() > 1) {
NestedInteger cur = stk.top();
stk.pop();
stk.top().add(cur);
}
i = j + 1;
}
}
return stk.top();
}
};
// Time: O(n)
// Space: O(h)
// Recursive solution.
class Solution2 {
public:
NestedInteger deserialize(string s) {
if (s.empty()) {
return NestedInteger();
}
int i = 0;
return deserializeHelper(s, &i);
}
private:
NestedInteger deserializeHelper(const string& s, int *i) {
NestedInteger result;
if (s[*i] != '[') {
int j = *i;
while (j < s.length() && (s[j] == '-' || isdigit(s[j]))) {
++j;
}
result.setInteger(stoi(s.substr(*i, j - *i + 1)));
*i = j;
} else {
++(*i);
while (*i < s.length() && s[*i] != ']') {
result.add(deserializeHelper(s, i));
if (*i < s.length() && s[*i] == ',') {
++(*i);
}
}
++(*i);
}
return result;
}
};
// Time: O(n)
// Space: O(n)
// Recursive solution.
class Solution3 {
public:
NestedInteger deserialize(string s) {
if (s.empty()) {
return NestedInteger();
}
istringstream in(s); // copy string: extra O(n) space
return deserializeHelper(in);
}
private:
NestedInteger deserializeHelper(istringstream &in) {
NestedInteger result;
int num = 0;
if (in >> num) {
result.setInteger(num);
} else {
in.clear();
in.get();
while (in.peek() != ']') {
result.add(deserializeHelper(in));
if (in.peek() == ',') {
in.get();
}
}
in.get();
}
return result;
}
};
<|endoftext|> |
<commit_before>// Time: O(m * n * l), l is length of the word
// Space: O(l)
class Solution {
public:
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
bool exist(vector<vector<char>> &board, string word) {
unordered_set<string> ret;
vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
int curr = 0;
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
if (wordSearchDFS(board, visited, word, i, j, curr)) {
return true;
}
}
}
return false;
}
bool wordSearchDFS(vector<vector<char>> &grid,
vector<vector<bool>> &visited,
string word,
int i,
int j,
int curr) {
// Invalid state.
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) {
return false;
}
// Not mathced or visited.
if (grid[i][j] != word[curr] || visited[i][j] ) {
return false;
}
// Update current string.
++curr;
// Find the string, add to the answers.
if (curr == word.length()) {
return true;
}
// Marked as visited.
visited[i][j] = true;
// Try each direction.
vector<pair<int, int>> direction{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
for (int k = 0; k < 4; ++k) {
if (wordSearchDFS(grid, visited, word,
i + direction[k].first, j + direction[k].second, curr)) {
return true;
}
}
visited[i][j] = false;
return false;
}
};
<commit_msg>Update word-search.cpp<commit_after>// Time: O(m * n * l), l is length of the word
// Space: O(l)
class Solution {
public:
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
bool exist(vector<vector<char>> &board, string word) {
unordered_set<string> ret;
vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
int cur = 0;
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
if (wordSearchDFS(board, visited, word, i, j, cur)) {
return true;
}
}
}
return false;
}
bool wordSearchDFS(vector<vector<char>> &grid,
vector<vector<bool>> &visited,
string word,
int i,
int j,
int cur) {
// Invalid state.
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) {
return false;
}
// Not mathced or visited.
if (grid[i][j] != word[cur] || visited[i][j]) {
return false;
}
// Update current string.
++cur;
// Find the string, add to the answers.
if (cur == word.length()) {
return true;
}
// Marked as visited.
visited[i][j] = true;
// Try each direction.
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
for (const auto& d : directions) {
if (wordSearchDFS(grid, visited, word,
i + d.first, j + d.second, cur)) {
return true;
}
}
visited[i][j] = false;
return false;
}
};
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestPBGLAlgorithms.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.
=========================================================================*/
/*
* Copyright (C) 2008 The Trustees of Indiana University.
* Use, modification and distribution is subject to the Boost Software
* License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt)
*/
#include <mpi.h>
#include "vtkBoostBreadthFirstSearch.h"
#include "vtkDataSetAttributes.h"
#include "vtkEdgeListIterator.h"
#include "vtkInEdgeIterator.h"
#include "vtkInformation.h"
#include "vtkIntArray.h"
#include "vtkIOStream.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkMutableUndirectedGraph.h"
#include "vtkOutEdgeIterator.h"
#include "vtkPBGLDistributedGraphHelper.h"
#include "vtkSmartPointer.h"
#include "vtkVertexListIterator.h"
#include <vtksys/stl/algorithm>
#include <vtksys/stl/functional>
#include <vtksys/stl/vector>
#include <boost/parallel/mpi/datatype.hpp> // for get_mpi_datatype
#include <stdlib.h>
#include <assert.h>
using vtkstd::pair;
using vtkstd::vector;
static vtkIdType verticesPerNode = 1000;
void TestDirectedGraph()
{
// Create a new graph
vtkSmartPointer<vtkMutableDirectedGraph> graph
= vtkSmartPointer<vtkMutableDirectedGraph>::New();
// Create a Parallel BGL distributed graph helper
vtkSmartPointer<vtkPBGLDistributedGraphHelper> helper
= vtkSmartPointer<vtkPBGLDistributedGraphHelper>::New();
// Hook the distributed graph helper into the graph. graph will then
// be a distributed graph.
graph->SetDistributedGraphHelper(helper);
int numProcs
= graph->GetInformation()->Get(vtkDataObject::DATA_NUMBER_OF_PIECES());
int myRank
= graph->GetInformation()->Get(vtkDataObject::DATA_PIECE_NUMBER());
if (numProcs == 1)
{
cout << "Distributed-graph test run with one node; nothing to do.\n";
return;
}
// Build a graph with verticesPerNode vertices on each node
if (myRank == 0)
{
(cout << "Building distributed directed graph...").flush();
}
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddVertex();
}
// Add an extra vertex on the first and last processors. These
// vertices will be the source and the sink of search algorithms,
// respectively.
if (myRank == 0 || myRank == numProcs - 1)
{
graph->AddVertex();
}
// Add edges from the ith vertex on each node to the ith vertex on
// the next node (not counting the extra vertices, of course).
if (myRank < numProcs - 1)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, i),
graph->MakeDistributedId(myRank+1, i));
}
}
// Add edges from the source vertex to each of the vertices on the
// first node
if (myRank == 0)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, verticesPerNode),
graph->MakeDistributedId(myRank, i));
}
}
// Add edges from each of the vertices on the last node to the sink
// vertex.
if (myRank == numProcs - 1)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, i),
graph->MakeDistributedId(myRank, verticesPerNode));
}
}
// Synchronize so that everyone catches up
helper->Synchronize();
if (myRank == 0)
{
(cout << " done.\n").flush();
}
// Build the breadth-first search filter
vtkSmartPointer<vtkBoostBreadthFirstSearch> bfs
= vtkSmartPointer<vtkBoostBreadthFirstSearch>::New();
bfs->SetInput(graph);
bfs->SetOriginVertex(graph->MakeDistributedId(0, verticesPerNode));
// Run the breadth-first search
if (myRank == 0)
{
(cout << " Breadth-first search...").flush();
}
bfs->Update();
// Verify the results of the breadth-first search
if (myRank == 0)
{
(cout << " verifying...").flush();
}
graph = bfs->GetOutput();
int index;
vtkIntArray *distArray
= vtkIntArray::SafeDownCast(graph->GetVertexData()->GetArray("BFS", index));
assert(distArray);
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
if (distArray->GetValue(i) != myRank + 1)
{
cerr << "Value at vertex " << i << " on rank " << myRank
<< " is " << distArray->GetValue(i) << ", expected "
<< (myRank + 1) << endl;
}
assert(distArray->GetValue(i) == myRank + 1);
}
if (myRank == 0)
assert(distArray->GetValue(verticesPerNode) == 0);
if (myRank == numProcs - 1)
assert(distArray->GetValue(verticesPerNode) == numProcs + 1);
helper->Synchronize();
if (myRank == 0)
{
(cout << " done.\n").flush();
}
}
int main(int argc, char** argv)
{
MPI_Init(&argc, &argv);
TestDirectedGraph();
MPI_Finalize();
return 0;
}
<commit_msg>ENH: Test breadth-first search on undirected distributed graphs<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestPBGLAlgorithms.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.
=========================================================================*/
/*
* Copyright (C) 2008 The Trustees of Indiana University.
* Use, modification and distribution is subject to the Boost Software
* License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt)
*/
#include <mpi.h>
#include "vtkBoostBreadthFirstSearch.h"
#include "vtkDataSetAttributes.h"
#include "vtkEdgeListIterator.h"
#include "vtkInEdgeIterator.h"
#include "vtkInformation.h"
#include "vtkIntArray.h"
#include "vtkIOStream.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkMutableUndirectedGraph.h"
#include "vtkOutEdgeIterator.h"
#include "vtkPBGLDistributedGraphHelper.h"
#include "vtkSmartPointer.h"
#include "vtkVertexListIterator.h"
#include <vtksys/stl/algorithm>
#include <vtksys/stl/functional>
#include <vtksys/stl/vector>
#include <boost/parallel/mpi/datatype.hpp> // for get_mpi_datatype
#include <stdlib.h>
#include <assert.h>
using vtkstd::pair;
using vtkstd::vector;
static vtkIdType verticesPerNode = 1000;
void TestDirectedGraph()
{
// Create a new graph
vtkSmartPointer<vtkMutableDirectedGraph> graph
= vtkSmartPointer<vtkMutableDirectedGraph>::New();
// Create a Parallel BGL distributed graph helper
vtkSmartPointer<vtkPBGLDistributedGraphHelper> helper
= vtkSmartPointer<vtkPBGLDistributedGraphHelper>::New();
// Hook the distributed graph helper into the graph. graph will then
// be a distributed graph.
graph->SetDistributedGraphHelper(helper);
int numProcs
= graph->GetInformation()->Get(vtkDataObject::DATA_NUMBER_OF_PIECES());
int myRank
= graph->GetInformation()->Get(vtkDataObject::DATA_PIECE_NUMBER());
if (numProcs == 1)
{
cout << "Distributed-graph test run with one node; nothing to do.\n";
return;
}
// Build a graph with verticesPerNode vertices on each node
if (myRank == 0)
{
(cout << "Building distributed directed graph...").flush();
}
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddVertex();
}
// Add an extra vertex on the first and last processors. These
// vertices will be the source and the sink of search algorithms,
// respectively.
if (myRank == 0 || myRank == numProcs - 1)
{
graph->AddVertex();
}
// Add edges from the ith vertex on each node to the ith vertex on
// the next node (not counting the extra vertices, of course).
if (myRank < numProcs - 1)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, i),
graph->MakeDistributedId(myRank+1, i));
}
}
// Add edges from the source vertex to each of the vertices on the
// first node
if (myRank == 0)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, verticesPerNode),
graph->MakeDistributedId(myRank, i));
}
}
// Add edges from each of the vertices on the last node to the sink
// vertex.
if (myRank == numProcs - 1)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, i),
graph->MakeDistributedId(myRank, verticesPerNode));
}
}
// Synchronize so that everyone catches up
helper->Synchronize();
if (myRank == 0)
{
(cout << " done.\n").flush();
}
// Build the breadth-first search filter
vtkSmartPointer<vtkBoostBreadthFirstSearch> bfs
= vtkSmartPointer<vtkBoostBreadthFirstSearch>::New();
bfs->SetInput(graph);
bfs->SetOriginVertex(graph->MakeDistributedId(0, verticesPerNode));
// Run the breadth-first search
if (myRank == 0)
{
(cout << " Breadth-first search...").flush();
}
bfs->Update();
// Verify the results of the breadth-first search
if (myRank == 0)
{
(cout << " verifying...").flush();
}
graph = bfs->GetOutput();
int index;
vtkIntArray *distArray
= vtkIntArray::SafeDownCast(graph->GetVertexData()->GetArray("BFS", index));
assert(distArray);
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
if (distArray->GetValue(i) != myRank + 1)
{
cerr << "Value at vertex " << i << " on rank " << myRank
<< " is " << distArray->GetValue(i) << ", expected "
<< (myRank + 1) << endl;
}
assert(distArray->GetValue(i) == myRank + 1);
}
if (myRank == 0)
assert(distArray->GetValue(verticesPerNode) == 0);
if (myRank == numProcs - 1)
assert(distArray->GetValue(verticesPerNode) == numProcs + 1);
helper->Synchronize();
if (myRank == 0)
{
(cout << " done.\n").flush();
}
}
void TestUndirectedGraph()
{
// Create a new graph
vtkSmartPointer<vtkMutableUndirectedGraph> graph
= vtkSmartPointer<vtkMutableUndirectedGraph>::New();
// Create a Parallel BGL distributed graph helper
vtkSmartPointer<vtkPBGLDistributedGraphHelper> helper
= vtkSmartPointer<vtkPBGLDistributedGraphHelper>::New();
// Hook the distributed graph helper into the graph. graph will then
// be a distributed graph.
graph->SetDistributedGraphHelper(helper);
int numProcs
= graph->GetInformation()->Get(vtkDataObject::DATA_NUMBER_OF_PIECES());
int myRank
= graph->GetInformation()->Get(vtkDataObject::DATA_PIECE_NUMBER());
if (numProcs == 1)
{
cout << "Distributed-graph test run with one node; nothing to do.\n";
return;
}
// Build a graph with verticesPerNode vertices on each node
if (myRank == 0)
{
(cout << "Building distributed undirected graph...").flush();
}
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddVertex();
}
// Add an extra vertex on the first and last processors. These
// vertices will be the source and the sink of search algorithms,
// respectively.
if (myRank == 0 || myRank == numProcs - 1)
{
graph->AddVertex();
}
// Add edges from the ith vertex on each node to the ith vertex on
// the next node (not counting the extra vertices, of course).
if (myRank < numProcs - 1)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, i),
graph->MakeDistributedId(myRank+1, i));
}
}
// Add edges from the source vertex to each of the vertices on the
// first node
if (myRank == 0)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, verticesPerNode),
graph->MakeDistributedId(myRank, i));
}
}
// Add edges from each of the vertices on the last node to the sink
// vertex.
if (myRank == numProcs - 1)
{
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
graph->AddEdge(graph->MakeDistributedId(myRank, i),
graph->MakeDistributedId(myRank, verticesPerNode));
}
}
// Synchronize so that everyone catches up
helper->Synchronize();
if (myRank == 0)
{
(cout << " done.\n").flush();
}
// Build the breadth-first search filter
vtkSmartPointer<vtkBoostBreadthFirstSearch> bfs
= vtkSmartPointer<vtkBoostBreadthFirstSearch>::New();
bfs->SetInput(graph);
bfs->SetOriginVertex(graph->MakeDistributedId(0, verticesPerNode));
// Run the breadth-first search
if (myRank == 0)
{
(cout << " Breadth-first search...").flush();
}
bfs->Update();
// Verify the results of the breadth-first search
if (myRank == 0)
{
(cout << " verifying...").flush();
}
graph = bfs->GetOutput();
int index;
vtkIntArray *distArray
= vtkIntArray::SafeDownCast(graph->GetVertexData()->GetArray("BFS", index));
assert(distArray);
for (vtkIdType i = 0; i < verticesPerNode; ++i)
{
if (distArray->GetValue(i) != myRank + 1)
{
cerr << "Value at vertex " << i << " on rank " << myRank
<< " is " << distArray->GetValue(i) << ", expected "
<< (myRank + 1) << endl;
}
assert(distArray->GetValue(i) == myRank + 1);
}
if (myRank == 0)
assert(distArray->GetValue(verticesPerNode) == 0);
if (myRank == numProcs - 1)
assert(distArray->GetValue(verticesPerNode) == numProcs + 1);
helper->Synchronize();
if (myRank == 0)
{
(cout << " done.\n").flush();
}
}
int main(int argc, char** argv)
{
MPI_Init(&argc, &argv);
TestDirectedGraph();
TestUndirectedGraph();
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2016 Benjamin Glatzel
//
// 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.
// Precompiled header file
#include "stdafx.h"
#include "stdafx_editor.h"
IntrinsicEdPrefabsView::IntrinsicEdPrefabsView(QWidget* parent)
: QTreeView(parent)
{
_model = new IntrinsicEdPrefabModel();
_model->setNameFilters({"*.prefab.json"});
_model->setNameFilterDisables(false);
setModel(_model);
setRootIndex(_model->setRootPath("media/prefabs"));
// setHeaderHidden(true);
setColumnHidden(2, true);
}
IntrinsicEdPrefabsView::~IntrinsicEdPrefabsView() {}
// <-
QStringList IntrinsicEdPrefabModel::mimeTypes() const
{
return {"PrefabFilePath"};
}
QMimeData*
IntrinsicEdPrefabModel::mimeData(const QModelIndexList& indexes) const
{
QFileInfo info = fileInfo(indexes[0]);
QMimeData* mimeData = new QMimeData();
if (info.isFile())
{
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
stream << info.filePath();
mimeData->setData("PrefabFilePath", encodedData);
}
return mimeData;
}
QVariant IntrinsicEdPrefabModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::DecorationRole && index.column() == 0)
{
QFileInfo info = fileInfo(index);
if (info.isFile())
{
return IntrinsicEd::getPixmap("Prefab");
}
else if (info.isDir())
{
return IntrinsicEd::getPixmap("Folder");
}
}
return QFileSystemModel::data(index, role);
}<commit_msg>Prefabs browser tweaks<commit_after>// Copyright 2016 Benjamin Glatzel
//
// 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.
// Precompiled header file
#include "stdafx.h"
#include "stdafx_editor.h"
IntrinsicEdPrefabsView::IntrinsicEdPrefabsView(QWidget* parent)
: QTreeView(parent)
{
_model = new IntrinsicEdPrefabModel();
_model->setNameFilters({"*.prefab.json"});
_model->setNameFilterDisables(false);
setModel(_model);
setRootIndex(_model->setRootPath("media/prefabs"));
setHeaderHidden(true);
setColumnHidden(3, true);
setColumnHidden(2, true);
setColumnHidden(1, true);
}
IntrinsicEdPrefabsView::~IntrinsicEdPrefabsView() {}
// <-
QStringList IntrinsicEdPrefabModel::mimeTypes() const
{
return {"PrefabFilePath"};
}
QMimeData*
IntrinsicEdPrefabModel::mimeData(const QModelIndexList& indexes) const
{
QFileInfo info = fileInfo(indexes[0]);
QMimeData* mimeData = new QMimeData();
if (info.isFile())
{
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
stream << info.filePath();
mimeData->setData("PrefabFilePath", encodedData);
}
return mimeData;
}
QVariant IntrinsicEdPrefabModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::DecorationRole && index.column() == 0)
{
QFileInfo info = fileInfo(index);
if (info.isFile())
{
return IntrinsicEd::getPixmap("Prefab");
}
else if (info.isDir())
{
return IntrinsicEd::getPixmap("Folder");
}
}
return QFileSystemModel::data(index, role);
}<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xbf;
pchMessageStart[1] = 0xf4;
pchMessageStart[2] = 0x1a;
pchMessageStart[3] = 0xb6;
vAlertPubKey = ParseHex("");
nDefaultPort = 58273;
nRPCPort = 59273;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
const char* pszTimestamp = "ISIS terror attacks in Brussels";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1458750507, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1458750507;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 468977;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000001a7bb3214e3e1d2e4c256082b817a3c5dff5def37456ae16d7edaa508be"));
assert(genesis.hashMerkleRoot == uint256("0xa1de9df44936bd1dd483e217fa17ec1881d2caf741ca67a33f6cd6850183078c"));
vSeeds.push_back(CDNSSeedData("ionomy.com","dnsseed.ionomy.com"));
vSeeds.push_back(CDNSSeedData("ionomy.nl","main.seed.ionomy.nl"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
nLastPOWBlock = 2000;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x5f;
pchMessageStart[1] = 0xf2;
pchMessageStart[2] = 0x15;
pchMessageStart[3] = 0x30;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("");
nDefaultPort = 51002;
nRPCPort = 51003;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 72686;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x0000070638e1fb122fb31b4753a5311f3c8784604d9f6ce42e8fec96d94173b4"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,127);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Update chainparams.cpp<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xbf;
pchMessageStart[1] = 0xf4;
pchMessageStart[2] = 0x1a;
pchMessageStart[3] = 0xb6;
vAlertPubKey = ParseHex("");
nDefaultPort = 58273;
nRPCPort = 59273;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
const char* pszTimestamp = "ISIS terror attacks in Brussels";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1458750507, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1458750507;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 468977;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000001a7bb3214e3e1d2e4c256082b817a3c5dff5def37456ae16d7edaa508be"));
assert(genesis.hashMerkleRoot == uint256("0xa1de9df44936bd1dd483e217fa17ec1881d2caf741ca67a33f6cd6850183078c"));
vSeeds.push_back(CDNSSeedData("ionomy.com","dnsseed.ionomy.com"));
vSeeds.push_back(CDNSSeedData("ionomy.nl","main.seed.ionomy.nl"));
vSeeds.push_back(CDNSSeedData("ionomy.com","dnsseed2.ionomy.com"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
nLastPOWBlock = 2000;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x5f;
pchMessageStart[1] = 0xf2;
pchMessageStart[2] = 0x15;
pchMessageStart[3] = 0x30;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("");
nDefaultPort = 51002;
nRPCPort = 51003;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 72686;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x0000070638e1fb122fb31b4753a5311f3c8784604d9f6ce42e8fec96d94173b4"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,127);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/atom_api_tray.h"
#include <string>
#include "base/threading/thread_task_runner_handle.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "shell/browser/api/atom_api_menu.h"
#include "shell/browser/browser.h"
#include "shell/common/api/atom_api_native_image.h"
#include "shell/common/native_mate_converters/gfx_converter.h"
#include "shell/common/native_mate_converters/image_converter.h"
#include "shell/common/native_mate_converters/string16_converter.h"
#include "shell/common/node_includes.h"
#include "ui/gfx/image/image.h"
namespace mate {
template <>
struct Converter<electron::TrayIcon::HighlightMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::TrayIcon::HighlightMode* out) {
using HighlightMode = electron::TrayIcon::HighlightMode;
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "always") {
*out = HighlightMode::ALWAYS;
return true;
}
if (mode == "selection") {
*out = HighlightMode::SELECTION;
return true;
}
if (mode == "never") {
*out = HighlightMode::NEVER;
return true;
}
}
return false;
}
};
} // namespace mate
namespace electron {
namespace api {
Tray::Tray(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Handle<NativeImage> image)
: tray_icon_(TrayIcon::Create()) {
SetImage(isolate, image);
tray_icon_->AddObserver(this);
InitWith(isolate, wrapper);
}
Tray::~Tray() = default;
// static
mate::WrappableBase* Tray::New(mate::Handle<NativeImage> image,
mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
args->ThrowError("Cannot create Tray before app is ready");
return nullptr;
}
return new Tray(args->isolate(), args->GetThis(), image);
}
void Tray::OnClicked(const gfx::Rect& bounds,
const gfx::Point& location,
int modifiers) {
EmitWithFlags("click", modifiers, bounds, location);
}
void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) {
EmitWithFlags("double-click", modifiers, bounds);
}
void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) {
EmitWithFlags("right-click", modifiers, bounds);
}
void Tray::OnBalloonShow() {
Emit("balloon-show");
}
void Tray::OnBalloonClicked() {
Emit("balloon-click");
}
void Tray::OnBalloonClosed() {
Emit("balloon-closed");
}
void Tray::OnDrop() {
Emit("drop");
}
void Tray::OnDropFiles(const std::vector<std::string>& files) {
Emit("drop-files", files);
}
void Tray::OnDropText(const std::string& text) {
Emit("drop-text", text);
}
void Tray::OnMouseEntered(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-enter", modifiers, location);
}
void Tray::OnMouseExited(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-leave", modifiers, location);
}
void Tray::OnMouseMoved(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-move", modifiers, location);
}
void Tray::OnDragEntered() {
Emit("drag-enter");
}
void Tray::OnDragExited() {
Emit("drag-leave");
}
void Tray::OnDragEnded() {
Emit("drag-end");
}
void Tray::SetImage(v8::Isolate* isolate, mate::Handle<NativeImage> image) {
#if defined(OS_WIN)
tray_icon_->SetImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetImage(image->image());
#endif
}
void Tray::SetPressedImage(v8::Isolate* isolate,
mate::Handle<NativeImage> image) {
#if defined(OS_WIN)
tray_icon_->SetPressedImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetPressedImage(image->image());
#endif
}
void Tray::SetToolTip(const std::string& tool_tip) {
tray_icon_->SetToolTip(tool_tip);
}
void Tray::SetTitle(const std::string& title) {
#if defined(OS_MACOSX)
tray_icon_->SetTitle(title);
#endif
}
std::string Tray::GetTitle() {
#if defined(OS_MACOSX)
return tray_icon_->GetTitle();
#else
return "";
#endif
}
void Tray::SetHighlightMode(TrayIcon::HighlightMode mode) {
tray_icon_->SetHighlightMode(mode);
}
void Tray::SetIgnoreDoubleClickEvents(bool ignore) {
#if defined(OS_MACOSX)
tray_icon_->SetIgnoreDoubleClickEvents(ignore);
#endif
}
bool Tray::GetIgnoreDoubleClickEvents() {
#if defined(OS_MACOSX)
return tray_icon_->GetIgnoreDoubleClickEvents();
#else
return false;
#endif
}
void Tray::DisplayBalloon(mate::Arguments* args,
const mate::Dictionary& options) {
mate::Handle<NativeImage> icon;
options.Get("icon", &icon);
base::string16 title, content;
if (!options.Get("title", &title) || !options.Get("content", &content)) {
args->ThrowError("'title' and 'content' must be defined");
return;
}
#if defined(OS_WIN)
tray_icon_->DisplayBalloon(
icon.IsEmpty() ? NULL : icon->GetHICON(GetSystemMetrics(SM_CXSMICON)),
title, content);
#else
tray_icon_->DisplayBalloon(icon.IsEmpty() ? gfx::Image() : icon->image(),
title, content);
#endif
}
void Tray::PopUpContextMenu(mate::Arguments* args) {
mate::Handle<Menu> menu;
args->GetNext(&menu);
gfx::Point pos;
args->GetNext(&pos);
tray_icon_->PopUpContextMenu(pos, menu.IsEmpty() ? nullptr : menu->model());
}
void Tray::SetContextMenu(v8::Isolate* isolate, mate::Handle<Menu> menu) {
menu_.Reset(isolate, menu.ToV8());
tray_icon_->SetContextMenu(menu.IsEmpty() ? nullptr : menu->model());
}
gfx::Rect Tray::GetBounds() {
return tray_icon_->GetBounds();
}
// static
void Tray::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Tray"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("setImage", &Tray::SetImage)
.SetMethod("setPressedImage", &Tray::SetPressedImage)
.SetMethod("setToolTip", &Tray::SetToolTip)
.SetMethod("setTitle", &Tray::SetTitle)
.SetMethod("getTitle", &Tray::GetTitle)
.SetMethod("setHighlightMode", &Tray::SetHighlightMode)
.SetMethod("setIgnoreDoubleClickEvents",
&Tray::SetIgnoreDoubleClickEvents)
.SetMethod("getIgnoreDoubleClickEvents",
&Tray::GetIgnoreDoubleClickEvents)
.SetMethod("displayBalloon", &Tray::DisplayBalloon)
.SetMethod("popUpContextMenu", &Tray::PopUpContextMenu)
.SetMethod("setContextMenu", &Tray::SetContextMenu)
.SetMethod("getBounds", &Tray::GetBounds);
}
} // namespace api
} // namespace electron
namespace {
using electron::api::Tray;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
Tray::SetConstructor(isolate, base::BindRepeating(&Tray::New));
mate::Dictionary dict(isolate, exports);
dict.Set(
"Tray",
Tray::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_tray, Initialize)
<commit_msg>fix: tray.displayBalloon() does not work with custom icon on Windows (#19330)<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/atom_api_tray.h"
#include <string>
#include "base/threading/thread_task_runner_handle.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "shell/browser/api/atom_api_menu.h"
#include "shell/browser/browser.h"
#include "shell/common/api/atom_api_native_image.h"
#include "shell/common/native_mate_converters/gfx_converter.h"
#include "shell/common/native_mate_converters/image_converter.h"
#include "shell/common/native_mate_converters/string16_converter.h"
#include "shell/common/node_includes.h"
#include "ui/gfx/image/image.h"
namespace mate {
template <>
struct Converter<electron::TrayIcon::HighlightMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::TrayIcon::HighlightMode* out) {
using HighlightMode = electron::TrayIcon::HighlightMode;
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "always") {
*out = HighlightMode::ALWAYS;
return true;
}
if (mode == "selection") {
*out = HighlightMode::SELECTION;
return true;
}
if (mode == "never") {
*out = HighlightMode::NEVER;
return true;
}
}
return false;
}
};
} // namespace mate
namespace electron {
namespace api {
Tray::Tray(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Handle<NativeImage> image)
: tray_icon_(TrayIcon::Create()) {
SetImage(isolate, image);
tray_icon_->AddObserver(this);
InitWith(isolate, wrapper);
}
Tray::~Tray() = default;
// static
mate::WrappableBase* Tray::New(mate::Handle<NativeImage> image,
mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
args->ThrowError("Cannot create Tray before app is ready");
return nullptr;
}
return new Tray(args->isolate(), args->GetThis(), image);
}
void Tray::OnClicked(const gfx::Rect& bounds,
const gfx::Point& location,
int modifiers) {
EmitWithFlags("click", modifiers, bounds, location);
}
void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) {
EmitWithFlags("double-click", modifiers, bounds);
}
void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) {
EmitWithFlags("right-click", modifiers, bounds);
}
void Tray::OnBalloonShow() {
Emit("balloon-show");
}
void Tray::OnBalloonClicked() {
Emit("balloon-click");
}
void Tray::OnBalloonClosed() {
Emit("balloon-closed");
}
void Tray::OnDrop() {
Emit("drop");
}
void Tray::OnDropFiles(const std::vector<std::string>& files) {
Emit("drop-files", files);
}
void Tray::OnDropText(const std::string& text) {
Emit("drop-text", text);
}
void Tray::OnMouseEntered(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-enter", modifiers, location);
}
void Tray::OnMouseExited(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-leave", modifiers, location);
}
void Tray::OnMouseMoved(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-move", modifiers, location);
}
void Tray::OnDragEntered() {
Emit("drag-enter");
}
void Tray::OnDragExited() {
Emit("drag-leave");
}
void Tray::OnDragEnded() {
Emit("drag-end");
}
void Tray::SetImage(v8::Isolate* isolate, mate::Handle<NativeImage> image) {
#if defined(OS_WIN)
tray_icon_->SetImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetImage(image->image());
#endif
}
void Tray::SetPressedImage(v8::Isolate* isolate,
mate::Handle<NativeImage> image) {
#if defined(OS_WIN)
tray_icon_->SetPressedImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetPressedImage(image->image());
#endif
}
void Tray::SetToolTip(const std::string& tool_tip) {
tray_icon_->SetToolTip(tool_tip);
}
void Tray::SetTitle(const std::string& title) {
#if defined(OS_MACOSX)
tray_icon_->SetTitle(title);
#endif
}
std::string Tray::GetTitle() {
#if defined(OS_MACOSX)
return tray_icon_->GetTitle();
#else
return "";
#endif
}
void Tray::SetHighlightMode(TrayIcon::HighlightMode mode) {
tray_icon_->SetHighlightMode(mode);
}
void Tray::SetIgnoreDoubleClickEvents(bool ignore) {
#if defined(OS_MACOSX)
tray_icon_->SetIgnoreDoubleClickEvents(ignore);
#endif
}
bool Tray::GetIgnoreDoubleClickEvents() {
#if defined(OS_MACOSX)
return tray_icon_->GetIgnoreDoubleClickEvents();
#else
return false;
#endif
}
void Tray::DisplayBalloon(mate::Arguments* args,
const mate::Dictionary& options) {
mate::Handle<NativeImage> icon;
options.Get("icon", &icon);
base::string16 title, content;
if (!options.Get("title", &title) || !options.Get("content", &content)) {
args->ThrowError("'title' and 'content' must be defined");
return;
}
#if defined(OS_WIN)
tray_icon_->DisplayBalloon(
icon.IsEmpty() ? NULL : icon->GetHICON(GetSystemMetrics(SM_CXICON)),
title, content);
#else
tray_icon_->DisplayBalloon(icon.IsEmpty() ? gfx::Image() : icon->image(),
title, content);
#endif
}
void Tray::PopUpContextMenu(mate::Arguments* args) {
mate::Handle<Menu> menu;
args->GetNext(&menu);
gfx::Point pos;
args->GetNext(&pos);
tray_icon_->PopUpContextMenu(pos, menu.IsEmpty() ? nullptr : menu->model());
}
void Tray::SetContextMenu(v8::Isolate* isolate, mate::Handle<Menu> menu) {
menu_.Reset(isolate, menu.ToV8());
tray_icon_->SetContextMenu(menu.IsEmpty() ? nullptr : menu->model());
}
gfx::Rect Tray::GetBounds() {
return tray_icon_->GetBounds();
}
// static
void Tray::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Tray"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("setImage", &Tray::SetImage)
.SetMethod("setPressedImage", &Tray::SetPressedImage)
.SetMethod("setToolTip", &Tray::SetToolTip)
.SetMethod("setTitle", &Tray::SetTitle)
.SetMethod("getTitle", &Tray::GetTitle)
.SetMethod("setHighlightMode", &Tray::SetHighlightMode)
.SetMethod("setIgnoreDoubleClickEvents",
&Tray::SetIgnoreDoubleClickEvents)
.SetMethod("getIgnoreDoubleClickEvents",
&Tray::GetIgnoreDoubleClickEvents)
.SetMethod("displayBalloon", &Tray::DisplayBalloon)
.SetMethod("popUpContextMenu", &Tray::PopUpContextMenu)
.SetMethod("setContextMenu", &Tray::SetContextMenu)
.SetMethod("getBounds", &Tray::GetBounds);
}
} // namespace api
} // namespace electron
namespace {
using electron::api::Tray;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
Tray::SetConstructor(isolate, base::BindRepeating(&Tray::New));
mate::Dictionary dict(isolate, exports);
dict.Set(
"Tray",
Tray::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_tray, Initialize)
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016-2017 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "renderviewtilecallback.h"
// Standard headers.
#include <cassert>
// Boost headers.
#include <boost/shared_array.hpp>
// Maya headers.
#include <maya/MRenderView.h>
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/image/pixel.h"
#include "foundation/image/tile.h"
#include "foundation/math/scalar.h"
// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/log.h"
// appleseed.maya headers.
#include "appleseedmaya/idlejobqueue.h"
#include "appleseedmaya/utils.h"
namespace asf = foundation;
namespace asr = renderer;
namespace
{
const int MaxHighlightSize = 8;
class RenderViewTileCallback
: public renderer::ITileCallback
{
public:
RenderViewTileCallback(
const asf::AABB2i& displayWindow,
const asf::AABB2i& dataWindow,
RendererController& rendererController,
ComputationPtr& computation)
: m_displayWindow(displayWindow)
, m_dataWindow(dataWindow)
, m_rendererController(rendererController)
, m_computation(computation)
{
for(int i = 0; i < MaxHighlightSize; ++i)
{
m_highlightPixels[i].r = 1.0f;
m_highlightPixels[i].g = 1.0f;
m_highlightPixels[i].b = 1.0f;
m_highlightPixels[i].a = 1.0f;
}
}
virtual void release()
{
delete this;
}
virtual void pre_render(
const size_t x,
const size_t y,
const size_t width,
const size_t height)
{
int xmin = static_cast<int>(x);
int ymin = static_cast<int>(y);
int xmax = static_cast<int>(x + width - 1);
int ymax = static_cast<int>(y + height - 1);
if (!intersect_with_data_window(xmin, ymin, xmax, ymax))
return;
int halfWidth = (xmax - xmin + 1) / 2;
int halfHeight = (ymax - ymin + 1) / 2;
int lineSize = std::min(std::min(halfWidth, halfHeight), MaxHighlightSize - 1);
// Flip Y interval vertically (Maya is Y up).
flip_pixel_interval(displayWindowHeight(), ymin, ymax);
HighlightTile highlightJob(xmin, ymin, xmax, ymax, lineSize, m_highlightPixels, m_rendererController, m_computation);
IdleJobQueue::pushJob(highlightJob);
}
virtual void post_render(
const asr::Frame* frame)
{
const asf::CanvasProperties& frame_props = frame->image().properties();
for( size_t ty = 0; ty < frame_props.m_tile_count_y; ++ty )
for( size_t tx = 0; tx < frame_props.m_tile_count_x; ++tx )
write_tile(frame, tx, ty);
}
virtual void post_render_tile(
const asr::Frame* frame,
const size_t tile_x,
const size_t tile_y)
{
write_tile(frame, tile_x, tile_y);
}
private:
struct HighlightTile
{
HighlightTile(
const size_t xmin,
const size_t ymin,
const size_t xmax,
const size_t ymax,
const size_t lineSize,
RV_PIXEL* highlightPixels,
RendererController& rendererController,
ComputationPtr computation)
: m_xmin(static_cast<unsigned int>(xmin))
, m_ymin(static_cast<unsigned int>(ymin))
, m_xmax(static_cast<unsigned int>(xmax))
, m_ymax(static_cast<unsigned int>(ymax))
, m_lineSize(static_cast<unsigned int>(lineSize))
, m_pixels(highlightPixels)
, m_rendererController(rendererController)
, m_computation(computation)
{
}
void operator()()
{
if (m_computation->isInterruptRequested())
{
m_rendererController.set_status(RendererController::AbortRendering);
return;
}
draw_hline(m_xmin , m_xmin + m_lineSize, m_ymin);
draw_hline(m_xmax - m_lineSize, m_xmax , m_ymin);
draw_hline(m_xmin , m_xmin + m_lineSize, m_ymax);
draw_hline(m_xmax - m_lineSize, m_xmax , m_ymax);
draw_vline(m_xmin, m_ymin , m_ymin + m_lineSize);
draw_vline(m_xmin, m_ymax - m_lineSize, m_ymax );
draw_vline(m_xmax, m_ymin , m_ymin + m_lineSize);
draw_vline(m_xmax, m_ymax - m_lineSize, m_ymax );
}
void draw_hline(
const unsigned int x0,
const unsigned int x1,
const unsigned int y) const
{
MRenderView::updatePixels(x0, x1, y, y, m_pixels, true);
MRenderView::refresh(x0, x1, y, y);
}
void draw_vline(
const unsigned int x,
const unsigned int y0,
const unsigned int y1) const
{
MRenderView::updatePixels(x, x, y0, y1, m_pixels, true);
MRenderView::refresh(x, x, y0, y1);
}
const unsigned int m_xmin;
const unsigned int m_ymin;
const unsigned int m_xmax;
const unsigned int m_ymax;
const unsigned int m_lineSize;
RV_PIXEL* m_pixels;
RendererController& m_rendererController;
ComputationPtr m_computation;
};
struct WriteTileToRenderView
{
WriteTileToRenderView(
const size_t xmin,
const size_t ymin,
const size_t xmax,
const size_t ymax,
boost::shared_array<RV_PIXEL> pixels,
RendererController& rendererController,
ComputationPtr computation)
: m_xmin(static_cast<unsigned int>(xmin))
, m_ymin(static_cast<unsigned int>(ymin))
, m_xmax(static_cast<unsigned int>(xmax))
, m_ymax(static_cast<unsigned int>(ymax))
, m_pixels(pixels)
, m_rendererController(rendererController)
, m_computation(computation)
{
}
void operator()()
{
if (m_computation->isInterruptRequested())
{
m_rendererController.set_status(RendererController::AbortRendering);
return;
}
MRenderView::updatePixels(m_xmin, m_xmax, m_ymin, m_ymax, m_pixels.get(), true);
MRenderView::refresh(m_xmin, m_xmax, m_ymin, m_ymax);
}
const unsigned int m_xmin;
const unsigned int m_ymin;
const unsigned int m_xmax;
const unsigned int m_ymax;
boost::shared_array<RV_PIXEL> m_pixels;
RendererController& m_rendererController;
ComputationPtr m_computation;
};
void write_tile(
const asr::Frame* frame,
const size_t tile_x,
const size_t tile_y)
{
const foundation::Tile& tile = frame->image().tile(tile_x, tile_y);
assert(tile.get_pixel_format() == foundation::PixelFormatFloat);
assert(tile.get_channel_count() == 4);
const asf::CanvasProperties& props = frame->image().properties();
const int x0 = static_cast<int>(tile_x * props.m_tile_width);
const int y0 = static_cast<int>(tile_y * props.m_tile_height);
int xmin = x0;
int ymin = y0;
int xmax = xmin + static_cast<int>(tile.get_width()) - 1;
int ymax = ymin + static_cast<int>(tile.get_height()) - 1;
if (!intersect_with_data_window(xmin, ymin, xmax, ymax))
return;
const size_t w = xmax - xmin + 1;
const size_t h = ymax - ymin + 1;
boost::shared_array<RV_PIXEL> pixels(new RV_PIXEL[w * h]);
RV_PIXEL* p = pixels.get();
// Copy and flip the tile verticaly (Maya's renderview is y up).
for (int j = ymax; j >= ymin; --j)
{
size_t y = j - y0;
for (int i = xmin; i <= xmax; ++i)
{
const size_t x = i - x0;
p->r = tile.get_component<float>(x, y, 0);
p->g = tile.get_component<float>(x, y, 1);
p->b = tile.get_component<float>(x, y, 2);
p->a = tile.get_component<float>(x, y, 3);
p++;
}
}
flip_pixel_interval(displayWindowHeight(), ymin, ymax);
WriteTileToRenderView tileJob(xmin, ymin, xmax, ymax, pixels, m_rendererController, m_computation);
IdleJobQueue::pushJob(tileJob);
}
int displayWindowHeight() const
{
return m_displayWindow.max.y + 1;
}
bool intersect_with_data_window(
int& xmin,
int& ymin,
int& xmax,
int& ymax) const
{
xmin = std::max(m_dataWindow.min.x, xmin);
xmax = std::min(m_dataWindow.max.x, xmax);
ymin = std::max(m_dataWindow.min.y, ymin);
ymax = std::min(m_dataWindow.max.y, ymax);
if (xmax < xmin || ymax < ymin)
return false;
return true;
}
RV_PIXEL m_highlightPixels[MaxHighlightSize];
const asf::AABB2i m_displayWindow;
const asf::AABB2i m_dataWindow;
RendererController& m_rendererController;
ComputationPtr m_computation;
};
} // unnamed.
RenderViewTileCallbackFactory::RenderViewTileCallbackFactory(
RendererController& rendererController,
ComputationPtr computation)
: m_rendererController(rendererController)
, m_computation(computation)
{
}
RenderViewTileCallbackFactory::~RenderViewTileCallbackFactory()
{
MRenderView::endRender();
}
void RenderViewTileCallbackFactory::release()
{
delete this;
}
renderer::ITileCallback* RenderViewTileCallbackFactory::create()
{
return new RenderViewTileCallback(
m_displayWindow,
m_dataWindow,
m_rendererController,
m_computation);
}
void RenderViewTileCallbackFactory::renderViewStart(const renderer::Frame& frame)
{
const asf::CanvasProperties& frameProps = frame.image().properties();
const int width = static_cast<int>(frameProps.m_canvas_width);
const int height = static_cast<int>(frameProps.m_canvas_height);
m_displayWindow = asf::AABB2i(asf::Vector2i(0, 0), asf::Vector2i(width - 1, height - 1));
if (frame.has_crop_window())
{
m_dataWindow = frame.get_crop_window();
int ymin = m_dataWindow.min.y;
int ymax = m_dataWindow.max.y;
flip_pixel_interval(height, ymin, ymax);
MRenderView::startRegionRender(
static_cast<unsigned int>(width),
static_cast<unsigned int>(height),
static_cast<unsigned int>(m_dataWindow.min.x),
static_cast<unsigned int>(m_dataWindow.max.x),
static_cast<unsigned int>(ymin),
static_cast<unsigned int>(ymax),
false,
true);
}
else
{
m_dataWindow = m_displayWindow;
MRenderView::startRender(width, height, false, true);
}
}
<commit_msg>Refresh render view once instead of 8 times in tile highlighting code<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016-2017 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "renderviewtilecallback.h"
// Standard headers.
#include <cassert>
// Boost headers.
#include "boost/shared_array.hpp"
// Maya headers.
#include <maya/MRenderView.h>
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/image/pixel.h"
#include "foundation/image/tile.h"
#include "foundation/math/scalar.h"
// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/log.h"
// appleseed.maya headers.
#include "appleseedmaya/idlejobqueue.h"
#include "appleseedmaya/utils.h"
namespace asf = foundation;
namespace asr = renderer;
namespace
{
const int MaxHighlightSize = 8;
class RenderViewTileCallback
: public renderer::ITileCallback
{
public:
RenderViewTileCallback(
const asf::AABB2i& displayWindow,
const asf::AABB2i& dataWindow,
RendererController& rendererController,
ComputationPtr& computation)
: m_displayWindow(displayWindow)
, m_dataWindow(dataWindow)
, m_rendererController(rendererController)
, m_computation(computation)
{
for(int i = 0; i < MaxHighlightSize; ++i)
{
m_highlightPixels[i].r = 1.0f;
m_highlightPixels[i].g = 1.0f;
m_highlightPixels[i].b = 1.0f;
m_highlightPixels[i].a = 1.0f;
}
}
virtual void release()
{
delete this;
}
virtual void pre_render(
const size_t x,
const size_t y,
const size_t width,
const size_t height)
{
int xmin = static_cast<int>(x);
int ymin = static_cast<int>(y);
int xmax = static_cast<int>(x + width - 1);
int ymax = static_cast<int>(y + height - 1);
if (!intersect_with_data_window(xmin, ymin, xmax, ymax))
return;
int halfWidth = (xmax - xmin + 1) / 2;
int halfHeight = (ymax - ymin + 1) / 2;
int lineSize = std::min(std::min(halfWidth, halfHeight), MaxHighlightSize - 1);
// Flip Y interval vertically (Maya is Y up).
flip_pixel_interval(displayWindowHeight(), ymin, ymax);
HighlightTile highlightJob(xmin, ymin, xmax, ymax, lineSize, m_highlightPixels, m_rendererController, m_computation);
IdleJobQueue::pushJob(highlightJob);
}
virtual void post_render(
const asr::Frame* frame)
{
const asf::CanvasProperties& frame_props = frame->image().properties();
for( size_t ty = 0; ty < frame_props.m_tile_count_y; ++ty )
for( size_t tx = 0; tx < frame_props.m_tile_count_x; ++tx )
write_tile(frame, tx, ty);
}
virtual void post_render_tile(
const asr::Frame* frame,
const size_t tile_x,
const size_t tile_y)
{
write_tile(frame, tile_x, tile_y);
}
private:
struct HighlightTile
{
HighlightTile(
const size_t xmin,
const size_t ymin,
const size_t xmax,
const size_t ymax,
const size_t lineSize,
RV_PIXEL* highlightPixels,
RendererController& rendererController,
ComputationPtr computation)
: m_xmin(static_cast<unsigned int>(xmin))
, m_ymin(static_cast<unsigned int>(ymin))
, m_xmax(static_cast<unsigned int>(xmax))
, m_ymax(static_cast<unsigned int>(ymax))
, m_lineSize(static_cast<unsigned int>(lineSize))
, m_pixels(highlightPixels)
, m_rendererController(rendererController)
, m_computation(computation)
{
}
void operator()()
{
if (m_computation->isInterruptRequested())
{
m_rendererController.set_status(RendererController::AbortRendering);
return;
}
draw_hline(m_xmin , m_xmin + m_lineSize, m_ymin);
draw_hline(m_xmax - m_lineSize, m_xmax , m_ymin);
draw_hline(m_xmin , m_xmin + m_lineSize, m_ymax);
draw_hline(m_xmax - m_lineSize, m_xmax , m_ymax);
draw_vline(m_xmin, m_ymin , m_ymin + m_lineSize);
draw_vline(m_xmin, m_ymax - m_lineSize, m_ymax );
draw_vline(m_xmax, m_ymin , m_ymin + m_lineSize);
draw_vline(m_xmax, m_ymax - m_lineSize, m_ymax );
MRenderView::refresh(m_xmin, m_xmax, m_ymin, m_ymax);
}
void draw_hline(
const unsigned int x0,
const unsigned int x1,
const unsigned int y) const
{
MRenderView::updatePixels(x0, x1, y, y, m_pixels, true);
}
void draw_vline(
const unsigned int x,
const unsigned int y0,
const unsigned int y1) const
{
MRenderView::updatePixels(x, x, y0, y1, m_pixels, true);
}
const unsigned int m_xmin;
const unsigned int m_ymin;
const unsigned int m_xmax;
const unsigned int m_ymax;
const unsigned int m_lineSize;
RV_PIXEL* m_pixels;
RendererController& m_rendererController;
ComputationPtr m_computation;
};
struct WriteTileToRenderView
{
WriteTileToRenderView(
const size_t xmin,
const size_t ymin,
const size_t xmax,
const size_t ymax,
boost::shared_array<RV_PIXEL> pixels,
RendererController& rendererController,
ComputationPtr computation)
: m_xmin(static_cast<unsigned int>(xmin))
, m_ymin(static_cast<unsigned int>(ymin))
, m_xmax(static_cast<unsigned int>(xmax))
, m_ymax(static_cast<unsigned int>(ymax))
, m_pixels(pixels)
, m_rendererController(rendererController)
, m_computation(computation)
{
}
void operator()()
{
if (m_computation->isInterruptRequested())
{
m_rendererController.set_status(RendererController::AbortRendering);
return;
}
MRenderView::updatePixels(m_xmin, m_xmax, m_ymin, m_ymax, m_pixels.get(), true);
MRenderView::refresh(m_xmin, m_xmax, m_ymin, m_ymax);
}
const unsigned int m_xmin;
const unsigned int m_ymin;
const unsigned int m_xmax;
const unsigned int m_ymax;
boost::shared_array<RV_PIXEL> m_pixels;
RendererController& m_rendererController;
ComputationPtr m_computation;
};
void write_tile(
const asr::Frame* frame,
const size_t tile_x,
const size_t tile_y)
{
const foundation::Tile& tile = frame->image().tile(tile_x, tile_y);
assert(tile.get_pixel_format() == foundation::PixelFormatFloat);
assert(tile.get_channel_count() == 4);
const asf::CanvasProperties& props = frame->image().properties();
const int x0 = static_cast<int>(tile_x * props.m_tile_width);
const int y0 = static_cast<int>(tile_y * props.m_tile_height);
int xmin = x0;
int ymin = y0;
int xmax = xmin + static_cast<int>(tile.get_width()) - 1;
int ymax = ymin + static_cast<int>(tile.get_height()) - 1;
if (!intersect_with_data_window(xmin, ymin, xmax, ymax))
return;
const size_t w = xmax - xmin + 1;
const size_t h = ymax - ymin + 1;
boost::shared_array<RV_PIXEL> pixels(new RV_PIXEL[w * h]);
RV_PIXEL* p = pixels.get();
// Copy and flip the tile verticaly (Maya's renderview is y up).
for (int j = ymax; j >= ymin; --j)
{
size_t y = j - y0;
for (int i = xmin; i <= xmax; ++i)
{
const size_t x = i - x0;
p->r = tile.get_component<float>(x, y, 0);
p->g = tile.get_component<float>(x, y, 1);
p->b = tile.get_component<float>(x, y, 2);
p->a = tile.get_component<float>(x, y, 3);
p++;
}
}
flip_pixel_interval(displayWindowHeight(), ymin, ymax);
WriteTileToRenderView tileJob(xmin, ymin, xmax, ymax, pixels, m_rendererController, m_computation);
IdleJobQueue::pushJob(tileJob);
}
int displayWindowHeight() const
{
return m_displayWindow.max.y + 1;
}
bool intersect_with_data_window(
int& xmin,
int& ymin,
int& xmax,
int& ymax) const
{
xmin = std::max(m_dataWindow.min.x, xmin);
xmax = std::min(m_dataWindow.max.x, xmax);
ymin = std::max(m_dataWindow.min.y, ymin);
ymax = std::min(m_dataWindow.max.y, ymax);
if (xmax < xmin || ymax < ymin)
return false;
return true;
}
RV_PIXEL m_highlightPixels[MaxHighlightSize];
const asf::AABB2i m_displayWindow;
const asf::AABB2i m_dataWindow;
RendererController& m_rendererController;
ComputationPtr m_computation;
};
} // unnamed.
RenderViewTileCallbackFactory::RenderViewTileCallbackFactory(
RendererController& rendererController,
ComputationPtr computation)
: m_rendererController(rendererController)
, m_computation(computation)
{
}
RenderViewTileCallbackFactory::~RenderViewTileCallbackFactory()
{
MRenderView::endRender();
}
void RenderViewTileCallbackFactory::release()
{
delete this;
}
renderer::ITileCallback* RenderViewTileCallbackFactory::create()
{
return new RenderViewTileCallback(
m_displayWindow,
m_dataWindow,
m_rendererController,
m_computation);
}
void RenderViewTileCallbackFactory::renderViewStart(const renderer::Frame& frame)
{
const asf::CanvasProperties& frameProps = frame.image().properties();
const int width = static_cast<int>(frameProps.m_canvas_width);
const int height = static_cast<int>(frameProps.m_canvas_height);
m_displayWindow = asf::AABB2i(asf::Vector2i(0, 0), asf::Vector2i(width - 1, height - 1));
if (frame.has_crop_window())
{
m_dataWindow = frame.get_crop_window();
int ymin = m_dataWindow.min.y;
int ymax = m_dataWindow.max.y;
flip_pixel_interval(height, ymin, ymax);
MRenderView::startRegionRender(
static_cast<unsigned int>(width),
static_cast<unsigned int>(height),
static_cast<unsigned int>(m_dataWindow.min.x),
static_cast<unsigned int>(m_dataWindow.max.x),
static_cast<unsigned int>(ymin),
static_cast<unsigned int>(ymax),
false,
true);
}
else
{
m_dataWindow = m_displayWindow;
MRenderView::startRender(width, height, false, true);
}
}
<|endoftext|> |
<commit_before><commit_msg>Update Trie.cpp<commit_after><|endoftext|> |
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/autowiring.h>
#include <autowiring/SatCounter.h>
#include "TestFixtures/Decoration.hpp"
class AutoFilterRvalueTest :
public testing::Test
{
public:
AutoFilterRvalueTest(void) {
AutoCurrentContext()->Initiate();
}
};
TEST_F(AutoFilterRvalueTest, SimpleCallCheck) {
AutoRequired<AutoPacketFactory> factory;
// Register an r-value filter that will receive our decoration
bool called = false;
*factory += [&] (Decoration<0>&& dec) { called = true; };
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{});
ASSERT_TRUE(called) << "R-value AutoFilter was not called as expected";
}
TEST_F(AutoFilterRvalueTest, CanModifyInPlace) {
AutoRequired<AutoPacketFactory> factory;
// Register an r-value filter that will receive our decoration
*factory += [&](Decoration<0>&& dec) { dec.i = 129; };
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{292});
const Decoration<0>& dec = packet->Get<Decoration<0>>();
ASSERT_EQ(129, dec.i) << "AutoFilter was not able to modify a decoration value in-place";
}
TEST_F(AutoFilterRvalueTest, CallOrderCorrect) {
std::vector<std::pair<size_t, Decoration<0>>> observations;
AutoRequired<AutoPacketFactory> factory;
// Register a bunch of lambdas that will take observations of the decoration
for (size_t i = 0; i < 10; i++)
*factory += [&, i](Decoration<0> dec) { observations.push_back({ i, dec }); };
// This is the filter that does the modification:
*factory += [](Decoration<0>&& dec) { dec.i = 9999; };
// Kick off, verify that filters all ran in the right order:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{100});
for (const auto& observation : observations)
ASSERT_EQ(9999, observation.second.i) << "AutoFilter " << observation.first << " ran before an r-value AutoFilter on the same altitude";
}
TEST_F(AutoFilterRvalueTest, CanUseInTheChain) {
AutoRequired<AutoPacketFactory> factory;
*factory += [](Decoration<0> dec0, Decoration<1>& dec1) {
dec1.i = dec0.i;
};
// This is the filter that does the modification
*factory += [](Decoration<1>&& dec1) {
dec1.i = 999;
};
*factory += [](Decoration<1> dec1, Decoration<2>& dec2) {
dec2.i = dec1.i;
};
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{100});
const Decoration<2>& dec2 = packet->Get<Decoration<2>>();
ASSERT_EQ(999, dec2.i) << "R-value AutoFilter was not able to modify a decoration value before passing on to the next Autofilter";
}
TEST_F(AutoFilterRvalueTest, DetectMultipleModifiers) {
AutoRequired<AutoPacketFactory> factory;
*factory += [](Decoration<0>&& dec0) {
dec0.i = 999;
};
*factory += [](Decoration<1> dec1, Decoration<0>&& dec0) {
dec0.i = dec1.i;
};
*factory += [](Decoration<0> dec0) {};
ASSERT_THROW(factory->NewPacket(), autowiring_error) << "An exception should have been thrown when there are multiple r-value AutoFilter for an existing subscriber";
}
TEST_F(AutoFilterRvalueTest, DetectCycle) {
AutoRequired<AutoPacketFactory> factory;
*factory += [](Decoration<0> dec0, Decoration<1>&& dec1) {
dec1.i = dec0.i;
};
*factory += [](Decoration<1> dec1, Decoration<0>&& dec0) {
dec0.i = dec1.i;
};
ASSERT_THROW(factory->NewPacket(), autowiring_error) << "An exception should have been thrown when there is a cycle in the AutoFilter graph";
}
<commit_msg>add test for multiple r-value autofilter<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/autowiring.h>
#include <autowiring/SatCounter.h>
#include "TestFixtures/Decoration.hpp"
class AutoFilterRvalueTest :
public testing::Test
{
public:
AutoFilterRvalueTest(void) {
AutoCurrentContext()->Initiate();
}
};
TEST_F(AutoFilterRvalueTest, SimpleCallCheck) {
AutoRequired<AutoPacketFactory> factory;
// Register an r-value filter that will receive our decoration
bool called = false;
*factory += [&] (Decoration<0>&& dec) { called = true; };
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{});
ASSERT_TRUE(called) << "R-value AutoFilter was not called as expected";
}
TEST_F(AutoFilterRvalueTest, CanModifyInPlace) {
AutoRequired<AutoPacketFactory> factory;
// Register an r-value filter that will receive our decoration
*factory += [&](Decoration<0>&& dec) { dec.i = 129; };
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{292});
const Decoration<0>& dec = packet->Get<Decoration<0>>();
ASSERT_EQ(129, dec.i) << "AutoFilter was not able to modify a decoration value in-place";
}
TEST_F(AutoFilterRvalueTest, CallOrderCorrect) {
std::vector<std::pair<size_t, Decoration<0>>> observations;
AutoRequired<AutoPacketFactory> factory;
// Register a bunch of lambdas that will take observations of the decoration
for (size_t i = 0; i < 10; i++)
*factory += [&, i](Decoration<0> dec) { observations.push_back({ i, dec }); };
// This is the filter that does the modification:
*factory += [](Decoration<0>&& dec) { dec.i = 9999; };
// Kick off, verify that filters all ran in the right order:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{100});
for (const auto& observation : observations)
ASSERT_EQ(9999, observation.second.i) << "AutoFilter " << observation.first << " ran before an r-value AutoFilter on the same altitude";
}
TEST_F(AutoFilterRvalueTest, CanUseInTheChain) {
AutoRequired<AutoPacketFactory> factory;
*factory += [](Decoration<0> dec0, Decoration<1>& dec1) {
dec1.i = dec0.i;
};
// This is the filter that does the modification
*factory += [](Decoration<1>&& dec1) {
dec1.i = 999;
};
*factory += [](Decoration<1> dec1, Decoration<2>& dec2) {
dec2.i = dec1.i;
};
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>{100});
const Decoration<2>& dec2 = packet->Get<Decoration<2>>();
ASSERT_EQ(999, dec2.i) << "R-value AutoFilter was not able to modify a decoration value before passing on to the next Autofilter";
}
TEST_F(AutoFilterRvalueTest, MultipleModifiersWithSameAltitude) {
AutoRequired<AutoPacketFactory> factory;
*factory += [](Decoration<0>&& dec0) {
dec0.i = 999;
};
*factory += [](Decoration<1> dec1, Decoration<0>&& dec0) {
dec0.i = dec1.i;
};
*factory += [](Decoration<0> dec0) {};
ASSERT_THROW(factory->NewPacket(), autowiring_error) << "An exception should have been thrown when there are multiple r-value AutoFilter with the same altitude for an existing subscriber";
}
TEST_F(AutoFilterRvalueTest, MultipleModifiersWithDifferentAltitude) {
AutoRequired<AutoPacketFactory> factory;
int called = 0;
*factory += [&](Decoration<1> dec1, Decoration<0>& dec0) {
called++;
dec0.i = dec1.i;
};
*factory += [&](Decoration<0>&& dec0) {
called++;
dec0.i = 999;
};
*factory += autowiring::altitude::Lowest, [&](Decoration<0>&& dec0) {
called++;
dec0.i = 1000;
};
*factory += [&](Decoration<0> dec0) {
called++;
};
auto packet = factory->NewPacket();
packet->AddRecipient(AutoFilterDescriptor([&] (Decoration<0>&& dec0) {
called++;
dec0.i = 2000;
}, autowiring::altitude::Highest));
packet->Decorate(Decoration<1>{555});
ASSERT_EQ(5, called) << "AutoFilters was not called as expected when there are multiple R-value AutoFilter with different altitude ";
const Decoration<0>& dec0 = packet->Get<Decoration<0>>();
ASSERT_EQ(1000, dec0.i) << "AutoFilters was not called in the correct order when there are multiple R-value AutoFilter with different altitude";
}
TEST_F(AutoFilterRvalueTest, DetectCycle) {
AutoRequired<AutoPacketFactory> factory;
*factory += [](Decoration<0> dec0, Decoration<1>&& dec1) {
dec1.i = dec0.i;
};
*factory += [](Decoration<1> dec1, Decoration<0>&& dec0) {
dec0.i = dec1.i;
};
ASSERT_THROW(factory->NewPacket(), autowiring_error) << "An exception should have been thrown when there is a cycle in the AutoFilter graph";
}
<|endoftext|> |
<commit_before>/*
* esteid-browser-plugin - a browser plugin for Estonian EID card
*
* Copyright (C) 2010 Estonian Informatics Centre
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "whitelistdialog.h"
#include "debug.h"
WhitelistDialog::WhitelistDialog(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade)
: Gtk::Dialog(cobject),
m_refGlade(refGlade),
m_entry(NULL),
m_addButton(NULL),
m_editButton(NULL),
m_deleteButton(NULL),
m_okButton(NULL),
m_cancelButton(NULL)
{
// Get the Glade-instantiated widgets
m_refGlade->get_widget("entry", m_entry);
m_refGlade->get_widget("addButton", m_addButton);
m_refGlade->get_widget("editButton", m_editButton);
m_refGlade->get_widget("deleteButton", m_deleteButton);
m_refGlade->get_widget("okButton", m_okButton);
m_refGlade->get_widget("cancelButton", m_cancelButton);
// Connect buttons to their signal handlers
if (m_entry) {
m_entry->signal_changed().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_entry_changed) );
}
if (m_addButton) {
m_addButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_add) );
}
if (m_editButton) {
m_editButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_edit) );
}
if (m_deleteButton) {
m_deleteButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_delete) );
}
if (m_okButton) {
m_okButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_ok) );
}
if (m_cancelButton) {
m_cancelButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_cancel) );
}
m_addButton->set_sensitive(false);
m_editButton->set_sensitive(false);
m_deleteButton->set_sensitive(false);
// Set up treeview
m_whitelistView = getTreeView();
m_listModel->clear();
m_whitelistView->signal_row_activated().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_treeview_row_activated) );
m_whitelistView->signal_cursor_changed().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_treeview_cursor_changed) );
}
WhitelistDialog::~WhitelistDialog()
{
}
Gtk::TreeView *WhitelistDialog::getTreeView()
{
Gtk::TreeView *treeview;
Gtk::CellRendererText *renderer;
Gtk::TreeViewColumn *col0;
m_refGlade->get_widget("whitelistView", treeview);
m_listModel = Gtk::ListStore::create(m_listColumns);
m_listModel->set_sort_column(0, Gtk::SORT_ASCENDING);
treeview->set_model(m_listModel);
// Set up custom renderer to show some sites as not sensitive
renderer = new Gtk::CellRendererText();
treeview->append_column("Sites", *renderer);
col0 = treeview->get_column(0);
col0->add_attribute(*renderer, "text", 0);
col0->add_attribute(*renderer, "sensitive", 1);
col0->add_attribute(*renderer, "editable", true);
renderer->signal_edited().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_cellrenderer_edited) );
return treeview;
}
void WhitelistDialog::addSites(const std::vector<std::string> & sv)
{
std::vector<std::string>::const_iterator it;
for (it = sv.begin(); it != sv.end(); ++it)
addSite(*it);
}
void WhitelistDialog::addDefaultSites(const std::vector<std::string> & sv)
{
std::vector<std::string>::const_iterator it;
for (it = sv.begin(); it != sv.end(); ++it)
addDefaultSite(*it);
}
void WhitelistDialog::addSite(const std::string & site, bool defaultSite)
{
Gtk::TreeModel::Row row;
row = *(m_listModel->append());
row[m_listColumns.site] = site;
if (defaultSite) // Mark sites in default whitelist as not sensitive
row[m_listColumns.sensitive] = false;
else
row[m_listColumns.sensitive] = true;
}
void WhitelistDialog::addDefaultSite(const std::string & site)
{
addSite(site, true);
}
void WhitelistDialog::setEntryText(const std::string & site)
{
m_entry->set_text(site);
}
void WhitelistDialog::clear()
{
m_listModel->clear();
}
void WhitelistDialog::on_entry_changed()
{
m_addButton->set_sensitive(m_entry->get_text_length() > 0);
}
void WhitelistDialog::on_button_add()
{
ESTEID_DEBUG("add pressed\n");
addSite(m_entry->get_text());
m_entry->set_text("");
}
void WhitelistDialog::on_button_edit()
{
Gtk::TreeModel::iterator it;
Gtk::TreePath path;
ESTEID_DEBUG("edit pressed\n");
it = getCurrentSelection();
if (it) {
path = m_listModel->get_path(it);
startEditing(path);
}
}
void WhitelistDialog::on_button_delete()
{
Gtk::TreeModel::iterator it;
ESTEID_DEBUG("delete pressed\n");
it = getCurrentSelection();
if (it) {
m_listModel->erase(it);
enableDisableButtons();
}
}
void WhitelistDialog::on_button_ok()
{
ESTEID_DEBUG("ok pressed\n");
response(Gtk::RESPONSE_OK);
}
void WhitelistDialog::on_button_cancel()
{
ESTEID_DEBUG("cancel pressed\n");
response(Gtk::RESPONSE_CANCEL);
}
void WhitelistDialog::on_treeview_row_activated(const Gtk::TreeModel::Path & path, Gtk::TreeViewColumn * /* column */)
{
ESTEID_DEBUG("row doubleclicked\n");
/* FIXME: Not needed unless we are going to open
a new dialog window in here. */
}
void WhitelistDialog::on_treeview_cursor_changed()
{
ESTEID_DEBUG("row clicked\n");
enableDisableButtons();
}
void WhitelistDialog::on_cellrenderer_edited(const Glib::ustring& path_string, const Glib::ustring& new_site)
{
Gtk::TreeModel::iterator it;
Gtk::TreePath path(path_string);
ESTEID_DEBUG("finished editing\n");
// Update the model with new value
it = m_listModel->get_iter(path);
if (it) {
Gtk::TreeModel::Row row = *it;
row[m_listColumns.site] = new_site;
}
}
// Enable or disable buttons depending on what is currently selected.
void WhitelistDialog::enableDisableButtons()
{
Gtk::TreeModel::iterator it;
it = getCurrentSelection();
if (it && (*it)[m_listColumns.sensitive]) {
// Sensitive text is selected
m_editButton->set_sensitive(true);
m_deleteButton->set_sensitive(true);
} else {
// Either nothing or non-sensitive text is selected
m_editButton->set_sensitive(false);
m_deleteButton->set_sensitive(false);
}
}
Gtk::TreeModel::iterator WhitelistDialog::getCurrentSelection()
{
return m_whitelistView->get_selection()->get_selected();
}
void WhitelistDialog::startEditing(Gtk::TreePath& path)
{
Gtk::TreeViewColumn *col0 = m_whitelistView->get_column(0);
bool start_editing = true;
m_whitelistView->set_cursor(path, *col0, start_editing);
}
std::vector<std::string> WhitelistDialog::getWhitelist()
{
std::vector<std::string> ret;
Gtk::TreeModel::iterator it;
for (it = m_listModel->children().begin(); it != m_listModel->children().end(); ++it) {
Gtk::TreeModel::Row row = *it;
// Return sites that are user set and skip default (read-only) values.
if (row[m_listColumns.sensitive]) {
ret.push_back(row[m_listColumns.site]);
}
}
return ret;
}
<commit_msg>esteid-browser-plugin: mark WhitelistDialog reponsible for deleting CellRenderer<commit_after>/*
* esteid-browser-plugin - a browser plugin for Estonian EID card
*
* Copyright (C) 2010 Estonian Informatics Centre
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "whitelistdialog.h"
#include "debug.h"
WhitelistDialog::WhitelistDialog(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade)
: Gtk::Dialog(cobject),
m_refGlade(refGlade),
m_entry(NULL),
m_addButton(NULL),
m_editButton(NULL),
m_deleteButton(NULL),
m_okButton(NULL),
m_cancelButton(NULL)
{
// Get the Glade-instantiated widgets
m_refGlade->get_widget("entry", m_entry);
m_refGlade->get_widget("addButton", m_addButton);
m_refGlade->get_widget("editButton", m_editButton);
m_refGlade->get_widget("deleteButton", m_deleteButton);
m_refGlade->get_widget("okButton", m_okButton);
m_refGlade->get_widget("cancelButton", m_cancelButton);
// Connect buttons to their signal handlers
if (m_entry) {
m_entry->signal_changed().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_entry_changed) );
}
if (m_addButton) {
m_addButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_add) );
}
if (m_editButton) {
m_editButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_edit) );
}
if (m_deleteButton) {
m_deleteButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_delete) );
}
if (m_okButton) {
m_okButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_ok) );
}
if (m_cancelButton) {
m_cancelButton->signal_clicked().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_button_cancel) );
}
m_addButton->set_sensitive(false);
m_editButton->set_sensitive(false);
m_deleteButton->set_sensitive(false);
// Set up treeview
m_whitelistView = getTreeView();
m_listModel->clear();
m_whitelistView->signal_row_activated().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_treeview_row_activated) );
m_whitelistView->signal_cursor_changed().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_treeview_cursor_changed) );
}
WhitelistDialog::~WhitelistDialog()
{
}
Gtk::TreeView *WhitelistDialog::getTreeView()
{
Gtk::TreeView *treeview;
Gtk::CellRendererText *renderer;
Gtk::TreeViewColumn *col0;
m_refGlade->get_widget("whitelistView", treeview);
m_listModel = Gtk::ListStore::create(m_listColumns);
m_listModel->set_sort_column(0, Gtk::SORT_ASCENDING);
treeview->set_model(m_listModel);
// Set up custom renderer to show some sites as not sensitive
renderer = manage(new Gtk::CellRendererText());
treeview->append_column("Sites", *renderer);
col0 = treeview->get_column(0);
col0->add_attribute(*renderer, "text", 0);
col0->add_attribute(*renderer, "sensitive", 1);
col0->add_attribute(*renderer, "editable", true);
renderer->signal_edited().connect( sigc::mem_fun(*this,
&WhitelistDialog::on_cellrenderer_edited) );
return treeview;
}
void WhitelistDialog::addSites(const std::vector<std::string> & sv)
{
std::vector<std::string>::const_iterator it;
for (it = sv.begin(); it != sv.end(); ++it)
addSite(*it);
}
void WhitelistDialog::addDefaultSites(const std::vector<std::string> & sv)
{
std::vector<std::string>::const_iterator it;
for (it = sv.begin(); it != sv.end(); ++it)
addDefaultSite(*it);
}
void WhitelistDialog::addSite(const std::string & site, bool defaultSite)
{
Gtk::TreeModel::Row row;
row = *(m_listModel->append());
row[m_listColumns.site] = site;
if (defaultSite) // Mark sites in default whitelist as not sensitive
row[m_listColumns.sensitive] = false;
else
row[m_listColumns.sensitive] = true;
}
void WhitelistDialog::addDefaultSite(const std::string & site)
{
addSite(site, true);
}
void WhitelistDialog::setEntryText(const std::string & site)
{
m_entry->set_text(site);
}
void WhitelistDialog::clear()
{
m_listModel->clear();
}
void WhitelistDialog::on_entry_changed()
{
m_addButton->set_sensitive(m_entry->get_text_length() > 0);
}
void WhitelistDialog::on_button_add()
{
ESTEID_DEBUG("add pressed\n");
addSite(m_entry->get_text());
m_entry->set_text("");
}
void WhitelistDialog::on_button_edit()
{
Gtk::TreeModel::iterator it;
Gtk::TreePath path;
ESTEID_DEBUG("edit pressed\n");
it = getCurrentSelection();
if (it) {
path = m_listModel->get_path(it);
startEditing(path);
}
}
void WhitelistDialog::on_button_delete()
{
Gtk::TreeModel::iterator it;
ESTEID_DEBUG("delete pressed\n");
it = getCurrentSelection();
if (it) {
m_listModel->erase(it);
enableDisableButtons();
}
}
void WhitelistDialog::on_button_ok()
{
ESTEID_DEBUG("ok pressed\n");
response(Gtk::RESPONSE_OK);
}
void WhitelistDialog::on_button_cancel()
{
ESTEID_DEBUG("cancel pressed\n");
response(Gtk::RESPONSE_CANCEL);
}
void WhitelistDialog::on_treeview_row_activated(const Gtk::TreeModel::Path & path, Gtk::TreeViewColumn * /* column */)
{
ESTEID_DEBUG("row doubleclicked\n");
/* FIXME: Not needed unless we are going to open
a new dialog window in here. */
}
void WhitelistDialog::on_treeview_cursor_changed()
{
ESTEID_DEBUG("row clicked\n");
enableDisableButtons();
}
void WhitelistDialog::on_cellrenderer_edited(const Glib::ustring& path_string, const Glib::ustring& new_site)
{
Gtk::TreeModel::iterator it;
Gtk::TreePath path(path_string);
ESTEID_DEBUG("finished editing\n");
// Update the model with new value
it = m_listModel->get_iter(path);
if (it) {
Gtk::TreeModel::Row row = *it;
row[m_listColumns.site] = new_site;
}
}
// Enable or disable buttons depending on what is currently selected.
void WhitelistDialog::enableDisableButtons()
{
Gtk::TreeModel::iterator it;
it = getCurrentSelection();
if (it && (*it)[m_listColumns.sensitive]) {
// Sensitive text is selected
m_editButton->set_sensitive(true);
m_deleteButton->set_sensitive(true);
} else {
// Either nothing or non-sensitive text is selected
m_editButton->set_sensitive(false);
m_deleteButton->set_sensitive(false);
}
}
Gtk::TreeModel::iterator WhitelistDialog::getCurrentSelection()
{
return m_whitelistView->get_selection()->get_selected();
}
void WhitelistDialog::startEditing(Gtk::TreePath& path)
{
Gtk::TreeViewColumn *col0 = m_whitelistView->get_column(0);
bool start_editing = true;
m_whitelistView->set_cursor(path, *col0, start_editing);
}
std::vector<std::string> WhitelistDialog::getWhitelist()
{
std::vector<std::string> ret;
Gtk::TreeModel::iterator it;
for (it = m_listModel->children().begin(); it != m_listModel->children().end(); ++it) {
Gtk::TreeModel::Row row = *it;
// Return sites that are user set and skip default (read-only) values.
if (row[m_listColumns.sensitive]) {
ret.push_back(row[m_listColumns.site]);
}
}
return ret;
}
<|endoftext|> |
<commit_before>//
// user.hpp
// ********
//
// Copyright (c) 2020 Sharon Fox (sharon at xandium dot io)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//
#pragma once
#include "aegis/config.hpp"
#include "aegis/utility.hpp"
#if !defined(AEGIS_DISABLE_ALL_CACHE)
#include "aegis/snowflake.hpp"
#include "aegis/gateway/objects/presence.hpp"
#include "aegis/fwd.hpp"
#include <nlohmann/json.hpp>
#include <string>
#include <queue>
#include <memory>
#include <set>
#include <shared_mutex>
namespace aegis
{
#if (AEGIS_HAS_STD_SHARED_MUTEX == 1)
using shared_mutex = std::shared_mutex;
#else
using shared_mutex = std::shared_timed_mutex;
#endif
using json = nlohmann::json;
/// Stores user-specific and guild-specific attributes of users
class user
{
public:
using presence = aegis::gateway::objects::presence;
explicit user(snowflake id) : _member_id(id) {}
/// Member owned guild information
struct guild_info
{
guild_info(snowflake _id) : id(_id) {};
snowflake id;/**< Snowflake of the guild for this data */
std::vector<snowflake> roles;
lib::optional<std::string> nickname;/**< Nickname of the user in this guild */
uint64_t joined_at = 0;/**< Unix timestamp of when member joined this guild */
bool deaf = false;/**< Whether member is deafened in a voice channel */
bool mute = false;/**< Whether member is muted in a voice channel */
};
/// Get the nickname of this user
/**
* @param guild_id The snowflake for the guild to check if nickname is set
* @returns string of the nickname or empty if no nickname is set
*/
AEGIS_DECL std::string get_name(snowflake guild_id) noexcept;
/// Get the nickname of this user
/**
* @returns string of the username
*/
std::string get_username() const noexcept
{
std::shared_lock<shared_mutex> l(_m);
std::string _username = _name;
return std::move(_username);
}
/// Get the discriminator of this user
/**
* @returns string of the discriminator
*/
uint16_t get_discriminator() const noexcept
{
return _discriminator;
}
/// Get the avatar hash of this user
/**
* @returns string of the avatar hash
*/
std::string get_avatar() const noexcept
{
std::shared_lock<shared_mutex> l(_m);
std::string t_avatar = _avatar;
return std::move(t_avatar);
}
/// Check whether user is a bot
/**
* @returns bool of bot status
*/
bool is_bot() const noexcept
{
return _is_bot;
}
/// Get the status of multi factor authentication
/**
* @returns bool of mfa status
*/
bool is_mfa_enabled() const noexcept
{
return _mfa_enabled;
}
/// Builds a mention for this user
/**
* @returns string of member mention
*/
AEGIS_DECL std::string get_mention() const noexcept;
/// Get the member owned guild information object
/**
* @param guild_id The snowflake for the guild
* @returns Pointer to the member owned guild information object
*/
AEGIS_DECL guild_info & get_guild_info(snowflake guild_id) noexcept;
AEGIS_DECL guild_info & get_guild_info_nolock(snowflake guild_id) noexcept;
AEGIS_DECL guild_info * get_guild_info_nocreate(snowflake guild_id) const noexcept;
/// Get the full name (username\#discriminator) of this user
/**
* @returns string of the full username and discriminator
*/
AEGIS_DECL std::string get_full_name() const noexcept;
/// Get the snowflake of this user
/**
* @returns snowflake of the user
*/
snowflake get_id() const noexcept
{
return _member_id;
}
/// Whether the DM channel id for this user has been cached yet
/**
* @returns bool
*/
bool has_dm() const noexcept
{
return !!get_dm_id();
}
/// Get the DM channel associated with this user
/// DM channels are obtained when a DM is sent
/**
* @returns snowflake of DM channel
*/
snowflake get_dm_id() const noexcept
{
return _dm_id;
}
/// Set the DM channel id for the user
/**
* @param _id Snowflake of DM channel for this user
*/
void set_dm_id(snowflake _id) noexcept
{
_dm_id = _id;
}
///
/**
* @returns shared_mutex The mutex for the user
*/
shared_mutex & mtx() noexcept
{
return _m;
}
private:
friend class core;
friend class guild;
friend class gateway::objects::message;
AEGIS_DECL void _load_data(gateway::objects::user mbr);
snowflake _member_id = 0;
snowflake _dm_id = 0;
presence::user_status _status = presence::user_status::Offline; /**< Member _status */
std::string _name; /**< Username of member */
uint16_t _discriminator = 0; /**< 4 digit discriminator (1-9999) */
std::string _avatar; /**< Hash of member avatar */
bool _is_bot = false; /**< true if member is a bot */
bool _mfa_enabled = false; /**< true if member has Two-factor authentication enabled */
std::vector<std::unique_ptr<guild_info>> guilds; /**< Vector of snowflakes to member owned guild information */
mutable shared_mutex _m;
/// requires the caller to handle locking
AEGIS_DECL void _load(guild * _guild, const json & obj, shards::shard * _shard, bool self_add = true);
/// does not lock the member object
AEGIS_DECL void _load_nolock(guild * _guild, const json & obj, shards::shard * _shard, bool self_add = true, bool guild_lock = true);
/// requires the caller to handle locking
AEGIS_DECL guild_info & _join(snowflake guild_id);
/// requires the caller to handle locking
AEGIS_DECL guild_info & _join_nolock(snowflake guild_id);
/// remove this member from the specified guild
void leave(snowflake guild_id)
{
std::unique_lock<shared_mutex> l(mtx());
guilds.erase(std::find_if(std::begin(guilds), std::end(guilds), [&guild_id](const std::unique_ptr<guild_info> & gi)
{
if (gi->id == guild_id)
return true;
return false;
}));
}
};
}
#else
namespace aegis
{
class user
{
public:
enum member_status
{
Offline,
Online,
Idle,
DoNotDisturb
};
};
}
#endif
<commit_msg>Fix typo in user.hpp (#53)<commit_after>//
// user.hpp
// ********
//
// Copyright (c) 2020 Sharon Fox (sharon at xandium dot io)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//
#pragma once
#include "aegis/config.hpp"
#include "aegis/utility.hpp"
#if !defined(AEGIS_DISABLE_ALL_CACHE)
#include "aegis/snowflake.hpp"
#include "aegis/gateway/objects/presence.hpp"
#include "aegis/fwd.hpp"
#include <nlohmann/json.hpp>
#include <string>
#include <queue>
#include <memory>
#include <set>
#include <shared_mutex>
namespace aegis
{
#if (AEGIS_HAS_STD_SHARED_MUTEX == 1)
using shared_mutex = std::shared_mutex;
#else
using shared_mutex = std::shared_timed_mutex;
#endif
using json = nlohmann::json;
/// Stores user-specific and guild-specific attributes of users
class user
{
public:
using presence = aegis::gateway::objects::presence;
explicit user(snowflake id) : _member_id(id) {}
/// Member owned guild information
struct guild_info
{
guild_info(snowflake _id) : id(_id) {};
snowflake id;/**< Snowflake of the guild for this data */
std::vector<snowflake> roles;
lib::optional<std::string> nickname;/**< Nickname of the user in this guild */
uint64_t joined_at = 0;/**< Unix timestamp of when member joined this guild */
bool deaf = false;/**< Whether member is deafened in a voice channel */
bool mute = false;/**< Whether member is muted in a voice channel */
};
/// Get the nickname of this user
/**
* @param guild_id The snowflake for the guild to check if nickname is set
* @returns string of the nickname or empty if no nickname is set
*/
AEGIS_DECL std::string get_name(snowflake guild_id) noexcept;
/// Get the username of this user
/**
* @returns string of the username
*/
std::string get_username() const noexcept
{
std::shared_lock<shared_mutex> l(_m);
std::string _username = _name;
return std::move(_username);
}
/// Get the discriminator of this user
/**
* @returns string of the discriminator
*/
uint16_t get_discriminator() const noexcept
{
return _discriminator;
}
/// Get the avatar hash of this user
/**
* @returns string of the avatar hash
*/
std::string get_avatar() const noexcept
{
std::shared_lock<shared_mutex> l(_m);
std::string t_avatar = _avatar;
return std::move(t_avatar);
}
/// Check whether user is a bot
/**
* @returns bool of bot status
*/
bool is_bot() const noexcept
{
return _is_bot;
}
/// Get the status of multi factor authentication
/**
* @returns bool of mfa status
*/
bool is_mfa_enabled() const noexcept
{
return _mfa_enabled;
}
/// Builds a mention for this user
/**
* @returns string of member mention
*/
AEGIS_DECL std::string get_mention() const noexcept;
/// Get the member owned guild information object
/**
* @param guild_id The snowflake for the guild
* @returns Pointer to the member owned guild information object
*/
AEGIS_DECL guild_info & get_guild_info(snowflake guild_id) noexcept;
AEGIS_DECL guild_info & get_guild_info_nolock(snowflake guild_id) noexcept;
AEGIS_DECL guild_info * get_guild_info_nocreate(snowflake guild_id) const noexcept;
/// Get the full name (username\#discriminator) of this user
/**
* @returns string of the full username and discriminator
*/
AEGIS_DECL std::string get_full_name() const noexcept;
/// Get the snowflake of this user
/**
* @returns snowflake of the user
*/
snowflake get_id() const noexcept
{
return _member_id;
}
/// Whether the DM channel id for this user has been cached yet
/**
* @returns bool
*/
bool has_dm() const noexcept
{
return !!get_dm_id();
}
/// Get the DM channel associated with this user
/// DM channels are obtained when a DM is sent
/**
* @returns snowflake of DM channel
*/
snowflake get_dm_id() const noexcept
{
return _dm_id;
}
/// Set the DM channel id for the user
/**
* @param _id Snowflake of DM channel for this user
*/
void set_dm_id(snowflake _id) noexcept
{
_dm_id = _id;
}
///
/**
* @returns shared_mutex The mutex for the user
*/
shared_mutex & mtx() noexcept
{
return _m;
}
private:
friend class core;
friend class guild;
friend class gateway::objects::message;
AEGIS_DECL void _load_data(gateway::objects::user mbr);
snowflake _member_id = 0;
snowflake _dm_id = 0;
presence::user_status _status = presence::user_status::Offline; /**< Member _status */
std::string _name; /**< Username of member */
uint16_t _discriminator = 0; /**< 4 digit discriminator (1-9999) */
std::string _avatar; /**< Hash of member avatar */
bool _is_bot = false; /**< true if member is a bot */
bool _mfa_enabled = false; /**< true if member has Two-factor authentication enabled */
std::vector<std::unique_ptr<guild_info>> guilds; /**< Vector of snowflakes to member owned guild information */
mutable shared_mutex _m;
/// requires the caller to handle locking
AEGIS_DECL void _load(guild * _guild, const json & obj, shards::shard * _shard, bool self_add = true);
/// does not lock the member object
AEGIS_DECL void _load_nolock(guild * _guild, const json & obj, shards::shard * _shard, bool self_add = true, bool guild_lock = true);
/// requires the caller to handle locking
AEGIS_DECL guild_info & _join(snowflake guild_id);
/// requires the caller to handle locking
AEGIS_DECL guild_info & _join_nolock(snowflake guild_id);
/// remove this member from the specified guild
void leave(snowflake guild_id)
{
std::unique_lock<shared_mutex> l(mtx());
guilds.erase(std::find_if(std::begin(guilds), std::end(guilds), [&guild_id](const std::unique_ptr<guild_info> & gi)
{
if (gi->id == guild_id)
return true;
return false;
}));
}
};
}
#else
namespace aegis
{
class user
{
public:
enum member_status
{
Offline,
Online,
Idle,
DoNotDisturb
};
};
}
#endif
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <iostream>
#include <sstream>
#include <tinyxml/tinyxml.h>
int main(int argc, char *argv[])
{
if (argc < 3)
{
std::cout << "Usage: CombinePartitions [nproc] [outfile]"
<< std::endl;
std::cout << " [nproc] = Number of partitions" << std::endl;
std::cout << " [outfile] = Target output filename" << std::endl;
exit(1);
}
TiXmlDocument docOutput;
TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "utf-8", "");
docOutput.LinkEndChild(decl);
TiXmlElement *master = new TiXmlElement("NEKTAR");
for (int n = 0; n < atoi(argv[1]); ++n)
{
std::string basename = argv[2];
std::string extension = argv[2];
basename = basename.substr(0, basename.find_last_of("."));
extension = extension.substr(extension.find_last_of(".") + 1);
std::stringstream filename;
filename << basename << "_P" << n << "." << extension;
TiXmlDocument docInput;
if (!docInput.LoadFile(filename.str()))
{
std::cerr << "Unable to open file '" << filename.str() << "'." << std::endl;
exit(1);
}
TiXmlElement *nektar = docInput.FirstChildElement("NEKTAR");
// load up root processor's meta data
if(n == 0 && nektar->FirstChildElement("Metadata"))
{
TiXmlElement *metadata = nektar->FirstChildElement("Metadata");
if(metadata)
{
master->LinkEndChild(new TiXmlElement(*metadata));
}
}
// load the elements from seperate files.
TiXmlElement *elements = nektar->FirstChildElement("ELEMENTS");
while (elements)
{
master->LinkEndChild(new TiXmlElement(*elements));
elements = elements->NextSiblingElement();
}
}
docOutput.LinkEndChild(master);
if (!docOutput.SaveFile(argv[2]))
{
std::cerr << "Unable to write file '" << argv[1] << "'." << std::endl;
}
exit(0);
}
<commit_msg>Update to allow for partiion deleting<commit_after>#include <cstdlib>
#include <iostream>
#include <sstream>
#include <tinyxml/tinyxml.h>
int main(int argc, char *argv[])
{
bool DeleteFiles = false;
if (argc < 3)
{
std::cout << "Usage: CombinePartitions [DeleteFile] nproc outfile"
<< std::endl;
std::cout << " [DeleteFiles] = Delete partiion files (optional)" << std::endl;
std::cout << " nproc = Number of partitions" << std::endl;
std::cout << " outfile = Target output filename" << std::endl;
exit(1);
}
if(argc == 4)
{
DeleteFiles = true;
}
TiXmlDocument docOutput;
TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "utf-8", "");
docOutput.LinkEndChild(decl);
TiXmlElement *master = new TiXmlElement("NEKTAR");
for (int n = 0; n < atoi(argv[argc-2]); ++n)
{
std::string basename = argv[argc-1];
std::string extension = argv[argc-1];
basename = basename.substr(0, basename.find_last_of("."));
extension = extension.substr(extension.find_last_of(".") + 1);
std::stringstream filename;
filename << basename << "_P" << n << "." << extension;
TiXmlDocument docInput;
if (!docInput.LoadFile(filename.str()))
{
std::cerr << "Unable to open file '" << filename.str() << "'." << std::endl;
exit(1);
}
TiXmlElement *nektar = docInput.FirstChildElement("NEKTAR");
// load up root processor's meta data
if(n == 0 && nektar->FirstChildElement("Metadata"))
{
TiXmlElement *metadata = nektar->FirstChildElement("Metadata");
if(metadata)
{
master->LinkEndChild(new TiXmlElement(*metadata));
}
}
// load the elements from seperate files.
TiXmlElement *elements = nektar->FirstChildElement("ELEMENTS");
while (elements)
{
master->LinkEndChild(new TiXmlElement(*elements));
elements = elements->NextSiblingElement();
}
}
docOutput.LinkEndChild(master);
if (!docOutput.SaveFile(argv[argc-1]))
{
std::cerr << "Unable to write file '" << argv[argc-2] << "'." << std::endl;
}
else
{
if(DeleteFiles)
{
for (int n = 0; n < atoi(argv[argc-2]); ++n)
{
std::string basename = argv[argc-1];
std::string extension = argv[argc-1];
basename = basename.substr(0, basename.find_last_of("."));
extension = extension.substr(extension.find_last_of(".") + 1);
std::stringstream filename;
filename << basename << "_P" << n << "." << extension;
std::string deloutput = "rm -rf ";
deloutput = deloutput + filename.str();
system(deloutput.c_str());
}
}
}
exit(0);
}
<|endoftext|> |
<commit_before>
//-------------------------------------
#ifdef SRTK_HAS_CXX11_STATIC_ASSERT
int main(void)
{
static_assert( true, "this should compile with C++0x static_assert keyword support");
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_FUNCTIONAL
struct C {
void func();
};
int main(void)
{
int *x = nullptr;
char *c = nullptr;
void (C::*pmf)() = nullptr;
if (nullptr==c) {}
if (nullptr==pmf) {}
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_FUNCTIONAL
#include <functional>
void f(int,int) {}
int main(void)
{
std::function<void(int,int)> g(f);
using namespace std::placeholders;
std::function<void(int)> h = std::bind(g,0,_1);
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_ALIAS_TEMPLATE
template<class T>
using ptr = T*;
int main(void)
{
ptr<int> x;
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_UNIQUE_PTR
#include <memory>
int main(void) {
std::unique_ptr<int> p1(new int);
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_FUNCTIONAL
#ifdef HAS_TR1_SUB_INCLUDE
#include <tr1/functional>
#else
#include <functional>
#endif
void f(int,int) {}
int main(void)
{
std::tr1::function<void(int,int)> g(f);
using namespace std::tr1::placeholders;
std::tr1::function<void(int)> h = std::tr1::bind(g,0,_1);
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_TYPE_TRAITS
#include <type_traits>
int main(void)
{
std::integral_constant<int, 0> a;
std::true_type b;
std::false_type c;
std::is_same<int,int>::type d;
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_TYPE_TRAITS
#ifdef HAS_TR1_SUB_INCLUDE
#include <tr1/type_traits>
#else
#include <type_traits>
#endif
int main(void)
{
std::tr1::integral_constant<int, 0> a;
std::tr1::true_type b;
std::tr1::false_type c;
std::tr1::is_same<int,int>::type d;
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_UNORDERED_MAP
#include <unordered_map>
int main(void)
{
// On OSX with gcc 4.0, there is an internal const correctness issue
// in the following.
std::unordered_map<int,int> s;
const std::unordered_map<int, int> &c_ref = s;
c_ref.find(1); // Problem is here.
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_UNORDERED_MAP
#ifdef HAS_TR1_SUB_INCLUDE
#include <tr1/unordered_map>
#else
#include <unordered_map>
#endif
int main(void)
{
// On OSX with gcc 4.0, there is an internal const correctness issue
// in the following.
std::tr1::unordered_map<int,int> s;
const std::tr1::unordered_map<int, int> &c_ref = s;
c_ref.find(1); // Problem is here.
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_SUB_INCLUDE
#include <tr1/functional>
#include <tr1/type_traits>
#include <tr1/unordered_map>
int main(void) { return 0; }
#endif
<commit_msg>FIX: Wrong copy pasting in the upgrade prevented compilation<commit_after>
//-------------------------------------
#ifdef SRTK_HAS_CXX11_STATIC_ASSERT
int main(void)
{
static_assert( true, "this should compile with C++0x static_assert keyword support");
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_NULLPTR
struct C {
void func();
};
int main(void)
{
int *x = nullptr;
char *c = nullptr;
void (C::*pmf)() = nullptr;
if (nullptr==c) {}
if (nullptr==pmf) {}
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_FUNCTIONAL
#include <functional>
void f(int,int) {}
int main(void)
{
std::function<void(int,int)> g(f);
using namespace std::placeholders;
std::function<void(int)> h = std::bind(g,0,_1);
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_ALIAS_TEMPLATE
template<class T>
using ptr = T*;
int main(void)
{
ptr<int> x;
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_UNIQUE_PTR
#include <memory>
int main(void) {
std::unique_ptr<int> p1(new int);
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_FUNCTIONAL
#ifdef HAS_TR1_SUB_INCLUDE
#include <tr1/functional>
#else
#include <functional>
#endif
void f(int,int) {}
int main(void)
{
std::tr1::function<void(int,int)> g(f);
using namespace std::tr1::placeholders;
std::tr1::function<void(int)> h = std::tr1::bind(g,0,_1);
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_TYPE_TRAITS
#include <type_traits>
int main(void)
{
std::integral_constant<int, 0> a;
std::true_type b;
std::false_type c;
std::is_same<int,int>::type d;
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_TYPE_TRAITS
#ifdef HAS_TR1_SUB_INCLUDE
#include <tr1/type_traits>
#else
#include <type_traits>
#endif
int main(void)
{
std::tr1::integral_constant<int, 0> a;
std::tr1::true_type b;
std::tr1::false_type c;
std::tr1::is_same<int,int>::type d;
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_CXX11_UNORDERED_MAP
#include <unordered_map>
int main(void)
{
// On OSX with gcc 4.0, there is an internal const correctness issue
// in the following.
std::unordered_map<int,int> s;
const std::unordered_map<int, int> &c_ref = s;
c_ref.find(1); // Problem is here.
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_UNORDERED_MAP
#ifdef HAS_TR1_SUB_INCLUDE
#include <tr1/unordered_map>
#else
#include <unordered_map>
#endif
int main(void)
{
// On OSX with gcc 4.0, there is an internal const correctness issue
// in the following.
std::tr1::unordered_map<int,int> s;
const std::tr1::unordered_map<int, int> &c_ref = s;
c_ref.find(1); // Problem is here.
return 0;
}
#endif
//-------------------------------------
#ifdef SRTK_HAS_TR1_SUB_INCLUDE
#include <tr1/functional>
#include <tr1/type_traits>
#include <tr1/unordered_map>
int main(void) { return 0; }
#endif
<|endoftext|> |
<commit_before>///
/// @file calculator.hpp
/// @brief calculator::eval(const std::string&) evaluates an integer
/// arithmetic expression and returns the result. If an error
/// occurs a calculator::error exception is thrown.
/// <https://github.com/kimwalisch/calculator>
/// @author Kim Walisch, <kim.walisch@gmail.com>
/// @copyright Copyright (C) 2013-2018 Kim Walisch
/// @license BSD 2-Clause, https://opensource.org/licenses/BSD-2-Clause
/// @version 1.3 patched: `^' is raise to power instead of XOR.
///
/// == Supported operators ==
///
/// OPERATOR NAME ASSOCIATIVITY PRECEDENCE
///
/// | Bitwise Inclusive OR Left 4
/// & Bitwise AND Left 6
/// << Shift Left Left 9
/// >> Shift Right Left 9
/// + Addition Left 10
/// - Subtraction Left 10
/// * Multiplication Left 20
/// / Division Left 20
/// % Modulo Left 20
/// ^, ** Raise to power Right 30
/// e, E Scientific notation Right 40
/// ~ Unary complement Left 99
///
/// The operator precedence has been set according to (uses the C and
/// C++ operator precedence): https://en.wikipedia.org/wiki/Order_of_operations
/// Operators with higher precedence are evaluated before operators
/// with relatively lower precedence. Unary operators are set to have
/// the highest precedence, this is not strictly correct for the power
/// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell,
/// Microsoft Excel, GNU bc, ...) use the same convention.
///
/// == Examples of valid expressions ==
///
/// "65536 >> 15" = 2
/// "2**16" = 65536
/// "(0 + 0xDf234 - 1000)*3/2%999" = 828
/// "-(2**2**2**2)" = -65536
/// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817
/// "(2**16) + (1 << 16) >> 0X5" = 4096
/// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221
///
/// == About the algorithm used ==
///
/// calculator::eval(std::string&) relies on the ExpressionParser
/// class which is a simple C++ operator precedence parser with infix
/// notation for integer arithmetic expressions.
/// ExpressionParser has its roots in a JavaScript parser published
/// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961
/// The same author has also published an article about his operator
/// precedence algorithm at PerlMonks:
/// http://www.perlmonks.org/?node_id=554516
///
#ifndef CALCULATOR_HPP
#define CALCULATOR_HPP
#include <stdexcept>
#include <string>
#include <sstream>
#include <stack>
#include <cstddef>
#include <cctype>
namespace calculator
{
/// calculator::eval() throws a calculator::error if it fails
/// to evaluate the expression string.
///
class error : public std::runtime_error
{
public:
error(const std::string& expr, const std::string& message)
: std::runtime_error(message),
expr_(expr)
{ }
#if __cplusplus >= 201103L || \
(defined(_MSC_VER) && _MSC_VER >= 1800)
~error() { }
#else
~error() throw() { }
#endif
std::string expression() const
{
return expr_;
}
private:
std::string expr_;
};
template <typename T>
class ExpressionParser
{
public:
/// Evaluate an integer arithmetic expression and return its result.
/// @throw error if parsing fails.
///
T eval(const std::string& expr)
{
T result = 0;
index_ = 0;
expr_ = expr;
try
{
result = parseExpr();
if (!isEnd())
unexpected();
}
catch (const calculator::error&)
{
while(!stack_.empty())
stack_.pop();
throw;
}
return result;
}
/// Get the integer value of a character.
T eval(char c)
{
std::string expr(1, c);
return eval(expr);
}
private:
enum
{
OPERATOR_NULL,
OPERATOR_BITWISE_OR, /// |
OPERATOR_BITWISE_XOR, /// ^
OPERATOR_BITWISE_AND, /// &
OPERATOR_BITWISE_SHL, /// <<
OPERATOR_BITWISE_SHR, /// >>
OPERATOR_ADDITION, /// +
OPERATOR_SUBTRACTION, /// -
OPERATOR_MULTIPLICATION, /// *
OPERATOR_DIVISION, /// /
OPERATOR_MODULO, /// %
OPERATOR_POWER, /// **
OPERATOR_EXPONENT /// e, E
};
struct Operator
{
/// Operator, one of the OPERATOR_* enum definitions
int op;
int precedence;
/// 'L' = left or 'R' = right
int associativity;
Operator(int opr, int prec, int assoc) :
op(opr),
precedence(prec),
associativity(assoc)
{ }
};
struct OperatorValue
{
Operator op;
T value;
OperatorValue(const Operator& opr, T val) :
op(opr),
value(val)
{ }
int getPrecedence() const
{
return op.precedence;
}
bool isNull() const
{
return op.op == OPERATOR_NULL;
}
};
/// Expression string
std::string expr_;
/// Current expression index, incremented whilst parsing
std::size_t index_;
/// The current operator and its left value
/// are pushed onto the stack if the operator on
/// top of the stack has lower precedence.
std::stack<OperatorValue> stack_;
/// Exponentiation by squaring, x^n.
static T pow(T x, T n)
{
T res = 1;
while (n > 0)
{
if (n % 2 != 0)
{
res *= x;
n -= 1;
}
n /= 2;
if (n > 0)
x *= x;
}
return res;
}
T checkZero(T value) const
{
if (value == 0)
{
std::string divOperators("/%");
std::size_t division = expr_.find_last_of(divOperators, index_ - 2);
std::ostringstream msg;
msg << "Parser error: division by 0";
if (division != std::string::npos)
msg << " (error token is \""
<< expr_.substr(division, expr_.size() - division)
<< "\")";
throw calculator::error(expr_, msg.str());
}
return value;
}
T calculate(T v1, T v2, const Operator& op) const
{
switch (op.op)
{
case OPERATOR_BITWISE_OR: return v1 | v2;
case OPERATOR_BITWISE_XOR: return v1 ^ v2;
case OPERATOR_BITWISE_AND: return v1 & v2;
case OPERATOR_BITWISE_SHL: return v1 << v2;
case OPERATOR_BITWISE_SHR: return v1 >> v2;
case OPERATOR_ADDITION: return v1 + v2;
case OPERATOR_SUBTRACTION: return v1 - v2;
case OPERATOR_MULTIPLICATION: return v1 * v2;
case OPERATOR_DIVISION: return v1 / checkZero(v2);
case OPERATOR_MODULO: return v1 % checkZero(v2);
case OPERATOR_POWER: return pow(v1, v2);
case OPERATOR_EXPONENT: return v1 * pow(10, v2);
default: return 0;
}
}
bool isEnd() const
{
return index_ >= expr_.size();
}
/// Returns the character at the current expression index or
/// 0 if the end of the expression is reached.
///
char getCharacter() const
{
if (!isEnd())
return expr_[index_];
return 0;
}
/// Parse str at the current expression index.
/// @throw error if parsing fails.
///
void expect(const std::string& str)
{
if (expr_.compare(index_, str.size(), str) != 0)
unexpected();
index_ += str.size();
}
void unexpected() const
{
std::ostringstream msg;
msg << "Syntax error: unexpected token \""
<< expr_.substr(index_, expr_.size() - index_)
<< "\" at index "
<< index_;
throw calculator::error(expr_, msg.str());
}
/// Eat all white space characters at the
/// current expression index.
///
void eatSpaces()
{
while (std::isspace(getCharacter()) != 0)
index_++;
}
/// Parse a binary operator at the current expression index.
/// @return Operator with precedence and associativity.
///
Operator parseOp()
{
eatSpaces();
switch (getCharacter())
{
case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');
case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');
case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');
case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');
case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');
case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');
case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');
case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');
case '*': index_++; if (getCharacter() != '*')
return Operator(OPERATOR_MULTIPLICATION, 20, 'L');
index_++; return Operator(OPERATOR_POWER, 30, 'R');
case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');
case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
default : return Operator(OPERATOR_NULL, 0, 'L');
}
}
static T toInteger(char c)
{
if (c >= '0' && c <= '9') return c -'0';
if (c >= 'a' && c <= 'f') return c -'a' + 0xa;
if (c >= 'A' && c <= 'F') return c -'A' + 0xa;
T noDigit = 0xf + 1;
return noDigit;
}
T getInteger() const
{
return toInteger(getCharacter());
}
T parseDecimal()
{
T value = 0;
for (T d; (d = getInteger()) <= 9; index_++)
value = value * 10 + d;
return value;
}
T parseHex()
{
index_ = index_ + 2;
T value = 0;
for (T h; (h = getInteger()) <= 0xf; index_++)
value = value * 0x10 + h;
return value;
}
bool isHex() const
{
if (index_ + 2 < expr_.size())
{
char x = expr_[index_ + 1];
char h = expr_[index_ + 2];
return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);
}
return false;
}
/// Parse an integer value at the current expression index.
/// The unary `+', `-' and `~' operators and opening
/// parentheses `(' cause recursion.
///
T parseValue()
{
T val = 0;
eatSpaces();
switch (getCharacter())
{
case '0': if (isHex())
val = parseHex();
else
val = parseDecimal();
break;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
val = parseDecimal();
break;
case '(': index_++;
val = parseExpr();
eatSpaces();
if (getCharacter() != ')')
{
if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: `)' expected at end of expression");
}
index_++; break;
case '~': index_++; val = ~parseValue(); break;
case '+': index_++; val = parseValue(); break;
case '-': index_++; val = parseValue() * static_cast<T>(-1);
break;
default : if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: value expected at end of expression");
}
return val;
}
/// Parse all operations of the current parenthesis
/// level and the levels above, when done
/// return the result (value).
///
T parseExpr()
{
stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));
// first parse value on the left
T value = parseValue();
while (!stack_.empty())
{
// parse an operator (+, -, *, ...)
Operator op(parseOp());
while (op.precedence < stack_.top().getPrecedence() || (
op.precedence == stack_.top().getPrecedence() &&
op.associativity == 'L'))
{
// end reached
if (stack_.top().isNull())
{
stack_.pop();
return value;
}
// do the calculation ("reduce"), producing a new value
value = calculate(stack_.top().value, value, stack_.top().op);
stack_.pop();
}
// store on stack_ and continue parsing ("shift")
stack_.push(OperatorValue(op, value));
// parse value on the right
value = parseValue();
}
return 0;
}
};
template <typename T>
inline T eval(const std::string& expression)
{
ExpressionParser<T> parser;
return parser.eval(expression);
}
template <typename T>
inline T eval(char c)
{
ExpressionParser<T> parser;
return parser.eval(c);
}
inline int eval(const std::string& expression)
{
return eval<int>(expression);
}
inline int eval(char c)
{
return eval<int>(c);
}
} // namespace calculator
#endif
<commit_msg>Silence clang-cl -Wdeprecated warning<commit_after>///
/// @file calculator.hpp
/// @brief calculator::eval(const std::string&) evaluates an integer
/// arithmetic expression and returns the result. If an error
/// occurs a calculator::error exception is thrown.
/// <https://github.com/kimwalisch/calculator>
/// @author Kim Walisch, <kim.walisch@gmail.com>
/// @copyright Copyright (C) 2013-2018 Kim Walisch
/// @license BSD 2-Clause, https://opensource.org/licenses/BSD-2-Clause
/// @version 1.4 patched: `^' is raise to power instead of XOR.
///
/// == Supported operators ==
///
/// OPERATOR NAME ASSOCIATIVITY PRECEDENCE
///
/// | Bitwise Inclusive OR Left 4
/// & Bitwise AND Left 6
/// << Shift Left Left 9
/// >> Shift Right Left 9
/// + Addition Left 10
/// - Subtraction Left 10
/// * Multiplication Left 20
/// / Division Left 20
/// % Modulo Left 20
/// ^, ** Raise to power Right 30
/// e, E Scientific notation Right 40
/// ~ Unary complement Left 99
///
/// The operator precedence has been set according to (uses the C and
/// C++ operator precedence): https://en.wikipedia.org/wiki/Order_of_operations
/// Operators with higher precedence are evaluated before operators
/// with relatively lower precedence. Unary operators are set to have
/// the highest precedence, this is not strictly correct for the power
/// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell,
/// Microsoft Excel, GNU bc, ...) use the same convention.
///
/// == Examples of valid expressions ==
///
/// "65536 >> 15" = 2
/// "2**16" = 65536
/// "(0 + 0xDf234 - 1000)*3/2%999" = 828
/// "-(2**2**2**2)" = -65536
/// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817
/// "(2**16) + (1 << 16) >> 0X5" = 4096
/// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221
///
/// == About the algorithm used ==
///
/// calculator::eval(std::string&) relies on the ExpressionParser
/// class which is a simple C++ operator precedence parser with infix
/// notation for integer arithmetic expressions.
/// ExpressionParser has its roots in a JavaScript parser published
/// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961
/// The same author has also published an article about his operator
/// precedence algorithm at PerlMonks:
/// http://www.perlmonks.org/?node_id=554516
///
#ifndef CALCULATOR_HPP
#define CALCULATOR_HPP
#include <stdexcept>
#include <string>
#include <sstream>
#include <stack>
#include <cstddef>
#include <cctype>
namespace calculator
{
/// calculator::eval() throws a calculator::error if it fails
/// to evaluate the expression string.
///
class error : public std::runtime_error
{
public:
error(const std::string& expr, const std::string& message)
: std::runtime_error(message),
expr_(expr)
{ }
#if __cplusplus < 201103L
~error() throw() { }
#endif
std::string expression() const
{
return expr_;
}
private:
std::string expr_;
};
template <typename T>
class ExpressionParser
{
public:
/// Evaluate an integer arithmetic expression and return its result.
/// @throw error if parsing fails.
///
T eval(const std::string& expr)
{
T result = 0;
index_ = 0;
expr_ = expr;
try
{
result = parseExpr();
if (!isEnd())
unexpected();
}
catch (const calculator::error&)
{
while(!stack_.empty())
stack_.pop();
throw;
}
return result;
}
/// Get the integer value of a character.
T eval(char c)
{
std::string expr(1, c);
return eval(expr);
}
private:
enum
{
OPERATOR_NULL,
OPERATOR_BITWISE_OR, /// |
OPERATOR_BITWISE_XOR, /// ^
OPERATOR_BITWISE_AND, /// &
OPERATOR_BITWISE_SHL, /// <<
OPERATOR_BITWISE_SHR, /// >>
OPERATOR_ADDITION, /// +
OPERATOR_SUBTRACTION, /// -
OPERATOR_MULTIPLICATION, /// *
OPERATOR_DIVISION, /// /
OPERATOR_MODULO, /// %
OPERATOR_POWER, /// **
OPERATOR_EXPONENT /// e, E
};
struct Operator
{
/// Operator, one of the OPERATOR_* enum definitions
int op;
int precedence;
/// 'L' = left or 'R' = right
int associativity;
Operator(int opr, int prec, int assoc) :
op(opr),
precedence(prec),
associativity(assoc)
{ }
};
struct OperatorValue
{
Operator op;
T value;
OperatorValue(const Operator& opr, T val) :
op(opr),
value(val)
{ }
int getPrecedence() const
{
return op.precedence;
}
bool isNull() const
{
return op.op == OPERATOR_NULL;
}
};
/// Expression string
std::string expr_;
/// Current expression index, incremented whilst parsing
std::size_t index_;
/// The current operator and its left value
/// are pushed onto the stack if the operator on
/// top of the stack has lower precedence.
std::stack<OperatorValue> stack_;
/// Exponentiation by squaring, x^n.
static T pow(T x, T n)
{
T res = 1;
while (n > 0)
{
if (n % 2 != 0)
{
res *= x;
n -= 1;
}
n /= 2;
if (n > 0)
x *= x;
}
return res;
}
T checkZero(T value) const
{
if (value == 0)
{
std::string divOperators("/%");
std::size_t division = expr_.find_last_of(divOperators, index_ - 2);
std::ostringstream msg;
msg << "Parser error: division by 0";
if (division != std::string::npos)
msg << " (error token is \""
<< expr_.substr(division, expr_.size() - division)
<< "\")";
throw calculator::error(expr_, msg.str());
}
return value;
}
T calculate(T v1, T v2, const Operator& op) const
{
switch (op.op)
{
case OPERATOR_BITWISE_OR: return v1 | v2;
case OPERATOR_BITWISE_XOR: return v1 ^ v2;
case OPERATOR_BITWISE_AND: return v1 & v2;
case OPERATOR_BITWISE_SHL: return v1 << v2;
case OPERATOR_BITWISE_SHR: return v1 >> v2;
case OPERATOR_ADDITION: return v1 + v2;
case OPERATOR_SUBTRACTION: return v1 - v2;
case OPERATOR_MULTIPLICATION: return v1 * v2;
case OPERATOR_DIVISION: return v1 / checkZero(v2);
case OPERATOR_MODULO: return v1 % checkZero(v2);
case OPERATOR_POWER: return pow(v1, v2);
case OPERATOR_EXPONENT: return v1 * pow(10, v2);
default: return 0;
}
}
bool isEnd() const
{
return index_ >= expr_.size();
}
/// Returns the character at the current expression index or
/// 0 if the end of the expression is reached.
///
char getCharacter() const
{
if (!isEnd())
return expr_[index_];
return 0;
}
/// Parse str at the current expression index.
/// @throw error if parsing fails.
///
void expect(const std::string& str)
{
if (expr_.compare(index_, str.size(), str) != 0)
unexpected();
index_ += str.size();
}
void unexpected() const
{
std::ostringstream msg;
msg << "Syntax error: unexpected token \""
<< expr_.substr(index_, expr_.size() - index_)
<< "\" at index "
<< index_;
throw calculator::error(expr_, msg.str());
}
/// Eat all white space characters at the
/// current expression index.
///
void eatSpaces()
{
while (std::isspace(getCharacter()) != 0)
index_++;
}
/// Parse a binary operator at the current expression index.
/// @return Operator with precedence and associativity.
///
Operator parseOp()
{
eatSpaces();
switch (getCharacter())
{
case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');
case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');
case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');
case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');
case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');
case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');
case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');
case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');
case '*': index_++; if (getCharacter() != '*')
return Operator(OPERATOR_MULTIPLICATION, 20, 'L');
index_++; return Operator(OPERATOR_POWER, 30, 'R');
case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');
case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
default : return Operator(OPERATOR_NULL, 0, 'L');
}
}
static T toInteger(char c)
{
if (c >= '0' && c <= '9') return c -'0';
if (c >= 'a' && c <= 'f') return c -'a' + 0xa;
if (c >= 'A' && c <= 'F') return c -'A' + 0xa;
T noDigit = 0xf + 1;
return noDigit;
}
T getInteger() const
{
return toInteger(getCharacter());
}
T parseDecimal()
{
T value = 0;
for (T d; (d = getInteger()) <= 9; index_++)
value = value * 10 + d;
return value;
}
T parseHex()
{
index_ = index_ + 2;
T value = 0;
for (T h; (h = getInteger()) <= 0xf; index_++)
value = value * 0x10 + h;
return value;
}
bool isHex() const
{
if (index_ + 2 < expr_.size())
{
char x = expr_[index_ + 1];
char h = expr_[index_ + 2];
return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);
}
return false;
}
/// Parse an integer value at the current expression index.
/// The unary `+', `-' and `~' operators and opening
/// parentheses `(' cause recursion.
///
T parseValue()
{
T val = 0;
eatSpaces();
switch (getCharacter())
{
case '0': if (isHex())
val = parseHex();
else
val = parseDecimal();
break;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
val = parseDecimal();
break;
case '(': index_++;
val = parseExpr();
eatSpaces();
if (getCharacter() != ')')
{
if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: `)' expected at end of expression");
}
index_++; break;
case '~': index_++; val = ~parseValue(); break;
case '+': index_++; val = parseValue(); break;
case '-': index_++; val = parseValue() * static_cast<T>(-1);
break;
default : if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: value expected at end of expression");
}
return val;
}
/// Parse all operations of the current parenthesis
/// level and the levels above, when done
/// return the result (value).
///
T parseExpr()
{
stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));
// first parse value on the left
T value = parseValue();
while (!stack_.empty())
{
// parse an operator (+, -, *, ...)
Operator op(parseOp());
while (op.precedence < stack_.top().getPrecedence() || (
op.precedence == stack_.top().getPrecedence() &&
op.associativity == 'L'))
{
// end reached
if (stack_.top().isNull())
{
stack_.pop();
return value;
}
// do the calculation ("reduce"), producing a new value
value = calculate(stack_.top().value, value, stack_.top().op);
stack_.pop();
}
// store on stack_ and continue parsing ("shift")
stack_.push(OperatorValue(op, value));
// parse value on the right
value = parseValue();
}
return 0;
}
};
template <typename T>
inline T eval(const std::string& expression)
{
ExpressionParser<T> parser;
return parser.eval(expression);
}
template <typename T>
inline T eval(char c)
{
ExpressionParser<T> parser;
return parser.eval(c);
}
inline int eval(const std::string& expression)
{
return eval<int>(expression);
}
inline int eval(char c)
{
return eval<int>(c);
}
} // namespace calculator
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds array into usable address objects.
static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int k = 0; k < count; ++k)
{
struct in_addr ip;
unsigned int i = data[k], t;
// -- convert to big endian
t = (i & 0x000000ff) << 24u
| (i & 0x0000ff00) << 8u
| (i & 0x00ff0000) >> 8u
| (i & 0xff000000) >> 24u;
memcpy(&ip, &t, sizeof(ip));
CAddress addr(CService(ip, port));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xd2;
pchMessageStart[1] = 0x2d;
pchMessageStart[2] = 0x1c;
pchMessageStart[3] = 0xe5;
vAlertPubKey = ParseHex("04cc24ab003c828cdd9cf4db2ebbde8esdfsdfsdsdfsdfsfsdfsdf1cecb3bbfa8b3127fcb9dd9b84d44112080827ed7c49a648af9fe788ff42e316aee665879c553f099e55299d6b54edd7e0");
nDefaultPort = 22349;
nRPCPort = 22348;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
const char* pszTimestamp = "June 13th, 2016: ISIS claims responsibility for the shooting massacre at Orlando FL gay night club yesterday morning leaving 49 dead & many wounded.";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1465873655, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1465873655;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 48480;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00008b645780949ad9a346df272390396d10f6c67a3bef9e2fe2114854786ac3"));
assert(genesis.hashMerkleRoot == uint256("0xffc835b4aab6d5002db95706cd864c5614dfb1d7cfda1ce3beedf740a9aca558"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(63);
base58Prefixes[SCRIPT_ADDRESS] = list_of(85);
base58Prefixes[SECRET_KEY] = list_of(153);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
vSeeds.push_back(CDNSSeedData("Syndicate1", "192.241.215.173"));
vSeeds.push_back(CDNSSeedData("Syndicate2", "192.241.237.60"));
vSeeds.push_back(CDNSSeedData("Syndicate3", "162.243.130.27"));
vSeeds.push_back(CDNSSeedData("Syndicate4", "162.243.131.87"));
vSeeds.push_back(CDNSSeedData("Syndicate5", "107.170.229.36"));
vSeeds.push_back(CDNSSeedData("Syndicate6", "104.131.58.180"));
vSeeds.push_back(CDNSSeedData("Syndicate7", "104.236.233.90"));
vSeeds.push_back(CDNSSeedData("Syndicate8", "45.55.179.6"));
vSeeds.push_back(CDNSSeedData("Syndicate9", "45.55.181.27"));
vSeeds.push_back(CDNSSeedData("Syndicate10", "45.55.181.37"));
vSeeds.push_back(CDNSSeedData("SYNX1", "198.199.100.4"));
vSeeds.push_back(CDNSSeedData("SYNX2", "107.170.247.240"));
vSeeds.push_back(CDNSSeedData("SYNX3", "162.243.0.171"));
vSeeds.push_back(CDNSSeedData("SYNX4", "162.243.62.235"));
vSeeds.push_back(CDNSSeedData("SyndicateBlockExplorer", "107.170.232.206"));
vSeeds.push_back(CDNSSeedData("SyndicateNode1", "162.243.121.185"));
convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort);
nPoolMaxTransactions = 3;
strDarksendPoolDummyAddress = "SyndicateDarksendPoo1DummyAdy4viSr";
nLastPOWBlock = 56007;
nPOSStartBlock = 180;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x2f;
pchMessageStart[1] = 0xca;
pchMessageStart[2] = 0x4d;
pchMessageStart[3] = 0x3e;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("9as8d7f9a8sd76f90a7df90a8sdfhadf8asdfnhasdfn7as9d8f7awefh9asdf89asd78fhasd89fhasdf789hasdf89");
nDefaultPort = 27170;
nRPCPort = 27171;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = 520159231;
genesis.nNonce = 80086;
// assert(hashGenesisBlock == uint256("0x"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(97);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort);
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Fix #5<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds array into usable address objects.
static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int k = 0; k < count; ++k)
{
struct in_addr ip;
unsigned int i = data[k], t;
// -- convert to big endian
t = (i & 0x000000ff) << 24u
| (i & 0x0000ff00) << 8u
| (i & 0x00ff0000) >> 8u
| (i & 0xff000000) >> 24u;
memcpy(&ip, &t, sizeof(ip));
CAddress addr(CService(ip, port));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xd2;
pchMessageStart[1] = 0x2d;
pchMessageStart[2] = 0x1c;
pchMessageStart[3] = 0xe5;
vAlertPubKey = ParseHex("04cc24ab003c828cdd9cf4db2ebbde8esdfsdfsdsdfsdfsfsdfsdf1cecb3bbfa8b3127fcb9dd9b84d44112080827ed7c49a648af9fe788ff42e316aee665879c553f099e55299d6b54edd7e0");
nDefaultPort = 22349;
nRPCPort = 22348;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
const char* pszTimestamp = "June 13th, 2016: ISIS claims responsibility for the shooting massacre at Orlando FL gay night club yesterday morning leaving 49 dead & many wounded.";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1465873655, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1465873655;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 48480;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00008b645780949ad9a346df272390396d10f6c67a3bef9e2fe2114854786ac3"));
assert(genesis.hashMerkleRoot == uint256("0xffc835b4aab6d5002db95706cd864c5614dfb1d7cfda1ce3beedf740a9aca558"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(63);
base58Prefixes[SCRIPT_ADDRESS] = list_of(85);
base58Prefixes[SECRET_KEY] = list_of(153);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
vSeeds.push_back(CDNSSeedData("Syndicate1", "192.241.215.173"));
vSeeds.push_back(CDNSSeedData("Syndicate2", "192.241.237.60"));
vSeeds.push_back(CDNSSeedData("Syndicate3", "162.243.130.27"));
vSeeds.push_back(CDNSSeedData("Syndicate4", "162.243.131.87"));
vSeeds.push_back(CDNSSeedData("Syndicate5", "104.131.145.170"));
vSeeds.push_back(CDNSSeedData("Syndicate6", "104.131.58.180"));
vSeeds.push_back(CDNSSeedData("Syndicate7", "104.236.233.90"));
vSeeds.push_back(CDNSSeedData("Syndicate8", "45.55.179.6"));
vSeeds.push_back(CDNSSeedData("Syndicate9", "45.55.181.27"));
vSeeds.push_back(CDNSSeedData("Syndicate10", "45.55.181.37"));
vSeeds.push_back(CDNSSeedData("SYNX1", "198.199.100.4"));
vSeeds.push_back(CDNSSeedData("SYNX2", "107.170.247.240"));
vSeeds.push_back(CDNSSeedData("SYNX3", "162.243.0.171"));
vSeeds.push_back(CDNSSeedData("SYNX4", "162.243.62.235"));
vSeeds.push_back(CDNSSeedData("SyndicateBlockExplorer", "107.170.232.206"));
vSeeds.push_back(CDNSSeedData("SyndicateNode1", "162.243.121.185"));
convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort);
nPoolMaxTransactions = 3;
strDarksendPoolDummyAddress = "SyndicateDarksendPoo1DummyAdy4viSr";
nLastPOWBlock = 56007;
nPOSStartBlock = 180;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x2f;
pchMessageStart[1] = 0xca;
pchMessageStart[2] = 0x4d;
pchMessageStart[3] = 0x3e;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("9as8d7f9a8sd76f90a7df90a8sdfhadf8asdfnhasdfn7as9d8f7awefh9asdf89asd78fhasd89fhasdf789hasdf89");
nDefaultPort = 27170;
nRPCPort = 27171;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = 520159231;
genesis.nNonce = 80086;
// assert(hashGenesisBlock == uint256("0x"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(97);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort);
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|> |
<commit_before>//===--- GenArchetype.cpp - Swift IR Generation for Archetype Types -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for archetype types in Swift.
//
//===----------------------------------------------------------------------===//
#include "GenArchetype.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Types.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "EnumPayload.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "GenClass.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenOpaque.h"
#include "GenPoly.h"
#include "GenProto.h"
#include "GenType.h"
#include "HeapTypeInfo.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "ProtocolInfo.h"
#include "ResilientTypeInfo.h"
#include "TypeInfo.h"
#include "WeakTypeInfo.h"
using namespace swift;
using namespace irgen;
llvm::Value *irgen::emitArchetypeTypeMetadataRef(IRGenFunction &IGF,
CanArchetypeType archetype) {
// Check for an existing cache entry.
auto localDataKind = LocalTypeDataKind::forTypeMetadata();
auto metadata = IGF.tryGetLocalTypeData(archetype, localDataKind);
// If that's not present, this must be an associated type.
if (!metadata) {
assert(!archetype->isPrimary() &&
"type metadata for primary archetype was not bound in context");
CanArchetypeType parent(archetype->getParent());
AssociatedType association(archetype->getAssocType());
metadata = emitAssociatedTypeMetadataRef(IGF, parent, association);
setTypeMetadataName(IGF.IGM, metadata, archetype);
IGF.setScopedLocalTypeData(archetype, localDataKind, metadata);
}
return metadata;
}
namespace {
/// A type implementation for an ArchetypeType, otherwise known as a
/// type variable: for example, Self in a protocol declaration, or T
/// in a generic declaration like foo<T>(x : T) -> T. The critical
/// thing here is that performing an operation involving archetypes
/// is dependent on the witness binding we can see.
class OpaqueArchetypeTypeInfo
: public ResilientTypeInfo<OpaqueArchetypeTypeInfo>
{
OpaqueArchetypeTypeInfo(llvm::Type *type) : ResilientTypeInfo(type) {}
public:
static const OpaqueArchetypeTypeInfo *create(llvm::Type *type) {
return new OpaqueArchetypeTypeInfo(type);
}
};
/// A type implementation for a class archetype, that is, an archetype
/// bounded by a class protocol constraint. These archetypes can be
/// represented by a refcounted pointer instead of an opaque value buffer.
/// If ObjC interop is disabled, we can use Swift refcounting entry
/// points, otherwise we have to use the unknown ones.
class ClassArchetypeTypeInfo
: public HeapTypeInfo<ClassArchetypeTypeInfo>
{
ReferenceCounting RefCount;
ClassArchetypeTypeInfo(llvm::PointerType *storageType,
Size size, const SpareBitVector &spareBits,
Alignment align,
ReferenceCounting refCount)
: HeapTypeInfo(storageType, size, spareBits, align),
RefCount(refCount)
{}
public:
static const ClassArchetypeTypeInfo *create(llvm::PointerType *storageType,
Size size, const SpareBitVector &spareBits,
Alignment align,
ReferenceCounting refCount) {
return new ClassArchetypeTypeInfo(storageType, size, spareBits, align,
refCount);
}
ReferenceCounting getReferenceCounting() const {
return RefCount;
}
};
class FixedSizeArchetypeTypeInfo
: public PODSingleScalarTypeInfo<FixedSizeArchetypeTypeInfo, LoadableTypeInfo>
{
FixedSizeArchetypeTypeInfo(llvm::Type *type, Size size, Alignment align,
const SpareBitVector &spareBits)
: PODSingleScalarTypeInfo(type, size, spareBits, align) {}
public:
static const FixedSizeArchetypeTypeInfo *
create(llvm::Type *type, Size size, Alignment align,
const SpareBitVector &spareBits) {
return new FixedSizeArchetypeTypeInfo(type, size, align, spareBits);
}
};
} // end anonymous namespace
/// Emit a single protocol witness table reference.
llvm::Value *irgen::emitArchetypeWitnessTableRef(IRGenFunction &IGF,
CanArchetypeType archetype,
ProtocolDecl *protocol) {
assert(Lowering::TypeConverter::protocolRequiresWitnessTable(protocol) &&
"looking up witness table for protocol that doesn't have one");
// The following approach assumes that a protocol will only appear in
// an archetype's conformsTo array if the archetype is either explicitly
// constrained to conform to that protocol (in which case we should have
// a cache entry for it) or there's an associated type declaration with
// that protocol listed as a direct requirement.
auto localDataKind =
LocalTypeDataKind::forAbstractProtocolWitnessTable(protocol);
// Check immediately for an existing cache entry.
// TODO: don't give this absolute precedence over other access paths.
auto wtable = IGF.tryGetLocalTypeData(archetype, localDataKind);
if (wtable) return wtable;
// It can happen with class constraints that Sema will consider a
// constraint to be abstract, but the minimized signature will
// eliminate it as concrete. Handle this by performing a concrete
// lookup.
// TODO: maybe Sema shouldn't ever do this?
if (Type classBound = archetype->getSuperclass()) {
auto conformance =
IGF.IGM.getSwiftModule()->lookupConformance(classBound, protocol);
if (conformance && conformance->isConcrete()) {
return emitWitnessTableRef(IGF, archetype, *conformance);
}
}
// If we don't have an environment, this must be an implied witness table
// reference.
// FIXME: eliminate this path when opened types have generic environments.
auto environment = archetype->getGenericEnvironment();
if (!environment) {
assert(archetype->isOpenedExistential() &&
"non-opened archetype lacking generic environment?");
SmallVector<ProtocolEntry, 4> entries;
for (auto p : archetype->getConformsTo()) {
const ProtocolInfo &impl = IGF.IGM.getProtocolInfo(p);
entries.push_back(ProtocolEntry(p, impl));
}
return emitImpliedWitnessTableRef(IGF, entries, protocol,
[&](unsigned index) -> llvm::Value* {
auto localDataKind =
LocalTypeDataKind::forAbstractProtocolWitnessTable(
entries[index].getProtocol());
auto wtable = IGF.tryGetLocalTypeData(archetype, localDataKind);
assert(wtable &&
"opened type without local type data for direct conformance?");
return wtable;
});
}
// Otherwise, ask the generic signature for the environment for the best
// path to the conformance.
// TODO: this isn't necessarily optimal if the direct conformance isn't
// concretely available; we really ought to be comparing the full paths
// to this conformance from concrete sources.
auto signature = environment->getGenericSignature()->getCanonicalSignature();
auto archetypeDepType = environment->mapTypeOutOfContext(archetype);
auto astPath = signature->getConformanceAccessPath(archetypeDepType, protocol,
*IGF.IGM.getSwiftModule());
auto i = astPath.begin(), e = astPath.end();
assert(i != e && "empty path!");
// The first entry in the path is a direct requirement of the signature,
// for which we should always have local type data available.
CanType rootArchetype =
environment->mapTypeIntoContext(i->first)->getCanonicalType();
ProtocolDecl *rootProtocol = i->second;
// Turn the rest of the path into a MetadataPath.
auto lastProtocol = rootProtocol;
MetadataPath path;
while (++i != e) {
auto &entry = *i;
CanType depType = CanType(entry.first);
ProtocolDecl *requirement = entry.second;
auto &lastPI = IGF.IGM.getProtocolInfo(lastProtocol);
// If it's a type parameter, it's self, and this is a base protocol
// requirement.
if (isa<GenericTypeParamType>(depType)) {
assert(depType->isEqual(lastProtocol->getSelfInterfaceType()));
WitnessIndex index = lastPI.getBaseIndex(requirement);
path.addInheritedProtocolComponent(index);
// Otherwise, it's an associated conformance requirement.
} else {
AssociatedConformance association(lastProtocol, depType, requirement);
WitnessIndex index = lastPI.getAssociatedConformanceIndex(association);
path.addAssociatedConformanceComponent(index);
}
lastProtocol = requirement;
}
assert(lastProtocol == protocol);
auto rootWTable = IGF.getLocalTypeData(rootArchetype,
LocalTypeDataKind::forAbstractProtocolWitnessTable(rootProtocol));
wtable = path.followFromWitnessTable(IGF, rootArchetype,
ProtocolConformanceRef(rootProtocol),
rootWTable, nullptr);
return wtable;
}
llvm::Value *irgen::emitAssociatedTypeMetadataRef(IRGenFunction &IGF,
CanArchetypeType origin,
AssociatedType association) {
// Find the conformance of the origin to the associated type's protocol.
llvm::Value *wtable = emitArchetypeWitnessTableRef(IGF, origin,
association.getSourceProtocol());
// Find the origin's type metadata.
llvm::Value *originMetadata = emitArchetypeTypeMetadataRef(IGF, origin);
return emitAssociatedTypeMetadataRef(IGF, originMetadata, wtable,
association);
}
const TypeInfo *TypeConverter::convertArchetypeType(ArchetypeType *archetype) {
assert(isExemplarArchetype(archetype) && "lowering non-exemplary archetype");
auto layout = archetype->getLayoutConstraint();
// If the archetype is class-constrained, use a class pointer
// representation.
if (archetype->requiresClass() ||
(layout && layout->isRefCounted())) {
auto refcount = getReferenceCountingForType(IGM, CanType(archetype));
llvm::PointerType *reprTy;
// If the archetype has a superclass constraint, it has at least the
// retain semantics of its superclass, and it can be represented with
// the supertype's pointer type.
if (auto super = archetype->getSuperclass()) {
auto &superTI = IGM.getTypeInfoForUnlowered(super);
reprTy = cast<llvm::PointerType>(superTI.StorageType);
} else {
if (refcount == ReferenceCounting::Native) {
reprTy = IGM.RefCountedPtrTy;
} else {
reprTy = IGM.UnknownRefCountedPtrTy;
}
}
// As a hack, assume class archetypes never have spare bits. There's a
// corresponding hack in MultiPayloadEnumImplStrategy::completeEnumTypeLayout
// to ignore spare bits of dependent-typed payloads.
auto spareBits =
SpareBitVector::getConstant(IGM.getPointerSize().getValueInBits(), false);
return ClassArchetypeTypeInfo::create(reprTy,
IGM.getPointerSize(),
spareBits,
IGM.getPointerAlignment(),
refcount);
}
// If the archetype is trivial fixed-size layout-constrained, use a fixed size
// representation.
if (layout && layout->isFixedSizeTrivial()) {
Size size(layout->getTrivialSizeInBytes());
auto layoutAlignment = layout->getAlignmentInBytes();
assert(layoutAlignment && "layout constraint alignment should not be 0");
Alignment align(layoutAlignment);
auto spareBits =
SpareBitVector::getConstant(size.getValueInBits(), false);
// Get an integer type of the required size.
auto ProperlySizedIntTy = SILType::getBuiltinIntegerType(
size.getValueInBits(), IGM.getSwiftModule()->getASTContext());
auto storageType = IGM.getStorageType(ProperlySizedIntTy);
return FixedSizeArchetypeTypeInfo::create(storageType, size, align,
spareBits);
}
// If the archetype is a trivial layout-constrained, use a POD
// representation. This type is not loadable, but it is known
// to be a POD.
if (layout && layout->isAddressOnlyTrivial()) {
// TODO: Create NonFixedSizeArchetypeTypeInfo and return it.
}
// Otherwise, for now, always use an opaque indirect type.
llvm::Type *storageType = IGM.OpaquePtrTy->getElementType();
return OpaqueArchetypeTypeInfo::create(storageType);
}
static void setMetadataRef(IRGenFunction &IGF,
ArchetypeType *archetype,
llvm::Value *metadata) {
assert(metadata->getType() == IGF.IGM.TypeMetadataPtrTy);
IGF.setUnscopedLocalTypeData(CanType(archetype),
LocalTypeDataKind::forTypeMetadata(),
metadata);
}
static void setWitnessTable(IRGenFunction &IGF,
ArchetypeType *archetype,
unsigned protocolIndex,
llvm::Value *wtable) {
assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy);
assert(protocolIndex < archetype->getConformsTo().size());
auto protocol = archetype->getConformsTo()[protocolIndex];
IGF.setUnscopedLocalTypeData(CanType(archetype),
LocalTypeDataKind::forAbstractProtocolWitnessTable(protocol),
wtable);
}
/// Inform IRGenFunction that the given archetype has the given value
/// witness value within this scope.
void IRGenFunction::bindArchetype(ArchetypeType *archetype,
llvm::Value *metadata,
ArrayRef<llvm::Value*> wtables) {
// Set the metadata pointer.
setTypeMetadataName(IGM, metadata, CanType(archetype));
setMetadataRef(*this, archetype, metadata);
// Set the protocol witness tables.
unsigned wtableI = 0;
for (unsigned i = 0, e = archetype->getConformsTo().size(); i != e; ++i) {
auto proto = archetype->getConformsTo()[i];
if (!Lowering::TypeConverter::protocolRequiresWitnessTable(proto))
continue;
auto wtable = wtables[wtableI++];
setProtocolWitnessTableName(IGM, wtable, CanType(archetype), proto);
setWitnessTable(*this, archetype, i, wtable);
}
assert(wtableI == wtables.size());
}
llvm::Value *irgen::emitDynamicTypeOfOpaqueArchetype(IRGenFunction &IGF,
Address addr,
SILType type) {
auto archetype = type.castTo<ArchetypeType>();
// Acquire the archetype's static metadata.
llvm::Value *metadata = emitArchetypeTypeMetadataRef(IGF, archetype);
return IGF.Builder.CreateCall(IGF.IGM.getGetDynamicTypeFn(),
{addr.getAddress(), metadata,
llvm::ConstantInt::get(IGF.IGM.Int1Ty, 0)});
}
<commit_msg>IRGen: Replace a mapTypeOutOfContext() call with ArchetypeType::getInterfaceType()<commit_after>//===--- GenArchetype.cpp - Swift IR Generation for Archetype Types -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for archetype types in Swift.
//
//===----------------------------------------------------------------------===//
#include "GenArchetype.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Types.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "EnumPayload.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "GenClass.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenOpaque.h"
#include "GenPoly.h"
#include "GenProto.h"
#include "GenType.h"
#include "HeapTypeInfo.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "ProtocolInfo.h"
#include "ResilientTypeInfo.h"
#include "TypeInfo.h"
#include "WeakTypeInfo.h"
using namespace swift;
using namespace irgen;
llvm::Value *irgen::emitArchetypeTypeMetadataRef(IRGenFunction &IGF,
CanArchetypeType archetype) {
// Check for an existing cache entry.
auto localDataKind = LocalTypeDataKind::forTypeMetadata();
auto metadata = IGF.tryGetLocalTypeData(archetype, localDataKind);
// If that's not present, this must be an associated type.
if (!metadata) {
assert(!archetype->isPrimary() &&
"type metadata for primary archetype was not bound in context");
CanArchetypeType parent(archetype->getParent());
AssociatedType association(archetype->getAssocType());
metadata = emitAssociatedTypeMetadataRef(IGF, parent, association);
setTypeMetadataName(IGF.IGM, metadata, archetype);
IGF.setScopedLocalTypeData(archetype, localDataKind, metadata);
}
return metadata;
}
namespace {
/// A type implementation for an ArchetypeType, otherwise known as a
/// type variable: for example, Self in a protocol declaration, or T
/// in a generic declaration like foo<T>(x : T) -> T. The critical
/// thing here is that performing an operation involving archetypes
/// is dependent on the witness binding we can see.
class OpaqueArchetypeTypeInfo
: public ResilientTypeInfo<OpaqueArchetypeTypeInfo>
{
OpaqueArchetypeTypeInfo(llvm::Type *type) : ResilientTypeInfo(type) {}
public:
static const OpaqueArchetypeTypeInfo *create(llvm::Type *type) {
return new OpaqueArchetypeTypeInfo(type);
}
};
/// A type implementation for a class archetype, that is, an archetype
/// bounded by a class protocol constraint. These archetypes can be
/// represented by a refcounted pointer instead of an opaque value buffer.
/// If ObjC interop is disabled, we can use Swift refcounting entry
/// points, otherwise we have to use the unknown ones.
class ClassArchetypeTypeInfo
: public HeapTypeInfo<ClassArchetypeTypeInfo>
{
ReferenceCounting RefCount;
ClassArchetypeTypeInfo(llvm::PointerType *storageType,
Size size, const SpareBitVector &spareBits,
Alignment align,
ReferenceCounting refCount)
: HeapTypeInfo(storageType, size, spareBits, align),
RefCount(refCount)
{}
public:
static const ClassArchetypeTypeInfo *create(llvm::PointerType *storageType,
Size size, const SpareBitVector &spareBits,
Alignment align,
ReferenceCounting refCount) {
return new ClassArchetypeTypeInfo(storageType, size, spareBits, align,
refCount);
}
ReferenceCounting getReferenceCounting() const {
return RefCount;
}
};
class FixedSizeArchetypeTypeInfo
: public PODSingleScalarTypeInfo<FixedSizeArchetypeTypeInfo, LoadableTypeInfo>
{
FixedSizeArchetypeTypeInfo(llvm::Type *type, Size size, Alignment align,
const SpareBitVector &spareBits)
: PODSingleScalarTypeInfo(type, size, spareBits, align) {}
public:
static const FixedSizeArchetypeTypeInfo *
create(llvm::Type *type, Size size, Alignment align,
const SpareBitVector &spareBits) {
return new FixedSizeArchetypeTypeInfo(type, size, align, spareBits);
}
};
} // end anonymous namespace
/// Emit a single protocol witness table reference.
llvm::Value *irgen::emitArchetypeWitnessTableRef(IRGenFunction &IGF,
CanArchetypeType archetype,
ProtocolDecl *protocol) {
assert(Lowering::TypeConverter::protocolRequiresWitnessTable(protocol) &&
"looking up witness table for protocol that doesn't have one");
// The following approach assumes that a protocol will only appear in
// an archetype's conformsTo array if the archetype is either explicitly
// constrained to conform to that protocol (in which case we should have
// a cache entry for it) or there's an associated type declaration with
// that protocol listed as a direct requirement.
auto localDataKind =
LocalTypeDataKind::forAbstractProtocolWitnessTable(protocol);
// Check immediately for an existing cache entry.
// TODO: don't give this absolute precedence over other access paths.
auto wtable = IGF.tryGetLocalTypeData(archetype, localDataKind);
if (wtable) return wtable;
// It can happen with class constraints that Sema will consider a
// constraint to be abstract, but the minimized signature will
// eliminate it as concrete. Handle this by performing a concrete
// lookup.
// TODO: maybe Sema shouldn't ever do this?
if (Type classBound = archetype->getSuperclass()) {
auto conformance =
IGF.IGM.getSwiftModule()->lookupConformance(classBound, protocol);
if (conformance && conformance->isConcrete()) {
return emitWitnessTableRef(IGF, archetype, *conformance);
}
}
// If we don't have an environment, this must be an implied witness table
// reference.
// FIXME: eliminate this path when opened types have generic environments.
auto environment = archetype->getGenericEnvironment();
if (!environment) {
assert(archetype->isOpenedExistential() &&
"non-opened archetype lacking generic environment?");
SmallVector<ProtocolEntry, 4> entries;
for (auto p : archetype->getConformsTo()) {
const ProtocolInfo &impl = IGF.IGM.getProtocolInfo(p);
entries.push_back(ProtocolEntry(p, impl));
}
return emitImpliedWitnessTableRef(IGF, entries, protocol,
[&](unsigned index) -> llvm::Value* {
auto localDataKind =
LocalTypeDataKind::forAbstractProtocolWitnessTable(
entries[index].getProtocol());
auto wtable = IGF.tryGetLocalTypeData(archetype, localDataKind);
assert(wtable &&
"opened type without local type data for direct conformance?");
return wtable;
});
}
// Otherwise, ask the generic signature for the environment for the best
// path to the conformance.
// TODO: this isn't necessarily optimal if the direct conformance isn't
// concretely available; we really ought to be comparing the full paths
// to this conformance from concrete sources.
auto signature = environment->getGenericSignature()->getCanonicalSignature();
auto archetypeDepType = archetype->getInterfaceType();
auto astPath = signature->getConformanceAccessPath(archetypeDepType, protocol,
*IGF.IGM.getSwiftModule());
auto i = astPath.begin(), e = astPath.end();
assert(i != e && "empty path!");
// The first entry in the path is a direct requirement of the signature,
// for which we should always have local type data available.
CanType rootArchetype =
environment->mapTypeIntoContext(i->first)->getCanonicalType();
ProtocolDecl *rootProtocol = i->second;
// Turn the rest of the path into a MetadataPath.
auto lastProtocol = rootProtocol;
MetadataPath path;
while (++i != e) {
auto &entry = *i;
CanType depType = CanType(entry.first);
ProtocolDecl *requirement = entry.second;
auto &lastPI = IGF.IGM.getProtocolInfo(lastProtocol);
// If it's a type parameter, it's self, and this is a base protocol
// requirement.
if (isa<GenericTypeParamType>(depType)) {
assert(depType->isEqual(lastProtocol->getSelfInterfaceType()));
WitnessIndex index = lastPI.getBaseIndex(requirement);
path.addInheritedProtocolComponent(index);
// Otherwise, it's an associated conformance requirement.
} else {
AssociatedConformance association(lastProtocol, depType, requirement);
WitnessIndex index = lastPI.getAssociatedConformanceIndex(association);
path.addAssociatedConformanceComponent(index);
}
lastProtocol = requirement;
}
assert(lastProtocol == protocol);
auto rootWTable = IGF.getLocalTypeData(rootArchetype,
LocalTypeDataKind::forAbstractProtocolWitnessTable(rootProtocol));
wtable = path.followFromWitnessTable(IGF, rootArchetype,
ProtocolConformanceRef(rootProtocol),
rootWTable, nullptr);
return wtable;
}
llvm::Value *irgen::emitAssociatedTypeMetadataRef(IRGenFunction &IGF,
CanArchetypeType origin,
AssociatedType association) {
// Find the conformance of the origin to the associated type's protocol.
llvm::Value *wtable = emitArchetypeWitnessTableRef(IGF, origin,
association.getSourceProtocol());
// Find the origin's type metadata.
llvm::Value *originMetadata = emitArchetypeTypeMetadataRef(IGF, origin);
return emitAssociatedTypeMetadataRef(IGF, originMetadata, wtable,
association);
}
const TypeInfo *TypeConverter::convertArchetypeType(ArchetypeType *archetype) {
assert(isExemplarArchetype(archetype) && "lowering non-exemplary archetype");
auto layout = archetype->getLayoutConstraint();
// If the archetype is class-constrained, use a class pointer
// representation.
if (archetype->requiresClass() ||
(layout && layout->isRefCounted())) {
auto refcount = getReferenceCountingForType(IGM, CanType(archetype));
llvm::PointerType *reprTy;
// If the archetype has a superclass constraint, it has at least the
// retain semantics of its superclass, and it can be represented with
// the supertype's pointer type.
if (auto super = archetype->getSuperclass()) {
auto &superTI = IGM.getTypeInfoForUnlowered(super);
reprTy = cast<llvm::PointerType>(superTI.StorageType);
} else {
if (refcount == ReferenceCounting::Native) {
reprTy = IGM.RefCountedPtrTy;
} else {
reprTy = IGM.UnknownRefCountedPtrTy;
}
}
// As a hack, assume class archetypes never have spare bits. There's a
// corresponding hack in MultiPayloadEnumImplStrategy::completeEnumTypeLayout
// to ignore spare bits of dependent-typed payloads.
auto spareBits =
SpareBitVector::getConstant(IGM.getPointerSize().getValueInBits(), false);
return ClassArchetypeTypeInfo::create(reprTy,
IGM.getPointerSize(),
spareBits,
IGM.getPointerAlignment(),
refcount);
}
// If the archetype is trivial fixed-size layout-constrained, use a fixed size
// representation.
if (layout && layout->isFixedSizeTrivial()) {
Size size(layout->getTrivialSizeInBytes());
auto layoutAlignment = layout->getAlignmentInBytes();
assert(layoutAlignment && "layout constraint alignment should not be 0");
Alignment align(layoutAlignment);
auto spareBits =
SpareBitVector::getConstant(size.getValueInBits(), false);
// Get an integer type of the required size.
auto ProperlySizedIntTy = SILType::getBuiltinIntegerType(
size.getValueInBits(), IGM.getSwiftModule()->getASTContext());
auto storageType = IGM.getStorageType(ProperlySizedIntTy);
return FixedSizeArchetypeTypeInfo::create(storageType, size, align,
spareBits);
}
// If the archetype is a trivial layout-constrained, use a POD
// representation. This type is not loadable, but it is known
// to be a POD.
if (layout && layout->isAddressOnlyTrivial()) {
// TODO: Create NonFixedSizeArchetypeTypeInfo and return it.
}
// Otherwise, for now, always use an opaque indirect type.
llvm::Type *storageType = IGM.OpaquePtrTy->getElementType();
return OpaqueArchetypeTypeInfo::create(storageType);
}
static void setMetadataRef(IRGenFunction &IGF,
ArchetypeType *archetype,
llvm::Value *metadata) {
assert(metadata->getType() == IGF.IGM.TypeMetadataPtrTy);
IGF.setUnscopedLocalTypeData(CanType(archetype),
LocalTypeDataKind::forTypeMetadata(),
metadata);
}
static void setWitnessTable(IRGenFunction &IGF,
ArchetypeType *archetype,
unsigned protocolIndex,
llvm::Value *wtable) {
assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy);
assert(protocolIndex < archetype->getConformsTo().size());
auto protocol = archetype->getConformsTo()[protocolIndex];
IGF.setUnscopedLocalTypeData(CanType(archetype),
LocalTypeDataKind::forAbstractProtocolWitnessTable(protocol),
wtable);
}
/// Inform IRGenFunction that the given archetype has the given value
/// witness value within this scope.
void IRGenFunction::bindArchetype(ArchetypeType *archetype,
llvm::Value *metadata,
ArrayRef<llvm::Value*> wtables) {
// Set the metadata pointer.
setTypeMetadataName(IGM, metadata, CanType(archetype));
setMetadataRef(*this, archetype, metadata);
// Set the protocol witness tables.
unsigned wtableI = 0;
for (unsigned i = 0, e = archetype->getConformsTo().size(); i != e; ++i) {
auto proto = archetype->getConformsTo()[i];
if (!Lowering::TypeConverter::protocolRequiresWitnessTable(proto))
continue;
auto wtable = wtables[wtableI++];
setProtocolWitnessTableName(IGM, wtable, CanType(archetype), proto);
setWitnessTable(*this, archetype, i, wtable);
}
assert(wtableI == wtables.size());
}
llvm::Value *irgen::emitDynamicTypeOfOpaqueArchetype(IRGenFunction &IGF,
Address addr,
SILType type) {
auto archetype = type.castTo<ArchetypeType>();
// Acquire the archetype's static metadata.
llvm::Value *metadata = emitArchetypeTypeMetadataRef(IGF, archetype);
return IGF.Builder.CreateCall(IGF.IGM.getGetDynamicTypeFn(),
{addr.getAddress(), metadata,
llvm::ConstantInt::get(IGF.IGM.Int1Ty, 0)});
}
<|endoftext|> |
<commit_before>#include "data_block_manager.hpp"
#include "log_serializer.hpp"
#include "utils.hpp"
#include "arch/arch.hpp"
void data_block_manager_t::start(direct_file_t *file) {
assert(state == state_unstarted);
dbfile = file;
last_data_extent = extent_manager->gen_extent();
blocks_in_last_data_extent = 0;
add_gc_entry();
state = state_ready;
}
void data_block_manager_t::start(direct_file_t *file, metablock_mixin_t *last_metablock) {
assert(state == state_unstarted);
dbfile = file;
last_data_extent = last_metablock->last_data_extent;
blocks_in_last_data_extent = last_metablock->blocks_in_last_data_extent;
state = state_ready;
}
bool data_block_manager_t::read(off64_t off_in, void *buf_out, iocallback_t *cb) {
assert(state == state_ready);
dbfile->read_async(off_in, block_size, buf_out, cb);
return false;
}
bool data_block_manager_t::write(void *buf_in, off64_t *off_out, iocallback_t *cb) {
// Either we're ready to write, or we're shutting down and just
// finished reading blocks for gc and called do_write.
assert(state == state_ready
|| (state == state_shutting_down && gc_state.step == gc_read));
off64_t offset = *off_out = gimme_a_new_offset();
dbfile->write_async(offset, block_size, buf_in, cb);
return false;
}
void data_block_manager_t::mark_garbage(off64_t offset) {
unsigned int extent_id = (offset / extent_manager->extent_size);
unsigned int block_id = (offset % extent_manager->extent_size) / block_size;
if ((gc_state.step == gc_read || gc_state.step == gc_write)
&& gc_state.current_entry.offset / extent_manager->extent_size == extent_id)
{
gc_state.current_entry.g_array.set(block_id, 1);
gc_stats.unyoung_garbage_blocks++;
} else {
assert(entries.get(extent_id));
entries.get(extent_id)->data.g_array.set(block_id, 1);
entries.get(extent_id)->update();
gc_stats.unyoung_garbage_blocks += !(entries.get(extent_id)->data.young);
}
}
void data_block_manager_t::start_reconstruct() {
gc_state.step = gc_reconstruct;
}
// Marks the block at the given offset as alive, in the appropriate
// gc_entry in the entries table. (This is used when we start up, when
// everything is presumed to be garbage, until we mark it as
// non-garbage.)
void data_block_manager_t::mark_live(off64_t offset) {
assert(gc_state.step == gc_reconstruct); // This is called at startup.
unsigned int extent_id = (offset / extent_manager->extent_size);
unsigned int block_id = (offset % extent_manager->extent_size) / block_size;
if (entries.get(extent_id) == NULL) {
gc_entry entry;
entry.init(extent_id * extent_manager->extent_size, false, false);
entry.g_array.set(); //set everything to garbage
entries.set(extent_id, gc_pq.push(entry));
}
/* mark the block as alive */
entries.get(extent_id)->data.g_array.set(block_id, 0);
}
void data_block_manager_t::end_reconstruct() {
for (unsigned int i = blocks_in_last_data_extent; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++)
mark_live(last_data_extent + (BTREE_BLOCK_SIZE * i));
gc_state.step = gc_ready;
}
void data_block_manager_t::start_gc() {
if (gc_state.step == gc_ready)
run_gc();
}
/* TODO this currently cleans extent by extent, we should tune it to always have a certain number of outstanding blocks
*/
void data_block_manager_t::run_gc() {
do {
bool fallthrough;
switch (gc_state.step) {
case gc_ready:
fallthrough = false;
//TODO, need to make sure we don't gc the extent we're writing to
if (should_we_keep_gcing(gc_pq.peak())) {
/* grab the entry */
gc_state.current_entry = gc_pq.pop();
// The reason why the GC deletes the entries instead of the PQ deleting them
// is in case we get a write to the block we are GCing.
gdelete(entries.get(gc_state.current_entry.offset / extent_manager->extent_size));
entries.set(gc_state.current_entry.offset / extent_manager->extent_size, NULL);
/* read all the live data into buffers */
/* make sure the read callback knows who we are */
gc_state.gc_read_callback.parent = this;
for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) {
if (!gc_state.current_entry.g_array[i]) {
dbfile->read_async(
gc_state.current_entry.offset + (i * block_size),
block_size,
gc_state.gc_blocks + (i * block_size),
&(gc_state.gc_read_callback));
gc_state.refcount++;
gc_state.blocks_copying++;
}
}
gc_state.step = gc_read;
if (gc_state.refcount == 0)
fallthrough = true;
} else {
return;
}
if (!fallthrough)
break;
case gc_read:
fallthrough = false;
/* refcount can == 0 here if we fell through */
gc_state.refcount--;
if (gc_state.refcount <= 0) {
/* we can get here with a refcount of 0 */
gc_state.refcount = 0;
/* check if blocks need to be copied */
if (gc_state.current_entry.g_array.count() < gc_state.current_entry.g_array.size()) {
/* an array to put our writes in */
log_serializer_t::write_t writes[gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count()];
int nwrites = 0;
for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) {
if (!gc_state.current_entry.g_array[i]) {
writes[nwrites].block_id = *((ser_block_id_t *) (gc_state.gc_blocks + (i * block_size)));
writes[nwrites].buf = gc_state.gc_blocks + (i * block_size);
writes[nwrites].callback = NULL;
nwrites++;
}
}
/* make sure the callback knows who we are */
gc_state.gc_write_callback.parent = this;
/* release the gc'ed extent (it's safe because
* the extent manager will ensure it won't be
* given away until the metablock is
* written) */
extent_manager->release_extent(gc_state.current_entry.offset);
/* schedule the write */
fallthrough = serializer->do_write(writes, gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count() , (log_serializer_t::write_txn_callback_t *) &gc_state.gc_write_callback);
} else {
fallthrough = true;
}
gc_state.step = gc_write;
}
if (!fallthrough)
break;
case gc_write:
//not valid when writes are asynchronous (it would be nice if we could have this)
assert(gc_state.current_entry.g_array.count() == gc_state.current_entry.g_array.size()); //Checks if everything in the array has been marked as garbage
assert(entries.get(gc_state.current_entry.offset / extent_manager->extent_size) == NULL);
assert(gc_state.refcount == 0);
gc_state.blocks_copying = 0;
gc_state.step = gc_ready;
/* update stats */
gc_stats.unyoung_total_blocks -= extent_manager->extent_size / BTREE_BLOCK_SIZE;
gc_stats.unyoung_garbage_blocks -= extent_manager->extent_size / BTREE_BLOCK_SIZE;
if(state == state_shutting_down) {
// The state = state_shut_down must happen
// _before_ the shutdown_callback is called.
state = state_shut_down;
if(shutdown_callback)
shutdown_callback->on_datablock_manager_shutdown();
return;
}
break;
default:
fail("Unknown gc_step");
break;
}
} while (gc_state.step == gc_ready);
}
void data_block_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert(state == state_ready
|| (state == state_shutting_down && gc_state.step == gc_read));
metablock->last_data_extent = last_data_extent;
metablock->blocks_in_last_data_extent = blocks_in_last_data_extent;
}
bool data_block_manager_t::shutdown(shutdown_callback_t *cb) {
assert(cb);
assert(state == state_ready);
if(gc_state.step != gc_ready) {
state = state_shutting_down;
shutdown_callback = cb;
return false;
}
state = state_shut_down;
return true;
}
off64_t data_block_manager_t::gimme_a_new_offset() {
if (blocks_in_last_data_extent == extent_manager->extent_size / block_size) {
/* deactivate the last extent */
entries.get(last_data_extent / extent_manager->extent_size)->data.active = false;
entries.get(last_data_extent / extent_manager->extent_size)->update();
last_data_extent = extent_manager->gen_extent();
blocks_in_last_data_extent = 0;
add_gc_entry();
}
off64_t offset = last_data_extent + blocks_in_last_data_extent * block_size;
blocks_in_last_data_extent ++;
return offset;
}
void data_block_manager_t::add_gc_entry() {
gc_entry entry;
entry.init(last_data_extent, true, true);
unsigned int extent_id = last_data_extent / extent_manager->extent_size;
assert(entries.get(extent_id) == NULL);
priority_queue_t<gc_entry, Less>::entry_t *pq_entry = gc_pq.push(entry);
entries.set(extent_id, pq_entry);
// update young_extent_queue
young_extent_queue.push(pq_entry);
mark_unyoung_entries();
}
// Looks at young_extent_queue and pops things off the queue that are
// no longer deemed young, marking them as not young.
void data_block_manager_t::mark_unyoung_entries() {
while (young_extent_queue.size() > GC_YOUNG_EXTENT_MAX_SIZE) {
remove_last_unyoung_entry();
}
gc_entry::timestamp_t current_time = gc_entry::current_timestamp();
while (!young_extent_queue.empty()
&& current_time - young_extent_queue.front()->data.timestamp > GC_YOUNG_EXTENT_TIMELIMIT_MICROS) {
remove_last_unyoung_entry();
}
}
// Pops young_extent_queue and marks the popped entry as unyoung.
// Assumes young_extent_queue is not empty.
void data_block_manager_t::remove_last_unyoung_entry() {
assert(!young_extent_queue.empty());
priority_queue_t<gc_entry, Less>::entry_t *pq_entry = young_extent_queue.front();
young_extent_queue.pop();
pq_entry->data.young = false;
pq_entry->update();
gc_stats.unyoung_total_blocks += extent_manager->extent_size / BTREE_BLOCK_SIZE;
gc_stats.unyoung_garbage_blocks += pq_entry->data.g_array.count();
}
/* functions for gc structures */
// Right now we start gc'ing when the garbage ratio is >= 0.75 (75%
// garbage) and we gc all blocks with that ratio or higher.
// Answers the following question: We're in the middle of gc'ing, and
// look, it's the next largest entry. Should we keep gc'ing? Returns
// false when the entry is active or young, or when its garbage ratio
// is lower than GC_THRESHOLD_RATIO_*.
bool data_block_manager_t::should_we_keep_gcing(const gc_entry& entry) const {
return !entry.active && !entry.young && entry.g_array.count() * GC_THRESHOLD_RATIO_DENOMINATOR >= ((extent_manager->extent_size / BTREE_BLOCK_SIZE) * GC_THRESHOLD_RATIO_NUMERATOR);
}
// Answers the following question: Do we want to bother gc'ing?
// Returns true when our garbage_ratio is greater than
// GC_THRESHOLD_RATIO_*.
bool data_block_manager_t::do_we_want_to_start_gcing() const {
return gc_stats.unyoung_garbage_blocks * GC_THRESHOLD_RATIO_DENOMINATOR >= GC_THRESHOLD_RATIO_NUMERATOR * gc_stats.unyoung_total_blocks;
}
/* !< is x less than y */
bool data_block_manager_t::Less::operator() (const data_block_manager_t::gc_entry x, const data_block_manager_t::gc_entry y) {
if (x.active || x.young)
return true;
else if (y.active || y.young)
return false;
else
return x.g_array.count() < y.g_array.count();
}
/****************
*Stat functions*
****************/
// This will return NaN when gc_stats.unyoung_total_blocks is zero.
float data_block_manager_t::garbage_ratio() {
// TODO: not divide by zero?
return (float) gc_stats.unyoung_garbage_blocks / (float) gc_stats.unyoung_total_blocks;
}
<commit_msg>Made mark_live properly update gc_stats<commit_after>#include "data_block_manager.hpp"
#include "log_serializer.hpp"
#include "utils.hpp"
#include "arch/arch.hpp"
void data_block_manager_t::start(direct_file_t *file) {
assert(state == state_unstarted);
dbfile = file;
last_data_extent = extent_manager->gen_extent();
blocks_in_last_data_extent = 0;
add_gc_entry();
state = state_ready;
}
void data_block_manager_t::start(direct_file_t *file, metablock_mixin_t *last_metablock) {
assert(state == state_unstarted);
dbfile = file;
last_data_extent = last_metablock->last_data_extent;
blocks_in_last_data_extent = last_metablock->blocks_in_last_data_extent;
state = state_ready;
}
bool data_block_manager_t::read(off64_t off_in, void *buf_out, iocallback_t *cb) {
assert(state == state_ready);
dbfile->read_async(off_in, block_size, buf_out, cb);
return false;
}
bool data_block_manager_t::write(void *buf_in, off64_t *off_out, iocallback_t *cb) {
// Either we're ready to write, or we're shutting down and just
// finished reading blocks for gc and called do_write.
assert(state == state_ready
|| (state == state_shutting_down && gc_state.step == gc_read));
off64_t offset = *off_out = gimme_a_new_offset();
dbfile->write_async(offset, block_size, buf_in, cb);
return false;
}
void data_block_manager_t::mark_garbage(off64_t offset) {
unsigned int extent_id = (offset / extent_manager->extent_size);
unsigned int block_id = (offset % extent_manager->extent_size) / block_size;
if ((gc_state.step == gc_read || gc_state.step == gc_write)
&& gc_state.current_entry.offset / extent_manager->extent_size == extent_id)
{
gc_state.current_entry.g_array.set(block_id, 1);
gc_stats.unyoung_garbage_blocks++;
} else {
assert(entries.get(extent_id));
entries.get(extent_id)->data.g_array.set(block_id, 1);
entries.get(extent_id)->update();
gc_stats.unyoung_garbage_blocks += !(entries.get(extent_id)->data.young);
}
}
void data_block_manager_t::start_reconstruct() {
gc_state.step = gc_reconstruct;
}
// Marks the block at the given offset as alive, in the appropriate
// gc_entry in the entries table. (This is used when we start up, when
// everything is presumed to be garbage, until we mark it as
// non-garbage.)
void data_block_manager_t::mark_live(off64_t offset) {
assert(gc_state.step == gc_reconstruct); // This is called at startup.
unsigned int extent_id = (offset / extent_manager->extent_size);
unsigned int block_id = (offset % extent_manager->extent_size) / block_size;
if (entries.get(extent_id) == NULL) {
gc_entry entry;
entry.init(extent_id * extent_manager->extent_size, false, false);
entry.g_array.set(); //set everything to garbage
entries.set(extent_id, gc_pq.push(entry));
// All are deemed garbage, and the block is not young.
gc_stats.unyoung_total_blocks += extent_manager->extent_size / BTREE_BLOCK_SIZE;
gc_stats.unyoung_garbage_blocks += extent_manager->extent_size / BTREE_BLOCK_SIZE;
}
/* mark the block as alive */
entries.get(extent_id)->data.g_array.set(block_id, 0);
// The block should never be young because we're reconstructing.
assert(!(entries.get(extent_id)->data.young));
gc_stats.unyoung_garbage_blocks--;
}
void data_block_manager_t::end_reconstruct() {
for (unsigned int i = blocks_in_last_data_extent; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++)
mark_live(last_data_extent + (BTREE_BLOCK_SIZE * i));
gc_state.step = gc_ready;
}
void data_block_manager_t::start_gc() {
if (gc_state.step == gc_ready)
run_gc();
}
/* TODO this currently cleans extent by extent, we should tune it to always have a certain number of outstanding blocks
*/
void data_block_manager_t::run_gc() {
do {
bool fallthrough;
switch (gc_state.step) {
case gc_ready:
fallthrough = false;
//TODO, need to make sure we don't gc the extent we're writing to
if (should_we_keep_gcing(gc_pq.peak())) {
/* grab the entry */
gc_state.current_entry = gc_pq.pop();
// The reason why the GC deletes the entries instead of the PQ deleting them
// is in case we get a write to the block we are GCing.
gdelete(entries.get(gc_state.current_entry.offset / extent_manager->extent_size));
entries.set(gc_state.current_entry.offset / extent_manager->extent_size, NULL);
/* read all the live data into buffers */
/* make sure the read callback knows who we are */
gc_state.gc_read_callback.parent = this;
for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) {
if (!gc_state.current_entry.g_array[i]) {
dbfile->read_async(
gc_state.current_entry.offset + (i * block_size),
block_size,
gc_state.gc_blocks + (i * block_size),
&(gc_state.gc_read_callback));
gc_state.refcount++;
gc_state.blocks_copying++;
}
}
gc_state.step = gc_read;
if (gc_state.refcount == 0)
fallthrough = true;
} else {
return;
}
if (!fallthrough)
break;
case gc_read:
fallthrough = false;
/* refcount can == 0 here if we fell through */
gc_state.refcount--;
if (gc_state.refcount <= 0) {
/* we can get here with a refcount of 0 */
gc_state.refcount = 0;
/* check if blocks need to be copied */
if (gc_state.current_entry.g_array.count() < gc_state.current_entry.g_array.size()) {
/* an array to put our writes in */
log_serializer_t::write_t writes[gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count()];
int nwrites = 0;
for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) {
if (!gc_state.current_entry.g_array[i]) {
writes[nwrites].block_id = *((ser_block_id_t *) (gc_state.gc_blocks + (i * block_size)));
writes[nwrites].buf = gc_state.gc_blocks + (i * block_size);
writes[nwrites].callback = NULL;
nwrites++;
}
}
/* make sure the callback knows who we are */
gc_state.gc_write_callback.parent = this;
/* release the gc'ed extent (it's safe because
* the extent manager will ensure it won't be
* given away until the metablock is
* written) */
extent_manager->release_extent(gc_state.current_entry.offset);
/* schedule the write */
fallthrough = serializer->do_write(writes, gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count() , (log_serializer_t::write_txn_callback_t *) &gc_state.gc_write_callback);
} else {
fallthrough = true;
}
gc_state.step = gc_write;
}
if (!fallthrough)
break;
case gc_write:
//not valid when writes are asynchronous (it would be nice if we could have this)
assert(gc_state.current_entry.g_array.count() == gc_state.current_entry.g_array.size()); //Checks if everything in the array has been marked as garbage
assert(entries.get(gc_state.current_entry.offset / extent_manager->extent_size) == NULL);
assert(gc_state.refcount == 0);
gc_state.blocks_copying = 0;
gc_state.step = gc_ready;
/* update stats */
gc_stats.unyoung_total_blocks -= extent_manager->extent_size / BTREE_BLOCK_SIZE;
gc_stats.unyoung_garbage_blocks -= extent_manager->extent_size / BTREE_BLOCK_SIZE;
if(state == state_shutting_down) {
// The state = state_shut_down must happen
// _before_ the shutdown_callback is called.
state = state_shut_down;
if(shutdown_callback)
shutdown_callback->on_datablock_manager_shutdown();
return;
}
break;
default:
fail("Unknown gc_step");
break;
}
} while (gc_state.step == gc_ready);
}
void data_block_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert(state == state_ready
|| (state == state_shutting_down && gc_state.step == gc_read));
metablock->last_data_extent = last_data_extent;
metablock->blocks_in_last_data_extent = blocks_in_last_data_extent;
}
bool data_block_manager_t::shutdown(shutdown_callback_t *cb) {
assert(cb);
assert(state == state_ready);
if(gc_state.step != gc_ready) {
state = state_shutting_down;
shutdown_callback = cb;
return false;
}
state = state_shut_down;
return true;
}
off64_t data_block_manager_t::gimme_a_new_offset() {
if (blocks_in_last_data_extent == extent_manager->extent_size / block_size) {
/* deactivate the last extent */
entries.get(last_data_extent / extent_manager->extent_size)->data.active = false;
entries.get(last_data_extent / extent_manager->extent_size)->update();
last_data_extent = extent_manager->gen_extent();
blocks_in_last_data_extent = 0;
add_gc_entry();
}
off64_t offset = last_data_extent + blocks_in_last_data_extent * block_size;
blocks_in_last_data_extent ++;
return offset;
}
void data_block_manager_t::add_gc_entry() {
gc_entry entry;
entry.init(last_data_extent, true, true);
unsigned int extent_id = last_data_extent / extent_manager->extent_size;
assert(entries.get(extent_id) == NULL);
priority_queue_t<gc_entry, Less>::entry_t *pq_entry = gc_pq.push(entry);
entries.set(extent_id, pq_entry);
// update young_extent_queue
young_extent_queue.push(pq_entry);
mark_unyoung_entries();
}
// Looks at young_extent_queue and pops things off the queue that are
// no longer deemed young, marking them as not young.
void data_block_manager_t::mark_unyoung_entries() {
while (young_extent_queue.size() > GC_YOUNG_EXTENT_MAX_SIZE) {
remove_last_unyoung_entry();
}
gc_entry::timestamp_t current_time = gc_entry::current_timestamp();
while (!young_extent_queue.empty()
&& current_time - young_extent_queue.front()->data.timestamp > GC_YOUNG_EXTENT_TIMELIMIT_MICROS) {
remove_last_unyoung_entry();
}
}
// Pops young_extent_queue and marks the popped entry as unyoung.
// Assumes young_extent_queue is not empty.
void data_block_manager_t::remove_last_unyoung_entry() {
assert(!young_extent_queue.empty());
priority_queue_t<gc_entry, Less>::entry_t *pq_entry = young_extent_queue.front();
young_extent_queue.pop();
pq_entry->data.young = false;
pq_entry->update();
gc_stats.unyoung_total_blocks += extent_manager->extent_size / BTREE_BLOCK_SIZE;
gc_stats.unyoung_garbage_blocks += pq_entry->data.g_array.count();
}
/* functions for gc structures */
// Right now we start gc'ing when the garbage ratio is >= 0.75 (75%
// garbage) and we gc all blocks with that ratio or higher.
// Answers the following question: We're in the middle of gc'ing, and
// look, it's the next largest entry. Should we keep gc'ing? Returns
// false when the entry is active or young, or when its garbage ratio
// is lower than GC_THRESHOLD_RATIO_*.
bool data_block_manager_t::should_we_keep_gcing(const gc_entry& entry) const {
return !entry.active && !entry.young && entry.g_array.count() * GC_THRESHOLD_RATIO_DENOMINATOR >= ((extent_manager->extent_size / BTREE_BLOCK_SIZE) * GC_THRESHOLD_RATIO_NUMERATOR);
}
// Answers the following question: Do we want to bother gc'ing?
// Returns true when our garbage_ratio is greater than
// GC_THRESHOLD_RATIO_*.
bool data_block_manager_t::do_we_want_to_start_gcing() const {
return gc_stats.unyoung_garbage_blocks * GC_THRESHOLD_RATIO_DENOMINATOR >= GC_THRESHOLD_RATIO_NUMERATOR * gc_stats.unyoung_total_blocks;
}
/* !< is x less than y */
bool data_block_manager_t::Less::operator() (const data_block_manager_t::gc_entry x, const data_block_manager_t::gc_entry y) {
if (x.active || x.young)
return true;
else if (y.active || y.young)
return false;
else
return x.g_array.count() < y.g_array.count();
}
/****************
*Stat functions*
****************/
// This will return NaN when gc_stats.unyoung_total_blocks is zero.
float data_block_manager_t::garbage_ratio() {
// TODO: not divide by zero?
return (float) gc_stats.unyoung_garbage_blocks / (float) gc_stats.unyoung_total_blocks;
}
<|endoftext|> |
<commit_before>/**
* @file data.cpp
* Implementation of the AppData class.
*
* @author Andrew Mass
* @date Created: 2014-07-12
* @date Modified: 2015-06-07
*/
#include "data.h"
bool AppData::readData(bool isVectorFile) {
return isVectorFile ? readDataVector() : readDataCustom();
}
bool AppData::readDataCustom() {
ifstream infile(this->filename.toLocal8Bit().data(), ios::in | ios::binary);
if(infile && infile.good()) {
infile.seekg(0, infile.end);
int length = infile.tellg();
infile.seekg(0, infile.beg);
char * bufferSigned = new char[length];
infile.read(bufferSigned, length);
unsigned char * buffer = (unsigned char *) bufferSigned;
bufferSigned = NULL;
if(!infile || !infile.good()) {
emit error("Problem reading input file. Try again or try another file.");
return false;
}
infile.close();
processBuffer(buffer, length);
return true;
} else {
emit error("Problem with input file. Try again or try another file.");
return false;
}
}
bool AppData::readDataVector() {
QFile inputFile(this->filename);
if(inputFile.open(QIODevice::ReadOnly)) {
QTextStream inputStream(&inputFile);
inputStream.readLine();
int lineCounter = 0;
while(!inputStream.atEnd()) {
inputStream.readLine();
lineCounter++;
}
inputStream.seek(0);
int progressCounter = 0;
int iter = 0;
inputStream.readLine();
while(!inputStream.atEnd()) {
QString line = inputStream.readLine();
if(!line.isEmpty()) {
processLine(line.simplified());
}
if((((double) iter++) / ((double) lineCounter)) * 100.0 > progressCounter) {
emit progress(++progressCounter);
}
}
inputFile.close();
return true;
}
emit error("Problem with input file. Try again or try another file.");
return false;
}
bool AppData::coalesceLogfiles(QStringList filenames) {
filenames.sort();
QStringList info = filenames.at(0).split("/");
QString firstFileNum = info.at(info.size() - 1).split(".").at(0);
QString lastFileName = filenames.at(filenames.size() - 1);
info = lastFileName.split("/");
QString lastFileNum = info.at(info.size() - 1).split(".").at(0);
QString directory = lastFileName.left(lastFileName.lastIndexOf('/') + 1);
QString outFilename = QString("%1coalesce-%2-%3.txt").arg(directory)
.arg(firstFileNum).arg(lastFileNum);
ofstream outFile(outFilename.toLocal8Bit().data(), ios::out | ios::trunc);
if(outFile && outFile.good()) {
QString header;
QFile firstFile(filenames.at(0));
if(firstFile.open(QIODevice::ReadOnly)) {
QTextStream inputStream(&firstFile);
header = inputStream.readLine();
QString adjHeader = QString("%1 %2 %3").arg(header.section(" ", 0, 0)).arg("Logfile [file]")
.arg(header.section(" ", 1));
outFile << adjHeader.toLocal8Bit().data() << '\n';
firstFile.close();
}
double latestTimestamp = -LOGFILE_COALESCE_SEPARATION;
for(int i = 0; i < filenames.size(); i++) {
emit progress((((double) i) / filenames.size()) * 100.0);
info = filenames.at(i).split("/");
QString logNum = info.at(info.size() - 1).split(".").at(0);
QFile inputFile(filenames.at(i));
if(inputFile.open(QIODevice::ReadOnly)) {
QTextStream inputStream(&inputFile);
if(QString::compare(header, inputStream.readLine())) {
emit error("Header mismatch. All logfiles must have the same headers.");
outFile.close();
return false;
}
QString firstLine = inputStream.readLine();
double firstTimestamp = firstLine.section(" ", 0, 0).toDouble();
firstLine = "0.0 " + firstLine.section(" ", 1);
outFile << firstLine.toLocal8Bit().data() << '\n';
latestTimestamp += LOGFILE_COALESCE_SEPARATION;
double timestampOffset = latestTimestamp;
while(!inputStream.atEnd()) {
QString line = inputStream.readLine();
double timestamp = line.section(" ", 0, 0).toDouble();
latestTimestamp = timestamp - firstTimestamp + timestampOffset;
line = QString("%1 %2 %3").arg(latestTimestamp).arg(logNum).arg(line.section(" ", 1));
outFile << line.toLocal8Bit().data() << '\n';
}
}
}
emit progress(100.0);
} else {
emit error("Problem opening output file.");
return false;
}
outFile.close();
return true;
}
bool AppData::writeAxis() {
QString outFilename = this->filename;
outFilename.replace(".txt", ".out.txt", Qt::CaseInsensitive);
ofstream outFile(outFilename.toLocal8Bit().data(), ios::out | ios::trunc);
if(outFile && outFile.good()) {
outFile << "xtime [s]";
latestValues.clear();
messageIndices.clear();
vector<double> vec_time;
vec_time.push_back(0.0);
latestValues.push_back(vec_time);
AppConfig config;
map<unsigned short, Message> messages = config.getMessages();
int indexCounter = 1;
typedef map<unsigned short, Message>::iterator it_msg;
for(it_msg msgIt = messages.begin(); msgIt != messages.end(); msgIt++) {
Message msg = msgIt->second;
vector<double> vec_msg;
vector<bool> msgEnabled = this->enabled[msg.id];
for(int i = 0; i < msg.channels.size(); i++) {
Channel chn = msg.channels[i];
if(msgEnabled[i]) {
outFile << " " << chn.title.toStdString() << " [" << chn.units.toStdString() << "]";
vec_msg.push_back(0.0);
}
}
latestValues.push_back(vec_msg);
messageIndices[msg.id] = indexCounter;
indexCounter++;
}
outFile.close();
return true;
} else {
emit error("Problem opening output file.");
return false;
}
}
void AppData::writeLine() {
QString outFilename = this->filename;
outFilename.replace(".txt", ".out.txt", Qt::CaseInsensitive);
ofstream outFile(outFilename.toLocal8Bit().data(), ios::out | ios::app);
if(outFile && outFile.good()) {
outFile << endl;
for(unsigned int i = 0; i < latestValues.size(); i++) {
for(unsigned int j = 0; j < latestValues[i].size(); j++) {
if(i != 0) {
outFile << " ";
}
outFile << latestValues[i][j];
}
}
outFile.close();
} else {
emit error(QString("Problem opening output file."));
}
}
void AppData::processBuffer(unsigned char * buffer, int length) {
AppConfig config;
map<unsigned short, Message> messages = config.getMessages();
emit progress(0);
int iter = 0;
int progressCounter = 0;
static int badMsgCounter = 0;
static int badTimeCounter = 0;
bool badMsgFound = false;
while(iter + 14 < length) {
if((((double) iter) / ((double) length)) * 100.0 > progressCounter) {
emit progress(++progressCounter);
}
unsigned short msgId = buffer[iter + 1] << 8 | buffer[iter];
iter += 2;
Message msg = messages[msgId];
if(msg.valid()) {
badMsgFound = false;
vector<bool> msgEnabled = this->enabled[msg.id];
int j = 0;
vector<double> values;
bool badChnFound = false;
for(int i = 0; i < msg.channels.size(); i++) {
Channel chn = msg.channels[i];
if(msgEnabled[i]) {
double value;
if(chn.isSigned) {
signed int data = msg.isBigEndian ?
buffer[iter] << 8 | buffer[iter + 1] : buffer[iter + 1] << 8 | buffer[iter];
value = (double) data;
} else {
unsigned int data = msg.isBigEndian ?
buffer[iter] << 8 | buffer[iter + 1] : buffer[iter + 1] << 8 | buffer[iter];
value = (double) data;
}
values.push_back((value - chn.offset) * chn.scalar);
// Check to see if the calculated value is out of range.
if(values[j] < chn.min || values[j] > chn.max) {
badChnFound = true;
}
j++;
}
iter += 2;
}
if(badChnFound) {
// Skip this message and don't write to the file.
iter += 4;
continue;
}
double upper = buffer[iter + 3] << 8 | buffer[iter + 2];
double lower = ((double) (buffer[iter + 1] << 8 | buffer[iter])) / 0x8000;
double timestamp = upper + lower - 1.0;
iter += 4;
/**
* We were experiencing problems with corrupt messages (or messages not understood by the
* translator interpreted as being corrupt) screwing up the natural, increasing order of
* timestamps in the logfile. This would cause the conversion to darab format to fail. This
* if statement checks to make sure the newly calculated timestamp within a small range of
* time in either direction.
*/
if(latestValues[0][0] == 0.0 || abs(timestamp - latestValues[0][0]) <= 1.0) {
latestValues[0][0] = timestamp;
for(int i = 0; i < j; i++) {
latestValues[messageIndices[msg.id]][i] = values[i];
}
writeLine();
} else {
if(++badTimeCounter < 6) {
emit error(QString("Invalid timestamp: %1. Previous: %2.")
.arg(timestamp).arg(latestValues[0][0]));
} else if(badTimeCounter == 7) {
emit error(QString("Invalid timestamp maxed out."));
}
}
} else {
if(!badMsgFound) {
if(++badMsgCounter < 6) {
emit error(QString("Invalid msgId: %1").arg(msgId, 0, 16));
} else if(badMsgCounter == 7) {
emit error(QString("Invalid msgId maxed out."));
}
}
badMsgFound = true;
iter += 2;
}
}
delete[] buffer;
buffer = NULL;
}
void AppData::processLine(QString line) {
AppConfig config;
map<unsigned short, Message> messages = config.getMessages();
QStringList sections = line.split(" ", QString::SkipEmptyParts);
if(sections.size() == 2 && sections[1].compare("Trigger") == 0) {
return;
}
if(sections.size() < 7) {
emit error("Invalid log file line.");
return;
}
bool successful = true;
unsigned short msgId;
msgId = sections[2].toUInt(&successful, 10);
if(!successful) {
emit error("Invalid message ID.");
return;
}
Message msg = messages[msgId];
if(msg.valid()) {
vector<bool> msgEnabled = this->enabled[msg.id];
int j = 0;
for(int i = 0; i < msg.channels.size(); i++) {
Channel chn = msg.channels[i];
if(msgEnabled[i]) {
double value;
successful = true;
unsigned char byteOne = sections[5 + (i * 2)].toUInt(&successful, 10);
unsigned char byteTwo = sections[5 + (i * 2) + 1].toUInt(&successful, 10);
if(!successful) {
emit error("Invalid channel data.");
return;
}
if(chn.isSigned) {
signed int data = msg.isBigEndian ? byteOne << 8 | byteTwo :
byteTwo << 8 | byteOne;
value = (double) data;
} else {
unsigned int data = msg.isBigEndian ? byteOne << 8 | byteTwo :
byteTwo << 8 | byteOne;
value = (double) data;
}
latestValues[messageIndices[msg.id]][j] = (value - chn.offset) * chn.scalar;
j++;
}
}
latestValues[0][0] = sections[0].toDouble();
writeLine();
} else {
//emit error(QString("Invalid msgId: %1").arg(msgId, 0, 16));
}
}
<commit_msg>Fix bug with empty logfiles and incorrect first line of each logfile.<commit_after>/**
* @file data.cpp
* Implementation of the AppData class.
*
* @author Andrew Mass
* @date Created: 2014-07-12
* @date Modified: 2015-06-07
*/
#include "data.h"
bool AppData::readData(bool isVectorFile) {
return isVectorFile ? readDataVector() : readDataCustom();
}
bool AppData::readDataCustom() {
ifstream infile(this->filename.toLocal8Bit().data(), ios::in | ios::binary);
if(infile && infile.good()) {
infile.seekg(0, infile.end);
int length = infile.tellg();
infile.seekg(0, infile.beg);
char * bufferSigned = new char[length];
infile.read(bufferSigned, length);
unsigned char * buffer = (unsigned char *) bufferSigned;
bufferSigned = NULL;
if(!infile || !infile.good()) {
emit error("Problem reading input file. Try again or try another file.");
return false;
}
infile.close();
processBuffer(buffer, length);
return true;
} else {
emit error("Problem with input file. Try again or try another file.");
return false;
}
}
bool AppData::readDataVector() {
QFile inputFile(this->filename);
if(inputFile.open(QIODevice::ReadOnly)) {
QTextStream inputStream(&inputFile);
inputStream.readLine();
int lineCounter = 0;
while(!inputStream.atEnd()) {
inputStream.readLine();
lineCounter++;
}
inputStream.seek(0);
int progressCounter = 0;
int iter = 0;
inputStream.readLine();
while(!inputStream.atEnd()) {
QString line = inputStream.readLine();
if(!line.isEmpty()) {
processLine(line.simplified());
}
if((((double) iter++) / ((double) lineCounter)) * 100.0 > progressCounter) {
emit progress(++progressCounter);
}
}
inputFile.close();
return true;
}
emit error("Problem with input file. Try again or try another file.");
return false;
}
bool AppData::coalesceLogfiles(QStringList filenames) {
filenames.sort();
QStringList info = filenames.at(0).split("/");
QString firstFileNum = info.at(info.size() - 1).split(".").at(0);
QString lastFileName = filenames.at(filenames.size() - 1);
info = lastFileName.split("/");
QString lastFileNum = info.at(info.size() - 1).split(".").at(0);
QString directory = lastFileName.left(lastFileName.lastIndexOf('/') + 1);
QString outFilename = QString("%1coalesce-%2-%3.txt").arg(directory)
.arg(firstFileNum).arg(lastFileNum);
ofstream outFile(outFilename.toLocal8Bit().data(), ios::out | ios::trunc);
if(outFile && outFile.good()) {
QString header;
QFile firstFile(filenames.at(0));
if(firstFile.open(QIODevice::ReadOnly)) {
QTextStream inputStream(&firstFile);
header = inputStream.readLine();
QString adjHeader = QString("%1 %2 %3").arg(header.section(" ", 0, 0)).arg("Logfile [file]")
.arg(header.section(" ", 1));
outFile << adjHeader.toLocal8Bit().data() << '\n';
firstFile.close();
}
double latestTimestamp = -LOGFILE_COALESCE_SEPARATION;
for(int i = 0; i < filenames.size(); i++) {
emit progress((((double) i) / filenames.size()) * 100.0);
info = filenames.at(i).split("/");
QString logNum = info.at(info.size() - 1).split(".").at(0);
QFile inputFile(filenames.at(i));
if(inputFile.open(QIODevice::ReadOnly)) {
QTextStream inputStream(&inputFile);
if(QString::compare(header, inputStream.readLine())) {
emit error("Header mismatch. All logfiles must have the same headers.");
outFile.close();
return false;
}
if(inputStream.atEnd()) {
continue;
}
QString firstLine = inputStream.readLine();
double firstTimestamp = firstLine.section(" ", 0, 0).toDouble();
firstLine = QString("0.0 %1 %2").arg(logNum).arg(firstLine.section(" ", 1));
outFile << firstLine.toLocal8Bit().data() << '\n';
latestTimestamp += LOGFILE_COALESCE_SEPARATION;
double timestampOffset = latestTimestamp;
while(!inputStream.atEnd()) {
QString line = inputStream.readLine();
double timestamp = line.section(" ", 0, 0).toDouble();
latestTimestamp = timestamp - firstTimestamp + timestampOffset;
line = QString("%1 %2 %3").arg(latestTimestamp).arg(logNum).arg(line.section(" ", 1));
outFile << line.toLocal8Bit().data() << '\n';
}
}
}
emit progress(100.0);
} else {
emit error("Problem opening output file.");
return false;
}
outFile.close();
return true;
}
bool AppData::writeAxis() {
QString outFilename = this->filename;
outFilename.replace(".txt", ".out.txt", Qt::CaseInsensitive);
ofstream outFile(outFilename.toLocal8Bit().data(), ios::out | ios::trunc);
if(outFile && outFile.good()) {
outFile << "xtime [s]";
latestValues.clear();
messageIndices.clear();
vector<double> vec_time;
vec_time.push_back(0.0);
latestValues.push_back(vec_time);
AppConfig config;
map<unsigned short, Message> messages = config.getMessages();
int indexCounter = 1;
typedef map<unsigned short, Message>::iterator it_msg;
for(it_msg msgIt = messages.begin(); msgIt != messages.end(); msgIt++) {
Message msg = msgIt->second;
vector<double> vec_msg;
vector<bool> msgEnabled = this->enabled[msg.id];
for(int i = 0; i < msg.channels.size(); i++) {
Channel chn = msg.channels[i];
if(msgEnabled[i]) {
outFile << " " << chn.title.toStdString() << " [" << chn.units.toStdString() << "]";
vec_msg.push_back(0.0);
}
}
latestValues.push_back(vec_msg);
messageIndices[msg.id] = indexCounter;
indexCounter++;
}
outFile.close();
return true;
} else {
emit error("Problem opening output file.");
return false;
}
}
void AppData::writeLine() {
QString outFilename = this->filename;
outFilename.replace(".txt", ".out.txt", Qt::CaseInsensitive);
ofstream outFile(outFilename.toLocal8Bit().data(), ios::out | ios::app);
if(outFile && outFile.good()) {
outFile << endl;
for(unsigned int i = 0; i < latestValues.size(); i++) {
for(unsigned int j = 0; j < latestValues[i].size(); j++) {
if(i != 0) {
outFile << " ";
}
outFile << latestValues[i][j];
}
}
outFile.close();
} else {
emit error(QString("Problem opening output file."));
}
}
void AppData::processBuffer(unsigned char * buffer, int length) {
AppConfig config;
map<unsigned short, Message> messages = config.getMessages();
emit progress(0);
int iter = 0;
int progressCounter = 0;
static int badMsgCounter = 0;
static int badTimeCounter = 0;
bool badMsgFound = false;
while(iter + 14 < length) {
if((((double) iter) / ((double) length)) * 100.0 > progressCounter) {
emit progress(++progressCounter);
}
unsigned short msgId = buffer[iter + 1] << 8 | buffer[iter];
iter += 2;
Message msg = messages[msgId];
if(msg.valid()) {
badMsgFound = false;
vector<bool> msgEnabled = this->enabled[msg.id];
int j = 0;
vector<double> values;
bool badChnFound = false;
for(int i = 0; i < msg.channels.size(); i++) {
Channel chn = msg.channels[i];
if(msgEnabled[i]) {
double value;
if(chn.isSigned) {
signed int data = msg.isBigEndian ?
buffer[iter] << 8 | buffer[iter + 1] : buffer[iter + 1] << 8 | buffer[iter];
value = (double) data;
} else {
unsigned int data = msg.isBigEndian ?
buffer[iter] << 8 | buffer[iter + 1] : buffer[iter + 1] << 8 | buffer[iter];
value = (double) data;
}
values.push_back((value - chn.offset) * chn.scalar);
// Check to see if the calculated value is out of range.
if(values[j] < chn.min || values[j] > chn.max) {
badChnFound = true;
}
j++;
}
iter += 2;
}
if(badChnFound) {
// Skip this message and don't write to the file.
iter += 4;
continue;
}
double upper = buffer[iter + 3] << 8 | buffer[iter + 2];
double lower = ((double) (buffer[iter + 1] << 8 | buffer[iter])) / 0x8000;
double timestamp = upper + lower - 1.0;
iter += 4;
/**
* We were experiencing problems with corrupt messages (or messages not understood by the
* translator interpreted as being corrupt) screwing up the natural, increasing order of
* timestamps in the logfile. This would cause the conversion to darab format to fail. This
* if statement checks to make sure the newly calculated timestamp within a small range of
* time in either direction.
*/
if(latestValues[0][0] == 0.0 || abs(timestamp - latestValues[0][0]) <= 1.0) {
latestValues[0][0] = timestamp;
for(int i = 0; i < j; i++) {
latestValues[messageIndices[msg.id]][i] = values[i];
}
writeLine();
} else {
if(++badTimeCounter < 6) {
emit error(QString("Invalid timestamp: %1. Previous: %2.")
.arg(timestamp).arg(latestValues[0][0]));
} else if(badTimeCounter == 7) {
emit error(QString("Invalid timestamp maxed out."));
}
}
} else {
if(!badMsgFound) {
if(++badMsgCounter < 6) {
emit error(QString("Invalid msgId: %1").arg(msgId, 0, 16));
} else if(badMsgCounter == 7) {
emit error(QString("Invalid msgId maxed out."));
}
}
badMsgFound = true;
iter += 2;
}
}
delete[] buffer;
buffer = NULL;
}
void AppData::processLine(QString line) {
AppConfig config;
map<unsigned short, Message> messages = config.getMessages();
QStringList sections = line.split(" ", QString::SkipEmptyParts);
if(sections.size() == 2 && sections[1].compare("Trigger") == 0) {
return;
}
if(sections.size() < 7) {
emit error("Invalid log file line.");
return;
}
bool successful = true;
unsigned short msgId;
msgId = sections[2].toUInt(&successful, 10);
if(!successful) {
emit error("Invalid message ID.");
return;
}
Message msg = messages[msgId];
if(msg.valid()) {
vector<bool> msgEnabled = this->enabled[msg.id];
int j = 0;
for(int i = 0; i < msg.channels.size(); i++) {
Channel chn = msg.channels[i];
if(msgEnabled[i]) {
double value;
successful = true;
unsigned char byteOne = sections[5 + (i * 2)].toUInt(&successful, 10);
unsigned char byteTwo = sections[5 + (i * 2) + 1].toUInt(&successful, 10);
if(!successful) {
emit error("Invalid channel data.");
return;
}
if(chn.isSigned) {
signed int data = msg.isBigEndian ? byteOne << 8 | byteTwo :
byteTwo << 8 | byteOne;
value = (double) data;
} else {
unsigned int data = msg.isBigEndian ? byteOne << 8 | byteTwo :
byteTwo << 8 | byteOne;
value = (double) data;
}
latestValues[messageIndices[msg.id]][j] = (value - chn.offset) * chn.scalar;
j++;
}
}
latestValues[0][0] = sections[0].toDouble();
writeLine();
} else {
//emit error(QString("Invalid msgId: %1").arg(msgId, 0, 16));
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <dsp/common.hpp>
namespace rack {
namespace dsp {
/** The simplest possible analog filter using an Euler solver.
https://en.wikipedia.org/wiki/RC_circuit
Use two RC filters in series for a bandpass filter.
*/
template <typename T = float>
struct TRCFilter {
T c = 0.f;
T xstate[1];
T ystate[1];
TRCFilter() {
reset();
}
void reset() {
xstate[0] = 0.f;
ystate[0] = 0.f;
}
/** Sets the cutoff angular frequency in radians.
*/
void setCutoff(T r) {
c = 2.f / r;
}
/** Sets the cutoff frequency.
`f` is the ratio between the cutoff frequency and sample rate, i.e. f = f_c / f_s
*/
void setCutoffFreq(T f) {
setCutoff(2.f * M_PI * f);
}
void process(T x) {
T y = (x + xstate[0] - ystate[0] * (1 - c)) / (1 + c);
xstate[0] = x;
ystate[0] = y;
}
T lowpass() {
return ystate[0];
}
T highpass() {
return xstate[0] - ystate[0];
}
};
typedef TRCFilter<> RCFilter;
/** Applies exponential smoothing to a signal with the ODE
\f$ \frac{dy}{dt} = x \lambda \f$.
*/
template <typename T = float>
struct TExponentialFilter {
T out = 0.f;
T lambda = 0.f;
void reset() {
out = 0.f;
}
void setLambda(T lambda) {
this->lambda = lambda;
}
T process(T deltaTime, T in) {
T y = out + (in - out) * lambda * deltaTime;
// If no change was made between the old and new output, assume T granularity is too small and snap output to input
out = simd::ifelse(out == y, in, y);
return out;
}
DEPRECATED T process(T in) {
return process(1.f, in);
}
};
typedef TExponentialFilter<> ExponentialFilter;
/** Like ExponentialFilter but jumps immediately to higher values.
*/
template <typename T = float>
struct TPeakFilter {
T out = 0.f;
T lambda = 0.f;
void reset() {
out = 0.f;
}
void setLambda(T lambda) {
this->lambda = lambda;
}
T process(T deltaTime, T in) {
T y = out + (in - out) * lambda * deltaTime;
out = simd::fmax(y, in);
return out;
}
/** Use the return value of process() instead. */
DEPRECATED T peak() {
return out;
}
/** Use setLambda() instead. */
DEPRECATED void setRate(T r) {
lambda = 1.f - r;
}
DEPRECATED T process(T x) {
return process(1.f, x);
}
};
typedef TPeakFilter<> PeakFilter;
template <typename T = float>
struct TSlewLimiter {
T out = 0.f;
T rise = 0.f;
T fall = 0.f;
void reset() {
out = 0.f;
}
void setRiseFall(T rise, T fall) {
this->rise = rise;
this->fall = fall;
}
T process(T deltaTime, T in) {
out = simd::clamp(in, out - fall * deltaTime, out + rise * deltaTime);
return out;
}
DEPRECATED T process(T in) {
return process(1.f, in);
}
};
typedef TSlewLimiter<> SlewLimiter;
template <typename T = float>
struct TExponentialSlewLimiter {
T out = 0.f;
T riseLambda = 0.f;
T fallLambda = 0.f;
void reset() {
out = 0.f;
}
void setRiseFall(T riseLambda, T fallLambda) {
this->riseLambda = riseLambda;
this->fallLambda = fallLambda;
}
T process(T deltaTime, T in) {
T lambda = simd::ifelse(in > out, riseLambda, fallLambda);
T y = out + (in - out) * lambda * deltaTime;
// If the change from the old out to the new out is too small for floats, set `in` directly.
out = simd::ifelse(out == y, in, y);
return out;
}
DEPRECATED T process(T in) {
return process(1.f, in);
}
};
typedef TExponentialSlewLimiter<> ExponentialSlewLimiter;
} // namespace dsp
} // namespace rack
<commit_msg>Add dsp::BiquadFilter.<commit_after>#pragma once
#include <dsp/common.hpp>
namespace rack {
namespace dsp {
/** The simplest possible analog filter using an Euler solver.
https://en.wikipedia.org/wiki/RC_circuit
Use two RC filters in series for a bandpass filter.
*/
template <typename T = float>
struct TRCFilter {
T c = 0.f;
T xstate[1];
T ystate[1];
TRCFilter() {
reset();
}
void reset() {
xstate[0] = 0.f;
ystate[0] = 0.f;
}
/** Sets the cutoff angular frequency in radians.
*/
void setCutoff(T r) {
c = 2.f / r;
}
/** Sets the cutoff frequency.
`f` is the ratio between the cutoff frequency and sample rate, i.e. f = f_c / f_s
*/
void setCutoffFreq(T f) {
setCutoff(2.f * M_PI * f);
}
void process(T x) {
T y = (x + xstate[0] - ystate[0] * (1 - c)) / (1 + c);
xstate[0] = x;
ystate[0] = y;
}
T lowpass() {
return ystate[0];
}
T highpass() {
return xstate[0] - ystate[0];
}
};
typedef TRCFilter<> RCFilter;
/** Applies exponential smoothing to a signal with the ODE
\f$ \frac{dy}{dt} = x \lambda \f$.
*/
template <typename T = float>
struct TExponentialFilter {
T out = 0.f;
T lambda = 0.f;
void reset() {
out = 0.f;
}
void setLambda(T lambda) {
this->lambda = lambda;
}
T process(T deltaTime, T in) {
T y = out + (in - out) * lambda * deltaTime;
// If no change was made between the old and new output, assume T granularity is too small and snap output to input
out = simd::ifelse(out == y, in, y);
return out;
}
DEPRECATED T process(T in) {
return process(1.f, in);
}
};
typedef TExponentialFilter<> ExponentialFilter;
/** Like ExponentialFilter but jumps immediately to higher values.
*/
template <typename T = float>
struct TPeakFilter {
T out = 0.f;
T lambda = 0.f;
void reset() {
out = 0.f;
}
void setLambda(T lambda) {
this->lambda = lambda;
}
T process(T deltaTime, T in) {
T y = out + (in - out) * lambda * deltaTime;
out = simd::fmax(y, in);
return out;
}
/** Use the return value of process() instead. */
DEPRECATED T peak() {
return out;
}
/** Use setLambda() instead. */
DEPRECATED void setRate(T r) {
lambda = 1.f - r;
}
DEPRECATED T process(T x) {
return process(1.f, x);
}
};
typedef TPeakFilter<> PeakFilter;
template <typename T = float>
struct TSlewLimiter {
T out = 0.f;
T rise = 0.f;
T fall = 0.f;
void reset() {
out = 0.f;
}
void setRiseFall(T rise, T fall) {
this->rise = rise;
this->fall = fall;
}
T process(T deltaTime, T in) {
out = simd::clamp(in, out - fall * deltaTime, out + rise * deltaTime);
return out;
}
DEPRECATED T process(T in) {
return process(1.f, in);
}
};
typedef TSlewLimiter<> SlewLimiter;
template <typename T = float>
struct TExponentialSlewLimiter {
T out = 0.f;
T riseLambda = 0.f;
T fallLambda = 0.f;
void reset() {
out = 0.f;
}
void setRiseFall(T riseLambda, T fallLambda) {
this->riseLambda = riseLambda;
this->fallLambda = fallLambda;
}
T process(T deltaTime, T in) {
T lambda = simd::ifelse(in > out, riseLambda, fallLambda);
T y = out + (in - out) * lambda * deltaTime;
// If the change from the old out to the new out is too small for floats, set `in` directly.
out = simd::ifelse(out == y, in, y);
return out;
}
DEPRECATED T process(T in) {
return process(1.f, in);
}
};
typedef TExponentialSlewLimiter<> ExponentialSlewLimiter;
template <typename T = float>
struct TBiquadFilter {
/** input state */
T x[2];
/** output state */
T y[2];
/** transfer function denominator coefficients: a_1, a_2
a_0 is fixed to 1.
*/
float a[2];
/** transfer function numerator coefficients: b_0, b_1, b_2 */
float b[3];
enum Type {
LOWPASS_1POLE,
HIGHPASS_1POLE,
LOWPASS,
HIGHPASS,
LOWSHELF,
HIGHSHELF,
BANDPASS,
PEAK,
NOTCH,
NUM_TYPES
};
Type type = LOWPASS;
TBiquadFilter() {
reset();
setParameters(0.f, 0.f, 1.f);
}
void reset() {
std::memset(x, 0, sizeof(x));
std::memset(y, 0, sizeof(y));
}
T process(T in) {
// Advance IIR
T out =
b[0] * in
+ b[1] * x[0]
+ b[2] * x[1]
- a[0] * y[0]
- a[1] * y[1];
// Push input
x[1] = x[0];
x[0] = in;
// Push output
y[1] = y[0];
y[0] = out;
return out;
}
/** Calculates and sets the biquad transfer function coefficients.
f: normalized frequency (cutoff frequency / sample rate), must be less than 0.5
Q: quality factor
V: gain
*/
void setParameters(float f, float Q, float V) {
float K = std::tan(M_PI * f);
switch (type) {
case LOWPASS_1POLE: {
a[0] = -std::exp(-2.f * M_PI * f);
a[1] = 0.f;
b[0] = 1.f + a[0];
b[1] = 0.f;
b[2] = 0.f;
} break;
case HIGHPASS_1POLE: {
a[0] = std::exp(-2.f * M_PI * (0.5f - f));
a[1] = 0.f;
b[0] = 1.f - a[0];
b[1] = 0.f;
b[2] = 0.f;
} break;
case LOWPASS: {
float norm = 1.f / (1.f + K / Q + K * K);
b[0] = K * K * norm;
b[1] = 2.f * b[0];
b[2] = b[0];
a[0] = 2.f * (K * K - 1.f) * norm;
a[1] = (1.f - K / Q + K * K) * norm;
} break;
case HIGHPASS: {
float norm = 1.f / (1.f + K / Q + K * K);
b[0] = norm;
b[1] = -2.f * b[0];
b[2] = b[0];
a[0] = 2.f * (K * K - 1.f) * norm;
a[1] = (1.f - K / Q + K * K) * norm;
} break;
case LOWSHELF: {
float sqrtV = std::sqrt(V);
if (V >= 1.f) {
float norm = 1.f / (1.f + M_SQRT2 * K + K * K);
b[0] = (1.f + M_SQRT2 * sqrtV * K + V * K * K) * norm;
b[1] = 2.f * (V * K * K - 1.f) * norm;
b[2] = (1.f - M_SQRT2 * sqrtV * K + V * K * K) * norm;
a[0] = 2.f * (K * K - 1.f) * norm;
a[1] = (1.f - M_SQRT2 * K + K * K) * norm;
}
else {
float norm = 1.f / (1.f + M_SQRT2 / sqrtV * K + K * K / V);
b[0] = (1.f + M_SQRT2 * K + K * K) * norm;
b[1] = 2.f * (K * K - 1) * norm;
b[2] = (1.f - M_SQRT2 * K + K * K) * norm;
a[0] = 2.f * (K * K / V - 1.f) * norm;
a[1] = (1.f - M_SQRT2 / sqrtV * K + K * K / V) * norm;
}
} break;
case HIGHSHELF: {
float sqrtV = std::sqrt(V);
if (V >= 1.f) {
float norm = 1.f / (1.f + M_SQRT2 * K + K * K);
b[0] = (V + M_SQRT2 * sqrtV * K + K * K) * norm;
b[1] = 2.f * (K * K - V) * norm;
b[2] = (V - M_SQRT2 * sqrtV * K + K * K) * norm;
a[0] = 2.f * (K * K - 1.f) * norm;
a[1] = (1.f - M_SQRT2 * K + K * K) * norm;
}
else {
float norm = 1.f / (1.f / V + M_SQRT2 / sqrtV * K + K * K);
b[0] = (1.f + M_SQRT2 * K + K * K) * norm;
b[1] = 2.f * (K * K - 1.f) * norm;
b[2] = (1.f - M_SQRT2 * K + K * K) * norm;
a[0] = 2.f * (K * K - 1.f / V) * norm;
a[1] = (1.f / V - M_SQRT2 / sqrtV * K + K * K) * norm;
}
} break;
case BANDPASS: {
float norm = 1.f / (1.f + K / Q + K * K);
b[0] = K / Q * norm;
b[1] = 0.f;
b[2] = -b[0];
a[0] = 2.f * (K * K - 1.f) * norm;
a[1] = (1.f - K / Q + K * K) * norm;
} break;
case PEAK: {
if (V >= 1.f) {
float norm = 1.f / (1.f + K / Q + K * K);
b[0] = (1.f + K / Q * V + K * K) * norm;
b[1] = 2.f * (K * K - 1.f) * norm;
b[2] = (1.f - K / Q * V + K * K) * norm;
a[0] = b[1];
a[1] = (1.f - K / Q + K * K) * norm;
}
else {
float norm = 1.f / (1.f + K / Q / V + K * K);
b[0] = (1.f + K / Q + K * K) * norm;
b[1] = 2.f * (K * K - 1.f) * norm;
b[2] = (1.f - K / Q + K * K) * norm;
a[0] = b[1];
a[1] = (1.f - K / Q / V + K * K) * norm;
}
} break;
case NOTCH: {
float norm = 1.f / (1.f + K / Q + K * K);
b[0] = (1.f + K * K) * norm;
b[1] = 2.f * (K * K - 1.f) * norm;
b[2] = b[0];
a[0] = b[1];
a[1] = (1.f - K / Q + K * K) * norm;
} break;
default: break;
}
}
/** Computes the gain of a particular frequency
f: normalized frequency
*/
float getFrequencyResponse(float f) {
float br = b[0];
float bi = 0.f;
float ar = 1.f;
float ai = 0.f;
for (int i = 1; i < 3; i++) {
float er = std::cos(2 * M_PI * -i * f);
float ei = std::sin(2 * M_PI * -i * f);
br += b[i] * er;
bi += b[i] * ei;
ar += a[i - 1] * er;
ai += a[i - 1] * ei;
}
// Compute |b / a|
float cr = (br * ar + bi * ai) / (ar * ar + ai * ai);
float ci = (bi * ar - br * ai) / (ar * ar + ai * ai);
return std::hypot(cr, ci);
}
};
typedef TBiquadFilter<> BiquadFilter;
} // namespace dsp
} // namespace rack
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xbf;
pchMessageStart[1] = 0xf4;
pchMessageStart[2] = 0x1a;
pchMessageStart[3] = 0xb6;
vAlertPubKey = ParseHex("");
nDefaultPort = 58273;
nRPCPort = 59273;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
const char* pszTimestamp = "ISIS terror attacks in Brussels";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1458750507, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1458750507;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 468977;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000001a7bb3214e3e1d2e4c256082b817a3c5dff5def37456ae16d7edaa508be"));
assert(genesis.hashMerkleRoot == uint256("0xa1de9df44936bd1dd483e217fa17ec1881d2caf741ca67a33f6cd6850183078c"));
vSeeds.push_back(CDNSSeedData("45.32.211.127", "45.32.211.127"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(103);
base58Prefixes[SCRIPT_ADDRESS] = list_of(88);
base58Prefixes[SECRET_KEY] = list_of(153);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
nLastPOWBlock = 2000;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x5f;
pchMessageStart[1] = 0xf2;
pchMessageStart[2] = 0x15;
pchMessageStart[3] = 0x30;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("");
nDefaultPort = 51002;
nRPCPort = 51003;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 72686;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x0000070638e1fb122fb31b4753a5311f3c8784604d9f6ce42e8fec96d94173b4"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(127);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Error: use of overloaded operator '=' is ambiguous<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xbf;
pchMessageStart[1] = 0xf4;
pchMessageStart[2] = 0x1a;
pchMessageStart[3] = 0xb6;
vAlertPubKey = ParseHex("");
nDefaultPort = 58273;
nRPCPort = 59273;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
const char* pszTimestamp = "ISIS terror attacks in Brussels";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1458750507, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1458750507;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 468977;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x000001a7bb3214e3e1d2e4c256082b817a3c5dff5def37456ae16d7edaa508be"));
assert(genesis.hashMerkleRoot == uint256("0xa1de9df44936bd1dd483e217fa17ec1881d2caf741ca67a33f6cd6850183078c"));
vSeeds.push_back(CDNSSeedData("45.32.211.127", "45.32.211.127"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
nLastPOWBlock = 2000;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x5f;
pchMessageStart[1] = 0xf2;
pchMessageStart[2] = 0x15;
pchMessageStart[3] = 0x30;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("");
nDefaultPort = 51002;
nRPCPort = 51003;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 72686;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x0000070638e1fb122fb31b4753a5311f3c8784604d9f6ce42e8fec96d94173b4"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,127);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x44;
pchMessageStart[1] = 0x45;
pchMessageStart[2] = 0x53;
pchMessageStart[3] = 0x54;
vAlertPubKey = ParseHex("04acdb4977a559440c1fa273cc79ef738ece2bfdc984ebcbd1defad4656b30d13d97a5f64448eb5ff4fd56420b340bf5d63ae57e929b666d5717f853a629103f61");
vchSyncCheckpointPubKey = ParseHex("0448addbefe39432f89547603c7016cac247ad9fdffa34459d5534cf0d64f3afec95a4f20c3d80941cdc771fa2ec4a652488dcfe8cc6abf5f3f2ab05a79f8bba6e");
nDefaultPort = 19199;
nRPCPort = 19200;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 18);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
const char* pszTimestamp = "2016 FootyCash launches and is a huge success";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1456082001, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1456082001;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 449;
hashGenesisBlock = uint256("0x0000005ec05d79bef930111ff31cc66e8127752a084936e0ff938fea15993241");
assert(hashGenesisBlock == uint256("0x0000005ec05d79bef930111ff31cc66e8127752a084936e0ff938fea15993241"));
assert(genesis.hashMerkleRoot == uint256("0x4e448dece2984c7c9312b4d878e8493664375d4b8b9fbdf232094aae71328406"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(30)(101)(250);
base58Prefixes[SCRIPT_ADDRESS] = list_of(85)(85)(85);
base58Prefixes[SECRET_KEY] = list_of(153)(153)(153);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
bnProofOfStakeLimit = CBigNum(~uint256(0)>>5);
nBasicPoWReward = 1000 * COIN;
nPoWHalving = 2000;
nLaunchTime = genesis.nTime;
nMinDelay = 2; //seconds
nCoinbaseMaturity = 20;
nStakeMinConfirmations = 20;
nStakeMinAge = 60 * 60 * 8;
nModifierInterval = 10 * 60; // time to elapse before new modifier is computed
nStakeCoinYearReward = 3 * CENT;
nPoSHalving = 1350 * 365; //
nLastPOWBlock = 20160;
nFirstPoSBlock = 10000;
nPoSGranularity = 15;
nTargetSpacing = (nPoSGranularity + 1) * 4;
nMaxMoney = nLastPOWBlock * nBasicPoWReward;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x64;
pchMessageStart[1] = 0x65;
pchMessageStart[2] = 0x73;
pchMessageStart[3] = 0x74;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("04acdb4977a559440c1fa273cc79ef738ece2bfdc984ebcbd1defad4656b30d13d97a5f64448eb5ff4fd56420b340bf5d63ae57e929b666d5717f853a629103f61");
nDefaultPort = 20199;
nRPCPort = 20200;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 0;
hashGenesisBlock = uint256("0x0000d864d0d5e1e6c08d8a9b6cdf66a62bc1c9a68d5c82e6088f368eaf770905");
assert(hashGenesisBlock == uint256("0x0000d864d0d5e1e6c08d8a9b6cdf66a62bc1c9a68d5c82e6088f368eaf770905"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(111);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
bnProofOfStakeLimit = CBigNum(~uint256(0) >> 20);
nCoinbaseMaturity = 10;
nStakeMinConfirmations = 10;
nStakeMinAge = 8 * 60; // 8 mins
nModifierInterval = 10 * 60; // time to elapse before new modifier is computed
nStakeCoinYearReward = 5 * CENT; // 5% per year
nLastPOWBlock = 1350*5*6;
nMaxMoney = 3141592654 * COIN;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet ) {
return false;
}
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Added seed node seed.footycash.com<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x44;
pchMessageStart[1] = 0x45;
pchMessageStart[2] = 0x53;
pchMessageStart[3] = 0x54;
vAlertPubKey = ParseHex("04acdb4977a559440c1fa273cc79ef738ece2bfdc984ebcbd1defad4656b30d13d97a5f64448eb5ff4fd56420b340bf5d63ae57e929b666d5717f853a629103f61");
vchSyncCheckpointPubKey = ParseHex("0448addbefe39432f89547603c7016cac247ad9fdffa34459d5534cf0d64f3afec95a4f20c3d80941cdc771fa2ec4a652488dcfe8cc6abf5f3f2ab05a79f8bba6e");
nDefaultPort = 19199;
nRPCPort = 19200;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 18);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
const char* pszTimestamp = "2016 FootyCash launches and is a huge success";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1456082001, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1456082001;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 449;
hashGenesisBlock = uint256("0x0000005ec05d79bef930111ff31cc66e8127752a084936e0ff938fea15993241");
assert(hashGenesisBlock == uint256("0x0000005ec05d79bef930111ff31cc66e8127752a084936e0ff938fea15993241"));
assert(genesis.hashMerkleRoot == uint256("0x4e448dece2984c7c9312b4d878e8493664375d4b8b9fbdf232094aae71328406"));
vSeeds.push_back(CDNSSeedData("seed.footycash.com", "seed.footycash.com"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(30)(101)(250);
base58Prefixes[SCRIPT_ADDRESS] = list_of(85)(85)(85);
base58Prefixes[SECRET_KEY] = list_of(153)(153)(153);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
bnProofOfStakeLimit = CBigNum(~uint256(0)>>5);
nBasicPoWReward = 1000 * COIN;
nPoWHalving = 2000;
nLaunchTime = genesis.nTime;
nMinDelay = 2; //seconds
nCoinbaseMaturity = 20;
nStakeMinConfirmations = 20;
nStakeMinAge = 60 * 60 * 8;
nModifierInterval = 10 * 60; // time to elapse before new modifier is computed
nStakeCoinYearReward = 3 * CENT;
nPoSHalving = 1350 * 365; //
nLastPOWBlock = 20160;
nFirstPoSBlock = 10000;
nPoSGranularity = 15;
nTargetSpacing = (nPoSGranularity + 1) * 4;
nMaxMoney = nLastPOWBlock * nBasicPoWReward;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x64;
pchMessageStart[1] = 0x65;
pchMessageStart[2] = 0x73;
pchMessageStart[3] = 0x74;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("04acdb4977a559440c1fa273cc79ef738ece2bfdc984ebcbd1defad4656b30d13d97a5f64448eb5ff4fd56420b340bf5d63ae57e929b666d5717f853a629103f61");
nDefaultPort = 20199;
nRPCPort = 20200;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 0;
hashGenesisBlock = uint256("0x0000d864d0d5e1e6c08d8a9b6cdf66a62bc1c9a68d5c82e6088f368eaf770905");
assert(hashGenesisBlock == uint256("0x0000d864d0d5e1e6c08d8a9b6cdf66a62bc1c9a68d5c82e6088f368eaf770905"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(111);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
bnProofOfStakeLimit = CBigNum(~uint256(0) >> 20);
nCoinbaseMaturity = 10;
nStakeMinConfirmations = 10;
nStakeMinAge = 8 * 60; // 8 mins
nModifierInterval = 10 * 60; // time to elapse before new modifier is computed
nStakeCoinYearReward = 5 * CENT; // 5% per year
nLastPOWBlock = 1350*5*6;
nMaxMoney = 3141592654 * COIN;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet ) {
return false;
}
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|> |
<commit_before>#ifndef LIBPORT_FWD_HH
# define LIBPORT_FWD_HH
namespace libport
{
#if 0
// We don't fwddecl hash, because it is too much of a PITA:
// namespace ns
// {
// struct foo;
// }
//
// namespace impl
// {
// struct foo {};
// }
//
// namespace ns
// {
// using impl::foo;
// }
// does not work, the compiler complains there are two definitions
// of ns::foo. The following works:
// namespace impl
// {
// template <typename T>
// struct foo;
// }
//
// namespace ns
// {
// using impl::foo;
// }
//
// namespace impl
// {
// template <typename T>
// struct foo {};
// }
//
// namespace ns
// {
// using impl::foo;
// }
// but the problem is that this definition will depend upon the
// architecture to find what the "impl" namespace is. So we
// just don't fwddecl hash, unless someone feels like filling the
// blanks.
// hash.hh.
// Warning: The VC++ implementation might have a different number of
// parameters, in which case a #if will be needed to fwd decl both
// flavors of hash_map.
// Anyway, we want std::tr1::unodered_map here.
template<class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
class hash_map;
// FIXME: To remove some day.
template<class K, class V>
class hash_map_type;
#endif
// lockable.hh.
class Lockable;
// package-info.hh;
class PackageInfo;
// path.hh;
struct Path;
// ref-pt.hh
template <class T> class RefPt;
// select-const.hh.
template <typename T> struct constify_traits;
template <typename T> struct id_traits;
// shared-ref.hh.
template <typename T> class shared_ref;
// semaphore.hh.
class Semaphore;
// symbol.hh.
class Symbol;
}
#endif // !LIBPORT_FWD_HH
<commit_msg>libport.fwd.<commit_after>#ifndef LIBPORT_FWD_HH
# define LIBPORT_FWD_HH
namespace libport
{
#if 0
// We don't fwddecl hash, because it is too much of a PITA:
// namespace ns
// {
// struct foo;
// }
//
// namespace impl
// {
// struct foo {};
// }
//
// namespace ns
// {
// using impl::foo;
// }
// does not work, the compiler complains there are two definitions
// of ns::foo. The following works:
// namespace impl
// {
// template <typename T>
// struct foo;
// }
//
// namespace ns
// {
// using impl::foo;
// }
//
// namespace impl
// {
// template <typename T>
// struct foo {};
// }
//
// namespace ns
// {
// using impl::foo;
// }
// but the problem is that this definition will depend upon the
// architecture to find what the "impl" namespace is. So we
// just don't fwddecl hash, unless someone feels like filling the
// blanks.
// hash.hh.
// Warning: The VC++ implementation might have a different number of
// parameters, in which case a #if will be needed to fwd decl both
// flavors of hash_map.
// Anyway, we want std::tr1::unodered_map here.
template<class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
class hash_map;
#endif
// lockable.hh.
class Lockable;
// package-info.hh;
class PackageInfo;
// path.hh;
struct Path;
// ref-pt.hh
template <class T> class RefPt;
// asio.hh;
struct Socket;
// select-const.hh.
template <typename T> struct constify_traits;
template <typename T> struct id_traits;
// shared-ref.hh.
template <typename T> class shared_ref;
// semaphore.hh.
class Semaphore;
// symbol.hh.
class Symbol;
}
#endif // !LIBPORT_FWD_HH
<|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.
===================================================================*/
// Testing
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"
// qt includes
#include "QApplication"
#include <qapplication>
// std includes
#include <string>
// MITK includes
#include "QmitkChartWidget.h"
#include "QmitkChartxyData.h"
#include "QmitkChartData.h"
class mitkChartWidgetTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkChartWidgetTestSuite);
// Test the dicom property parsing
MITK_TEST(AddOnce_Test_Success);
MITK_TEST(AddSameLabelTwice_Test_Success);
MITK_TEST(RemoveNonexistingData_Failure);
MITK_TEST(RemoveData_Success);
MITK_TEST(SetandGet_Success);
MITK_TEST(SetC3DataAndGet_Success);
MITK_TEST(AddAndRemoveData_Sucess);
// MITK_TEST(AddAndGet)
CPPUNIT_TEST_SUITE_END();
private:
std::vector<double> data1D;
std::string label;
public:
void setUp() override
{
data1D = {2, 4, 7, 8, 21, 5, 12, 65, 41, 9};
label = "testLabel";
int argc = 1;
char *argv[] = {"AppName"};
if (QApplication::instance() == nullptr)
{
new QApplication(argc, argv);
}
}
void tearDown() override {}
void AddOnce_Test_Success()
{
QmitkChartWidget widget;
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Adding data caused an exception", widget.AddData1D(data1D, label));
std::vector<std::unique_ptr<QmitkChartxyData>> *dataVector = widget.GetData();
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 1 && dataVector != nullptr);
QmitkChartxyData * dataPtr = dataVector->at(0).get();
CPPUNIT_ASSERT_MESSAGE("Label differs for no obvious reason", dataPtr->GetLabel().toString().toStdString() == label);
std::vector<QVariant> insertedYData = dataPtr->GetYData().toVector().toStdVector();
CPPUNIT_ASSERT_MESSAGE("Data differs in size", insertedYData.size() == data1D.size());
for (int i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
}
void AddSameLabelTwice_Test_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
widget.AddData1D(data1D, label);
auto dataVector = widget.GetData();
QmitkChartxyData* xyData1 = dataVector->at(0).get();
QmitkChartxyData* xyData2 = dataVector->at(1).get();
QVariant dataLabel1 = xyData1->GetLabel();
QVariant dataLabel2 = xyData2->GetLabel();
CPPUNIT_ASSERT_MESSAGE("The two dataLabel are the same", dataLabel1 != dataLabel2);
QString string1 = dataLabel1.toString();
QString string2 = dataLabel2.toString();
std::string stdString1 = string1.toStdString();
std::string stdString2 = string2.toStdString();
CPPUNIT_ASSERT_MESSAGE("The first dataLabel isn't still the same", stdString1 == label);
CPPUNIT_ASSERT_MESSAGE("The second dataLabel is still the same", stdString2 != label);
}
void AddAndRemoveData_Sucess()
{
std::vector<double> data1D2 = {2, 2};
std::string label2 = "testData2";
std::vector<double> data1D3 = {3, 3, 3};
std::string label3 = "testData3";
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
widget.AddData1D(data1D2, label2);
widget.AddData1D(data1D3, label3);
auto dataVector = widget.GetData();
// data with {data1D0, data1D2, data1D3}
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 3 && dataVector != nullptr);
widget.RemoveData(label2);
// data with {data1D0, data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 2 && dataVector != nullptr);
QmitkChartxyData *xyData1 = dataVector->at(0).get();
std::vector<QVariant> insertedYData = xyData1->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
QmitkChartxyData *xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
widget.RemoveData(label);
// data with {data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 1 && dataVector != nullptr);
widget.AddData1D(data1D2, label2);
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 2 && dataVector != nullptr);
//data with {data1D3, data1D2}
xyData1 = dataVector->at(0).get();
insertedYData = xyData1->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D2.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D2[i] == insertedYData[i]);
}
}
void RemoveNonexistingData_Failure()
{
QmitkChartWidget widget;
CPPUNIT_ASSERT_THROW_MESSAGE(
"Removin nonexistend label did not throw exception", widget.RemoveData(label), std::invalid_argument);
}
void RemoveData_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Removin nonexistend label did not throw exception", widget.RemoveData(label));
}
void SetandGet_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
std::string colorName = "green";
auto mitkChartxyData = widget.GetData();
QmitkChartxyData *xyData1 = mitkChartxyData->at(0).get();
//set color test
widget.SetColor(label, colorName);
auto qVariantColor = xyData1->GetColor();
QString qStringColor = qVariantColor.toString();
CPPUNIT_ASSERT_MESSAGE("The color isn't the assigned color", colorName == qStringColor.toStdString());
//set line style test
QVariant defaultLineStyle = xyData1->GetLineStyle();
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
QVariant lineStyle = xyData1->GetLineStyle();
QVariant defaultChartType = xyData1->GetChartType();
auto line= std::make_pair("line", QmitkChartWidget::ChartType::line);
if (defaultChartType.toString().toStdString() != line.first)
{
CPPUNIT_ASSERT_MESSAGE("The line style could be changed without ChartType line",
defaultLineStyle == lineStyle);
}
//set ChartType
widget.SetChartType(label, QmitkChartWidget::ChartType::line);
QVariant chartType = xyData1->GetChartType();
CPPUNIT_ASSERT_MESSAGE("The chart type could not be changed to line",
chartType.toString().toStdString() == line.first);
//set line style with chart type line
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
lineStyle = xyData1->GetLineStyle();
CPPUNIT_ASSERT_MESSAGE("The line style could not be changed", "dashed" == lineStyle.toString().toStdString());
}
void SetC3DataAndGet_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
//set YAxisScale
widget.SetYAxisScale(QmitkChartWidget::AxisScale::log);
QmitkChartData *c3Data = widget.GetC3Data();
QVariant yAxisScale = c3Data->GetYAxisScale();
CPPUNIT_ASSERT_MESSAGE("The YAxisScale could not be changed", "log" == yAxisScale.toString().toStdString());
//set Title
std::string testTitle = "testTitle";
widget.SetTitle(testTitle);
QVariant title = c3Data->GetTitle();
CPPUNIT_ASSERT_MESSAGE("The title could not be set", testTitle == title.toString().toStdString());
//set LegendPosition
widget.SetLegendPosition(QmitkChartWidget::LegendPosition::right);
QVariant legendPosition = c3Data->GetLegendPosition();
CPPUNIT_ASSERT_MESSAGE("The LegendPosition could not be changed", "right" == legendPosition.toString().toStdString());
//show legend
QVariant isShowLegend = c3Data->GetShowLegend();
widget.SetShowLegend(!isShowLegend.toBool());
QVariant isShowLegendInverted = c3Data->GetShowLegend();
CPPUNIT_ASSERT_MESSAGE("The ShowLegend could not be changed",
isShowLegend.toBool() != isShowLegendInverted.toBool());
//show dataPoints
QVariant dataPointSize = c3Data->GetDataPointSize();
bool showDataPoints = dataPointSize.toInt() > 0;
widget.SetShowDataPoints(!showDataPoints);
dataPointSize = c3Data->GetDataPointSize();
bool showDataPointsInvert = dataPointSize.toInt() > 0;
CPPUNIT_ASSERT_MESSAGE("The DataPoints could not be changed",
isShowLegend.toBool() != isShowLegendInverted.toBool());
//show SubCharts
QVariant showSubChart = c3Data->GetShowSubchart();
widget.Show(!showSubChart.toBool());
QVariant showSubChartInvert = c3Data->GetShowSubchart();
CPPUNIT_ASSERT_MESSAGE("The visibility of subCharts could not be changed",
showSubChart.toBool() != showSubChartInvert.toBool());
}
};
MITK_TEST_SUITE_REGISTRATION(mitkChartWidget)<commit_msg>use QApplication instead of qapplication for linux gcc<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.
===================================================================*/
// Testing
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"
// qt includes
#include "QApplication"
// std includes
#include <string>
// MITK includes
#include "QmitkChartWidget.h"
#include "QmitkChartxyData.h"
#include "QmitkChartData.h"
class mitkChartWidgetTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkChartWidgetTestSuite);
// Test the dicom property parsing
MITK_TEST(AddOnce_Test_Success);
MITK_TEST(AddSameLabelTwice_Test_Success);
MITK_TEST(RemoveNonexistingData_Failure);
MITK_TEST(RemoveData_Success);
MITK_TEST(SetandGet_Success);
MITK_TEST(SetC3DataAndGet_Success);
MITK_TEST(AddAndRemoveData_Sucess);
// MITK_TEST(AddAndGet)
CPPUNIT_TEST_SUITE_END();
private:
std::vector<double> data1D;
std::string label;
public:
void setUp() override
{
data1D = {2, 4, 7, 8, 21, 5, 12, 65, 41, 9};
label = "testLabel";
int argc = 1;
char *argv[] = {"AppName"};
if (QApplication::instance() == nullptr)
{
new QApplication(argc, argv);
}
}
void tearDown() override {}
void AddOnce_Test_Success()
{
QmitkChartWidget widget;
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Adding data caused an exception", widget.AddData1D(data1D, label));
std::vector<std::unique_ptr<QmitkChartxyData>> *dataVector = widget.GetData();
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 1 && dataVector != nullptr);
QmitkChartxyData * dataPtr = dataVector->at(0).get();
CPPUNIT_ASSERT_MESSAGE("Label differs for no obvious reason", dataPtr->GetLabel().toString().toStdString() == label);
std::vector<QVariant> insertedYData = dataPtr->GetYData().toVector().toStdVector();
CPPUNIT_ASSERT_MESSAGE("Data differs in size", insertedYData.size() == data1D.size());
for (int i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
}
void AddSameLabelTwice_Test_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
widget.AddData1D(data1D, label);
auto dataVector = widget.GetData();
QmitkChartxyData* xyData1 = dataVector->at(0).get();
QmitkChartxyData* xyData2 = dataVector->at(1).get();
QVariant dataLabel1 = xyData1->GetLabel();
QVariant dataLabel2 = xyData2->GetLabel();
CPPUNIT_ASSERT_MESSAGE("The two dataLabel are the same", dataLabel1 != dataLabel2);
QString string1 = dataLabel1.toString();
QString string2 = dataLabel2.toString();
std::string stdString1 = string1.toStdString();
std::string stdString2 = string2.toStdString();
CPPUNIT_ASSERT_MESSAGE("The first dataLabel isn't still the same", stdString1 == label);
CPPUNIT_ASSERT_MESSAGE("The second dataLabel is still the same", stdString2 != label);
}
void AddAndRemoveData_Sucess()
{
std::vector<double> data1D2 = {2, 2};
std::string label2 = "testData2";
std::vector<double> data1D3 = {3, 3, 3};
std::string label3 = "testData3";
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
widget.AddData1D(data1D2, label2);
widget.AddData1D(data1D3, label3);
auto dataVector = widget.GetData();
// data with {data1D0, data1D2, data1D3}
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 3 && dataVector != nullptr);
widget.RemoveData(label2);
// data with {data1D0, data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 2 && dataVector != nullptr);
QmitkChartxyData *xyData1 = dataVector->at(0).get();
std::vector<QVariant> insertedYData = xyData1->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
QmitkChartxyData *xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
widget.RemoveData(label);
// data with {data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 1 && dataVector != nullptr);
widget.AddData1D(data1D2, label2);
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 2 && dataVector != nullptr);
//data with {data1D3, data1D2}
xyData1 = dataVector->at(0).get();
insertedYData = xyData1->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (int i = 0; i < data1D2.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D2[i] == insertedYData[i]);
}
}
void RemoveNonexistingData_Failure()
{
QmitkChartWidget widget;
CPPUNIT_ASSERT_THROW_MESSAGE(
"Removin nonexistend label did not throw exception", widget.RemoveData(label), std::invalid_argument);
}
void RemoveData_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Removin nonexistend label did not throw exception", widget.RemoveData(label));
}
void SetandGet_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
std::string colorName = "green";
auto mitkChartxyData = widget.GetData();
QmitkChartxyData *xyData1 = mitkChartxyData->at(0).get();
//set color test
widget.SetColor(label, colorName);
auto qVariantColor = xyData1->GetColor();
QString qStringColor = qVariantColor.toString();
CPPUNIT_ASSERT_MESSAGE("The color isn't the assigned color", colorName == qStringColor.toStdString());
//set line style test
QVariant defaultLineStyle = xyData1->GetLineStyle();
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
QVariant lineStyle = xyData1->GetLineStyle();
QVariant defaultChartType = xyData1->GetChartType();
auto line= std::make_pair("line", QmitkChartWidget::ChartType::line);
if (defaultChartType.toString().toStdString() != line.first)
{
CPPUNIT_ASSERT_MESSAGE("The line style could be changed without ChartType line",
defaultLineStyle == lineStyle);
}
//set ChartType
widget.SetChartType(label, QmitkChartWidget::ChartType::line);
QVariant chartType = xyData1->GetChartType();
CPPUNIT_ASSERT_MESSAGE("The chart type could not be changed to line",
chartType.toString().toStdString() == line.first);
//set line style with chart type line
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
lineStyle = xyData1->GetLineStyle();
CPPUNIT_ASSERT_MESSAGE("The line style could not be changed", "dashed" == lineStyle.toString().toStdString());
}
void SetC3DataAndGet_Success()
{
QmitkChartWidget widget;
widget.AddData1D(data1D, label);
//set YAxisScale
widget.SetYAxisScale(QmitkChartWidget::AxisScale::log);
QmitkChartData *c3Data = widget.GetC3Data();
QVariant yAxisScale = c3Data->GetYAxisScale();
CPPUNIT_ASSERT_MESSAGE("The YAxisScale could not be changed", "log" == yAxisScale.toString().toStdString());
//set Title
std::string testTitle = "testTitle";
widget.SetTitle(testTitle);
QVariant title = c3Data->GetTitle();
CPPUNIT_ASSERT_MESSAGE("The title could not be set", testTitle == title.toString().toStdString());
//set LegendPosition
widget.SetLegendPosition(QmitkChartWidget::LegendPosition::right);
QVariant legendPosition = c3Data->GetLegendPosition();
CPPUNIT_ASSERT_MESSAGE("The LegendPosition could not be changed", "right" == legendPosition.toString().toStdString());
//show legend
QVariant isShowLegend = c3Data->GetShowLegend();
widget.SetShowLegend(!isShowLegend.toBool());
QVariant isShowLegendInverted = c3Data->GetShowLegend();
CPPUNIT_ASSERT_MESSAGE("The ShowLegend could not be changed",
isShowLegend.toBool() != isShowLegendInverted.toBool());
//show dataPoints
QVariant dataPointSize = c3Data->GetDataPointSize();
bool showDataPoints = dataPointSize.toInt() > 0;
widget.SetShowDataPoints(!showDataPoints);
dataPointSize = c3Data->GetDataPointSize();
bool showDataPointsInvert = dataPointSize.toInt() > 0;
CPPUNIT_ASSERT_MESSAGE("The DataPoints could not be changed",
isShowLegend.toBool() != isShowLegendInverted.toBool());
//show SubCharts
QVariant showSubChart = c3Data->GetShowSubchart();
widget.Show(!showSubChart.toBool());
QVariant showSubChartInvert = c3Data->GetShowSubchart();
CPPUNIT_ASSERT_MESSAGE("The visibility of subCharts could not be changed",
showSubChart.toBool() != showSubChartInvert.toBool());
}
};
MITK_TEST_SUITE_REGISTRATION(mitkChartWidget)<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: map.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef MAP_HPP
#define MAP_HPP
#include <mapnik/feature_type_style.hpp>
namespace mapnik
{
class Layer;
class MAPNIK_DECL Map
{
static const unsigned MIN_MAPSIZE=16;
static const unsigned MAX_MAPSIZE=2048;
unsigned width_;
unsigned height_;
int srid_;
Color background_;
std::map<std::string,feature_type_style> styles_;
std::vector<Layer> layers_;
Envelope<double> currentExtent_;
public:
typedef std::map<std::string,feature_type_style>::const_iterator style_iterator;
Map();
Map(int width,int height,int srid=-1);
Map(const Map& rhs);
Map& operator=(const Map& rhs);
style_iterator begin_styles() const;
style_iterator end_styles() const;
bool insert_style(std::string const& name,feature_type_style const& style);
void remove_style(const std::string& name);
feature_type_style const& find_style(std::string const& name) const;
size_t layerCount() const;
void addLayer(const Layer& l);
const Layer& getLayer(size_t index) const;
Layer& getLayer(size_t index);
void removeLayer(size_t index);
std::vector<Layer> const& layers() const;
unsigned getWidth() const;
unsigned getHeight() const;
void setWidth(unsigned width);
void setHeight(unsigned height);
void resize(unsigned width,unsigned height);
int srid() const;
void setBackground(const Color& c);
const Color& getBackground() const;
void zoom(double zoom);
void zoomToBox(const Envelope<double>& box);
void zoom_all();
void pan(int x,int y);
void pan_and_zoom(int x,int y,double zoom);
const Envelope<double>& getCurrentExtent() const;
double scale() const;
~Map();
private:
void fixAspectRatio();
};
}
#endif //MAP_HPP
<commit_msg>added remove_all<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: map.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef MAP_HPP
#define MAP_HPP
#include <mapnik/feature_type_style.hpp>
namespace mapnik
{
class Layer;
class MAPNIK_DECL Map
{
static const unsigned MIN_MAPSIZE=16;
static const unsigned MAX_MAPSIZE=2048;
unsigned width_;
unsigned height_;
int srid_;
Color background_;
std::map<std::string,feature_type_style> styles_;
std::vector<Layer> layers_;
Envelope<double> currentExtent_;
public:
typedef std::map<std::string,feature_type_style>::const_iterator style_iterator;
Map();
Map(int width,int height,int srid=-1);
Map(const Map& rhs);
Map& operator=(const Map& rhs);
style_iterator begin_styles() const;
style_iterator end_styles() const;
bool insert_style(std::string const& name,feature_type_style const& style);
void remove_style(const std::string& name);
feature_type_style const& find_style(std::string const& name) const;
size_t layerCount() const;
void addLayer(const Layer& l);
const Layer& getLayer(size_t index) const;
Layer& getLayer(size_t index);
void removeLayer(size_t index);
std::vector<Layer> const& layers() const;
void remove_all();
unsigned getWidth() const;
unsigned getHeight() const;
void setWidth(unsigned width);
void setHeight(unsigned height);
void resize(unsigned width,unsigned height);
int srid() const;
void setBackground(const Color& c);
const Color& getBackground() const;
void zoom(double zoom);
void zoomToBox(const Envelope<double>& box);
void zoom_all();
void pan(int x,int y);
void pan_and_zoom(int x,int y,double zoom);
const Envelope<double>& getCurrentExtent() const;
double scale() const;
~Map();
private:
void fixAspectRatio();
};
}
#endif //MAP_HPP
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <cctype>
#include <string>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include "network.h"
const string kEnwikiFile = "../enwiki-20151102-pages-articles-multistream.xml";
const string kIDOffsetTitleFile = "../id-offset-title.txt";
using namespace std;
typedef long long ll;
#define for_iter(i, n) for (__typeof(n.begin())i = n.begin(); i != n.end(); ++i)
const int kBufSize = 100000;
char g_input_buf[kBufSize];
class IDOffsetTitle {
public:
IDOffsetTitle(const string &filename)
{
Init(filename);
}
/*
* 从filename中读取<id> <offset> <title>内容
* 建立合适的数据结构,以支持下面的查找操作
*/
void Init(const string &filename)
{
FILE *fp = fopen(filename.c_str(), "r");
ll id;
int len;
long offset, pos_in_str;
char title_buf[kBufSize];
while (fgets(g_input_buf, kBufSize, fp)) {
sscanf(g_input_buf, "%lld%ld%[^\n]", &id, &offset, title_buf);
//printf("%lld %ld %s\n", id, offset, title_buf);
pos_in_str = title_concat_.length();
id_offset_[id] = offset;
ids_.push_back(id);
pos_.push_back(pos_in_str);
len = strlen(title_buf);
/* hadoop reduce will write a '\t' at the end of each kvpair */
if (title_buf[len - 1] == '\t')
title_buf[--len] = '\0';
for (int i = 0; i < len; i++) {
title_buf[i] = tolower(title_buf[i]);
if (!isalpha(title_buf[i]))
title_buf[i] = ' ';
}
title_concat_ += title_buf;
/*
* Warning!
* because every title starts with ' ' a space
*/
if (len == 2 && isalpha(title_buf[1]))
title_index_single_[char_num(title_buf[1])] = pos_in_str;
else
title_index_double_[char_num(title_buf[1])][char_num(title_buf[2])].push_back(pos_in_str);
}
printf("IDOffsetTitle init finish.\n");
fclose(fp);
}
/*
* 接受enwiki.xml中的偏移量
* 返回文章内容
*/
string Offset2Page(long offset)
{
printf("In function Offset2Page: handle offset = %ld\n", offset);
string page;
/* TODO change fp to private member variable */
FILE *fp = fopen(kEnwikiFile.c_str(), "r");
fseek(fp, offset, SEEK_SET);
char ch, a[7] = {0};
while ((ch = getc(fp))) {
page.push_back(ch);
for (int i = 0; i < 6; i++)
a[i] = a[i + 1];
a[6] = ch;
if (strcmp(a, "</page>") == 0)
break;
}
fclose(fp);
return page;
}
/*
* 接受文章ID,返回文章内容
* 即<page></page>之间的内容,包括page标签
* 常量时间
*/
string ID2Page(ll id)
{
printf("In function ID2Page: handle id = %lld\n", id);
return Offset2Page(id_offset_[id]);
}
vector<string> IDs2Pages(const vector<ll> ids)
{
/* For compatibility */
vector<string> pages;
for_iter(id, ids) {
pages.push_back(ID2Page(*id));
}
return pages;
}
/*
* 接受一个单词,从Title中查找子串,返回匹配的前K(default=10)条
* Since title_concat_.length() can be very large, this function may be slow
*/
vector<ll> Word2ID(const string &word, int K = 10)
{
long pos = 0;
vector<ll> ids;
assert(word.length() > 0);
if (word.length() == 1) {
pos = title_index_single_[word[0] - 'a'];
printf("%ld\n", pos);
long idx = lower_bound(pos_.begin(), pos_.end(), pos) - pos_.begin();
ids.push_back(ids_[idx]);
return ids;
}
long tmp = 0;
while (K-- && (pos = FindSubStringOrDie(title_concat_.c_str(), word.c_str(), tmp))) {
long idx = lower_bound(pos_.begin(), pos_.end(), pos) - pos_.begin();
ids.push_back(ids_[idx]);
}
return ids;
}
private:
/* 不接受长度 < 2的字符串 */
ll FindSubStringOrDie(const char *haystack, const char *needle, long &lastidx) {
int len = strlen(needle);
assert(len >= 2);
printf("In FindSubStringOrDir needle = %s\n", needle);
vector<long> &v = title_index_double_[char_num(needle[0])][char_num(needle[1])];
for (vector<long>::iterator it = v.begin() + lastidx; it != v.end(); ++it) {
lastidx++;
//printf("In FindSubStringOrDir it = %ld, string = %s\n", *it, string(haystack + *it + 1, strlen(needle)).c_str());
if (strncmp(haystack + *it + 1, needle, len) == 0)
return *it;
}
return 0; // or nullptr?
}
int char_num(int ch) { return ch - 'a'; }
/* ID到偏移量的hash */
unordered_map<ll, long> id_offset_;
/* 所有title字符串的拼接 */
string title_concat_;
/* 第i篇文章的id */
vector<ll> ids_;
/* 第i篇文章title在字符串中的下标*/
vector<long> pos_;
/* 索引两个字母开头的所有位置 加速查找 */
vector<long> title_index_double_[26][26];
long title_index_single_[26];
};
string Trim(string str) {
int start = 0, len = str.length();
for (string::const_iterator it = str.begin(); it != str.end() && isspace(*it); ++it, ++start);
for (string::const_reverse_iterator it = str.rbegin(); it != str.rend() && isspace(*it); ++it, --len);
return str.substr(start, len - start);
}
string WaitInput(TCPServer &server)
{
server.accept();
string msg = server.recv();
return Trim(msg);
}
int main() {
IDOffsetTitle query_class = IDOffsetTitle(kIDOffsetTitleFile);
TCPServer server("0.0.0.0", "23334");
while (1) {
string input = WaitInput(server);
cout << "recv:" << input << endl;
// do sth
vector<ll> ids = query_class.Word2ID(input);
if (ids.size() == 0) {
puts("No page found.");
server.send("No page found.");
} else {
puts("Found some pages:");
for_iter(id, ids)
printf("%lld\n", *id);
for_iter(id, ids) {
server.send(query_class.ID2Page(*id) + "\r\n\r\n");
}
}
}
return 0;
}
<commit_msg>实现了对倒排索引的查找<commit_after>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <cctype>
#include <string>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <queue>
#include <utility>
#include "network.h"
const string kEnwikiFile = "../enwiki-20151102-pages-articles-multistream.xml";
const string kIDOffsetTitleFile = "../id-offset-title.txt";
const string kInvertedIndexFile = "../inverted-index-fmt.txt";
const string kInvertedIndexWordOffsetFile = "../inverted-index-word-offset-df.txt";
const string kPageWordCountFile = "../page-wordcount.txt";
const string kPageMaxWordCountFile = "../page-max-wordcount.txt";
using namespace std;
typedef long long ll;
#define for_iter(i, n) for (__typeof(n.begin())i = n.begin(); i != n.end(); ++i)
const int kBufSize = 100000;
char g_input_buf[kBufSize];
class IDOffsetTitle {
public:
IDOffsetTitle(const string &offset_file, const string &context_file)
{
Init(offset_file, context_file);
}
/*
* 从offset_file中读取<id> <offset> <title>内容
* 建立合适的数据结构,以支持下面的查找操作
*/
void Init(const string &offset_file, const string &context_file)
{
context_fp_ = fopen(context_file.c_str(), "r");
FILE *fp = fopen(offset_file.c_str(), "r");
ll id;
int len;
long offset, pos_in_str;
char title_buf[kBufSize];
while (fgets(g_input_buf, kBufSize, fp)) {
sscanf(g_input_buf, "%lld%ld%[^\n]", &id, &offset, title_buf);
//printf("%lld %ld %s\n", id, offset, title_buf);
pos_in_str = title_concat_.length();
id_offset_[id] = offset;
ids_.push_back(id);
pos_.push_back(pos_in_str);
len = strlen(title_buf);
/* hadoop reduce will write a '\t' at the end of each kvpair */
if (title_buf[len - 1] == '\t')
title_buf[--len] = '\0';
for (int i = 0; i < len; i++) {
title_buf[i] = tolower(title_buf[i]);
if (!isalpha(title_buf[i]))
title_buf[i] = ' ';
}
title_concat_ += title_buf;
/*
* Warning!
* because every title starts with ' ' a space
*/
if (len == 2 && isalpha(title_buf[1]))
title_index_single_[char_num(title_buf[1])] = pos_in_str;
else
title_index_double_[char_num(title_buf[1])][char_num(title_buf[2])].push_back(pos_in_str);
}
printf("IDOffsetTitle init finished.\n");
fclose(fp);
}
/*
* 接受enwiki.xml中的偏移量
* 返回文章内容
*/
string Offset2Page(long offset)
{
printf("In function Offset2Page: handle offset = %ld\n", offset);
string page;
/* TODO change fp to private member variable */
FILE *fp = context_fp_;
fseek(fp, offset, SEEK_SET);
char ch, a[7] = {0};
while ((ch = getc(fp))) {
page.push_back(ch);
for (int i = 0; i < 6; i++)
a[i] = a[i + 1];
a[6] = ch;
if (strcmp(a, "</page>") == 0)
break;
}
return page;
}
/*
* 接受文章ID,返回文章内容
* 即<page></page>之间的内容,包括page标签
* 常量时间
*/
string ID2Page(ll id)
{
printf("In function ID2Page: handle id = %lld\n", id);
return Offset2Page(id_offset_[id]);
}
vector<string> IDs2Pages(const vector<ll> ids)
{
/* For compatibility */
vector<string> pages;
for_iter(id, ids) {
pages.push_back(ID2Page(*id));
}
return pages;
}
/*
* 接受一个单词,从Title中查找子串,返回匹配的前K(default=10)条
* Since title_concat_.length() can be very large, this function may be slow
*/
vector<ll> Word2ID(const string &word, int K = 10)
{
long pos = 0;
vector<ll> ids;
assert(word.length() > 0);
if (word.length() == 1) {
pos = title_index_single_[word[0] - 'a'];
printf("%ld\n", pos);
long idx = lower_bound(pos_.begin(), pos_.end(), pos) - pos_.begin();
ids.push_back(ids_[idx]);
return ids;
}
long tmp = 0;
while (K-- && (pos = FindSubStringOrDie(title_concat_.c_str(), word.c_str(), tmp))) {
long idx = lower_bound(pos_.begin(), pos_.end(), pos) - pos_.begin();
ids.push_back(ids_[idx]);
}
return ids;
}
private:
/* 不接受长度 < 2的字符串 */
ll FindSubStringOrDie(const char *haystack, const char *needle, long &lastidx) {
int len = strlen(needle);
assert(len >= 2);
printf("In FindSubStringOrDir needle = %s\n", needle);
vector<long> &v = title_index_double_[char_num(needle[0])][char_num(needle[1])];
for (vector<long>::iterator it = v.begin() + lastidx; it != v.end(); ++it) {
lastidx++;
//printf("In FindSubStringOrDir it = %ld, string = %s\n", *it, string(haystack + *it + 1, strlen(needle)).c_str());
if (strncmp(haystack + *it + 1, needle, len) == 0)
return *it;
}
return 0; // or nullptr?
}
int char_num(int ch) { return ch - 'a'; }
FILE *context_fp_;
/* ID到偏移量的hash */
unordered_map<ll, long> id_offset_;
/* 所有title字符串的拼接 */
string title_concat_;
/* 第i篇文章的id */
vector<ll> ids_;
/* 第i篇文章title在字符串中的下标*/
vector<long> pos_;
/* 索引两个字母开头的所有位置 加速查找 */
vector<long> title_index_double_[26][26];
long title_index_single_[26];
};
class InvertedIndex {
public:
/*
* 接受两个参数,前一个文件是后一个文件的偏移量索引
*/
InvertedIndex(const string &offset_file, const string &context_file)
{
Init(offset_file, context_file);
}
void Init(const string &offset_file, const string &context_file)
{
context_file_ = context_file;
FILE *fp = fopen(offset_file.c_str(), "r");
long offset, df;
char word_buf[kBufSize];
while (fgets(g_input_buf, kBufSize, fp)) {
sscanf(g_input_buf, "%s%ld%ld", word_buf, &offset, &df);
//printf("%s %ld %ld\n", word_buf, offset, df);
word_offset_[word_buf] = offset;
df_[word_buf] = df;
}
fclose(fp);
ll id;
int count;
fp = fopen(kPageWordCountFile.c_str(), "r");
while (~fscanf(fp, "%lld%d\n", &id, &count))
page_words_[id] = count;
fclose(fp);
fp = fopen(kPageMaxWordCountFile.c_str(), "r");
while (~fscanf(fp, "%lld%d\n", &id, &count))
page_max_words_[id] = count;
fclose(fp);
printf("InvertedIndex init finished.\n");
}
/*
* 接受一个字符串输入,该函数将字符串分成单词
* 根据DF排序,然后再根据TF查询相关度最高的K个解
* 返回结果文章的id
*/
vector<ll> Query(string input, int K = 10)
{
vector<string> words;
char *input_cstr = new char[input.length() + 1];
strcpy(input_cstr, input.c_str());
/* Warning: strncpy will not be null-terminated if n <= the length of the string */
//strncpy(input_cstr, input.c_str(), input.length() + 1);
for (char *ptr = strtok(input_cstr, " "); ptr != NULL; ptr = strtok(NULL, " "))
words.push_back(ptr);
//sort(words.begin(), words.end(), cmp_df);
/*
* Because the input is type by user, so we can use choose sort here
* which is O(n^2)
*/
for (int i = 0; i < (int)words.size() - 1; i++)
for (int j = i + 1; j < (int)words.size(); j++)
if (!cmp_df(words[i], words[j]))
swap(words[i], words[j]);
puts("After sort by DF, the input is:");
for_iter(word, words) {
putchar('\'');
printf("%s", word->c_str());
printf("%ld", word->length());
putchar('\'');
}
return Words2Pages(words, K);
}
/*
* 采用一次一单词
* DF小的单词在前面
*/
vector<ll> Words2Pages(const vector<string> words, int K = 10)
{
if (K < 100) {
/* use normal array */
} else {
/* Use priority_queue */
}
/* 一次性打开多个,减少seek */
vector<FILE*> fps;
for_iter(word, words) {
FILE *fp = fopen(context_file_.c_str(), "r");
fseek(fp, word_offset_[*word] + word->length(), SEEK_SET);
fps.push_back(fp);
}
unordered_map<ll, int> id_times;
unordered_map<ll, double> id_tfproduct;
struct IDTimesTF {
ll id;
double tfproduct;
int times;
bool operator < (const IDTimesTF &a) const {
return times > a.times || (times == a.times && tfproduct > a.tfproduct);
}
};
printf("%ld\n", df_["linux"]);
printf("%s\n", words[0].c_str());
printf("%ld\n", words[0].length());
printf("%ld\n", df_[words[0]]);
printf("%ld\n", df_[words[0].c_str()]);
ll id, tf;
vector<IDTimesTF> vec;
for (size_t i = 0; i < words.size(); ++i) {
long df = df_[words[i]];
printf("For words %s, df = %ld\n", words[i].c_str(), df);
for (long j = 0; j < df; j++) {
id = next_ll(fps[i]);
tf = next_ll(fps[i]);
id_times[id]++;
id_tfproduct[id] *= 1.0 * tf / page_words_[id];
}
}
for_iter(it, id_times) {
vec.push_back((IDTimesTF) {
it->first,
id_tfproduct[it->first],
it->second
});
}
sort(vec.begin(), vec.end());
vector<ll> ids;
for (size_t i = 0; i < (size_t)K && i < vec.size(); i++)
ids.push_back(vec[i].id);
for_iter(fp, fps)
fclose(*fp);
return ids;
}
private:
bool cmp_df(const string &a, const string &b)
{
return df_[a] < df_[b];
}
/* id是按字典序排的,所以应该调这个函数 */
string next_id(FILE *fp)
{
char s[30];
fscanf(fp, "%s", s);
return s;
}
/* Only consider positive number */
ll next_ll(FILE *fp)
{
char c;
while (c = getc(fp), !isdigit(c));
ll ret = c - 48;
while (c = getc(fp), isdigit(c))
ret = ret * 10 + c - 48;
return ret;
}
string context_file_;
/*
* key: word
* value: offset
*/
unordered_map<string, long> word_offset_;
/*
* 文档频率 Document Frequency
* key: word
* value: df
*/
unordered_map<string, long> df_;
/*
* key: id
* value: total words of page
*/
unordered_map<ll, int> page_words_;
unordered_map<ll, int> page_max_words_;
};
string Trim(string str) {
int start = 0, len = str.length();
for (string::const_iterator it = str.begin(); it != str.end() && isspace(*it); ++it, ++start);
for (string::const_reverse_iterator it = str.rbegin(); it != str.rend() && isspace(*it); ++it, --len);
return str.substr(start, len - start);
}
string WaitInput(TCPServer &server)
{
server.accept();
string msg = server.recv();
return Trim(msg);
}
int main() {
IDOffsetTitle query_class = IDOffsetTitle(kIDOffsetTitleFile, kEnwikiFile);
InvertedIndex inverted_index_class = InvertedIndex(kInvertedIndexWordOffsetFile, kInvertedIndexFile);
TCPServer server("0.0.0.0", "23334");
while (1) {
string input = WaitInput(server);
cout << "recv:" << input << endl;
size_t pos = input.find_first_of(" ");
assert(pos != string::npos);
int limit = strtol(input.substr(0, pos).c_str(), NULL, 10);
input = input.substr(pos + 1, input.length() - pos - 1);
printf("limit: %d\n", limit);
printf("query: %s\n", input.c_str());
// do sth
vector<string> result_pages;
vector<ll> ids = query_class.Word2ID(input);
unordered_map<ll, int> id_found_in_title;
if (ids.size() == 0) {
puts("Considering title. No page found.");
} else {
puts("Considering title. Found some pages:");
for_iter(id, ids) {
printf("%lld\n", *id);
id_found_in_title[*id] = 1;
}
for_iter(id, ids) {
result_pages.push_back(query_class.ID2Page(*id));
//server.send(query_class.ID2Page(*id) + "\r\n\r\n");
}
}
puts("Begin to find in pages...");
vector<ll> ids2 = inverted_index_class.Query(input);
if (ids2.size() == 0) {
puts("No page found in documents");
} else {
for_iter(id, ids2)
printf("%lld\n", *id);
for_iter(id, ids2) {
if (!id_found_in_title[*id]) {
result_pages.push_back(query_class.ID2Page(*id));
}
}
}
if (result_pages.size() == 0) {
puts("Finally found nothing, try some other words.");
server.send("Finally found nothing, try some other words.");
} else {
for_iter(page, result_pages) {
if (limit-- == 0)
break;
server.send((*page + "\r\n\r\n").c_str());
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 12305, uint256("0x0000000000096316da076ab294c5082be090c7190439aee8bbdfc7b49dae349d"))
;
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0000000017295c46d2ef2a1875ab3328cf6fc95e6edcb912c71ad0540080a807"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!GetBoolArg("-checkpoints", true))
return true;
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (!GetBoolArg("-checkpoints", true))
return 0;
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!GetBoolArg("-checkpoints", true))
return NULL;
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>New checkpoint<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 12305, uint256("0x0000000000096316da076ab294c5082be090c7190439aee8bbdfc7b49dae349d"))
( 14200, uint256("0x000000000002199e9958c3c9efd0e983d7239508b55ff61544fed91dfdf86d7b"))
;
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0000000017295c46d2ef2a1875ab3328cf6fc95e6edcb912c71ad0540080a807"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!GetBoolArg("-checkpoints", true))
return true;
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (!GetBoolArg("-checkpoints", true))
return 0;
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!GetBoolArg("-checkpoints", true))
return NULL;
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x000001328ca4babaa49f1da4ad93486dc3cac63b2ceec532cba19ad6fc475dc4"))
( 25000, uint256("0xb38fa4e25b9eddf294e382218d3a032696b4918420a283ffce02731d00e00e79"))
( 45000, uint256("0x2ce57b0b211134ce3e46e414d13c7ff7253f0a7a989c938fd577db4b7f0f1aeb"))
( 60011, uint256("0x0aaf8439de77cbc7b33e9dd7ea7b0950910c4ce9779c557f2daeae4805dd0bab"))
(118853, uint256("0x000000000000f9e23ce3b0a9c151156501a53d22264adb52998a7522d3280f1f"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1402313205, // * UNIX timestamp of last checkpoint block
141753, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
2880 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x0000017ce2a79c8bddafbbe47c004aa92b20678c354b34085f62b762084b9788"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1392876393,
0,
2880
};
const CCheckpointData &Checkpoints() {
if (TestNet())
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>v1.3.3<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x000001328ca4babaa49f1da4ad93486dc3cac63b2ceec532cba19ad6fc475dc4"))
( 25000, uint256("0xb38fa4e25b9eddf294e382218d3a032696b4918420a283ffce02731d00e00e79"))
( 45000, uint256("0x2ce57b0b211134ce3e46e414d13c7ff7253f0a7a989c938fd577db4b7f0f1aeb"))
( 60011, uint256("0x0aaf8439de77cbc7b33e9dd7ea7b0950910c4ce9779c557f2daeae4805dd0bab"))
(118853, uint256("0x000000000000f9e23ce3b0a9c151156501a53d22264adb52998a7522d3280f1f"))
(150001, uint256("0xfa91abd9f3e10b9287e44285d73284f82aca08b1428c886cb7cb02c16206948e"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1405073128, // * UNIX timestamp of last checkpoint block
184352, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
2880 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x0000017ce2a79c8bddafbbe47c004aa92b20678c354b34085f62b762084b9788"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1392876393,
0,
2880
};
const CCheckpointData &Checkpoints() {
if (TestNet())
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef PANDORA_PSIZE_H
#define PANDORA_PSIZE_H
#include <cstdint>
#include <stdexcept>
#include <algorithm>
#include <initializer_list>
#include <iostream>
namespace nix {
template<typename T>
class NDSizeBase {
public:
typedef T value_type;
typedef T *iterator;
typedef const T *const_iterator;
typedef T &reference;
typedef const T const_reference;
typedef T *pointer;
typedef size_t difference_type;
typedef size_t size_type;
NDSizeBase()
: rank(0), dims(nullptr)
{
}
explicit NDSizeBase(size_t _rank)
: rank(_rank), dims(nullptr)
{
allocate();
}
explicit NDSizeBase(size_t _rank, T fillValue)
: rank(_rank), dims(nullptr)
{
allocate();
fill(fillValue);
}
template<typename U>
NDSizeBase(std::initializer_list<U> args)
: rank(args.size())
{
allocate();
std::transform(args.begin(), args.end(), dims, [](const U& val){ return static_cast<T>(val);});
}
//copy
NDSizeBase(const NDSizeBase &other)
: rank(other.rank), dims(nullptr)
{
allocate();
std::copy(other.dims, other.dims + rank, dims);
}
//move (not tested due to: http://llvm.org/bugs/show_bug.cgi?id=12208)
NDSizeBase(NDSizeBase &&other)
: rank(other.rank), dims(other.dims)
{
other.dims = nullptr;
other.rank = 0;
}
//copy and move assignment operator (not tested, see above)
NDSizeBase& operator=(NDSizeBase other) {
swap(other);
return *this;
}
T& operator[] (const size_t index) {
const NDSizeBase *this_const = const_cast<const NDSizeBase*>(this);
return const_cast<T&>(this_const->operator[](index));
}
const T& operator[] (const size_t index) const {
if (index + 1 > rank) {
throw std::out_of_range ("Index out of bounds");
}
return dims[index];
}
NDSizeBase<T>& operator++() {
std::for_each(begin(), end(), [](T &val) {
val++;
});
return *this;
}
NDSizeBase<T> operator++(int) {
NDSizeBase<T> snapshot(*this);
operator++();
return snapshot;
}
NDSizeBase<T>& operator+=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] += rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator+=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] += val;
}
return *this;
}
NDSizeBase<T>& operator+=(int val) {
return operator+=(static_cast<T>(val));
}
NDSizeBase<T>& operator--() {
std::for_each(begin(), end(), [](T &val) {
val--;
});
return *this;
}
NDSizeBase<T> operator--(int) {
NDSizeBase<T> snapshot(*this);
operator--();
return snapshot;
}
NDSizeBase<T>& operator-=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] -= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator-=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] -= val;
}
return *this;
}
NDSizeBase<T>& operator-=(int val) {
return operator-=(static_cast<T>(val));
}
void swap(NDSizeBase &other) {
using std::swap;
swap(dims, other.dims);
rank = other.rank;
}
NDSizeBase<T>& operator*=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] *= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator/=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] /= rhs.dims[i];
}
return *this;
}
size_t size() const { return rank; }
size_t nelms() const {
size_t product = 1;
std::for_each(begin(), end(), [&](T val) {
product *= val;
});
return product;
}
size_t dot(const NDSizeBase<T> &other) const {
if(size() != other.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
size_t res = 0;
for (size_t i = 0; i < rank; i++) {
res += dims[i] * other.dims[i];
}
return res;
}
T* data() { return dims; }
const T* data() const {return dims; }
void fill(T value) {
std::fill_n(dims, rank, value);
}
~NDSizeBase(){
delete[] dims;
}
//we are modelling a boost::Collection
iterator begin() { return dims; }
iterator end() { return dims + rank; }
const_iterator begin() const { return dims; }
const_iterator end() const { return dims + rank; }
bool empty() const { return rank == 0; }
private:
void allocate() {
if (rank > 0) {
dims = new T[rank];
}
}
size_t rank;
T *dims;
};
template<typename T>
NDSizeBase<T> operator-(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs -= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, T rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(T lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, int rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(int lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, T rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(T lhs, const NDSizeBase<T> &rhs)
{
return operator*(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, T rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(T lhs, const NDSizeBase<T> &rhs)
{
return operator/(rhs, lhs);
}
template<typename T>
inline bool operator==(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size())
return false;
for (size_t i = 0; i < lhs.size(); i++) {
if (lhs[i] != rhs[i])
return false;
}
return true;
}
template<typename T>
inline bool operator!=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !operator==(lhs, rhs);
}
template<typename T>
inline std::ostream& operator<<(std::ostream &os, const NDSizeBase<T> &ndsize)
{
os << "NDSize {";
for(size_t i = 0; i < ndsize.size(); i++) {
if (i != 0) {
os << ", ";
}
os << ndsize[i];
}
os << "}\n";
return os;
}
/* ***** */
//Ideally we would use unit64_t (and int64_t) here to directly specify
//the size we want, but for now we stick with how the hdf5 library
//defines hsize_t, otherwise we will run into issues when on plaforms
// where unit64_t is an incompatible type to the type of hsize_t
//(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)
typedef NDSizeBase<unsigned long long int> NDSize;
typedef NDSizeBase<long long int> NDSSize;
} // namespace nix
#endif // PANDORA_PSIZE_H
<commit_msg>NDSize: add a description to a exception<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef PANDORA_PSIZE_H
#define PANDORA_PSIZE_H
#include <cstdint>
#include <stdexcept>
#include <algorithm>
#include <initializer_list>
#include <iostream>
namespace nix {
template<typename T>
class NDSizeBase {
public:
typedef T value_type;
typedef T *iterator;
typedef const T *const_iterator;
typedef T &reference;
typedef const T const_reference;
typedef T *pointer;
typedef size_t difference_type;
typedef size_t size_type;
NDSizeBase()
: rank(0), dims(nullptr)
{
}
explicit NDSizeBase(size_t _rank)
: rank(_rank), dims(nullptr)
{
allocate();
}
explicit NDSizeBase(size_t _rank, T fillValue)
: rank(_rank), dims(nullptr)
{
allocate();
fill(fillValue);
}
template<typename U>
NDSizeBase(std::initializer_list<U> args)
: rank(args.size())
{
allocate();
std::transform(args.begin(), args.end(), dims, [](const U& val){ return static_cast<T>(val);});
}
//copy
NDSizeBase(const NDSizeBase &other)
: rank(other.rank), dims(nullptr)
{
allocate();
std::copy(other.dims, other.dims + rank, dims);
}
//move (not tested due to: http://llvm.org/bugs/show_bug.cgi?id=12208)
NDSizeBase(NDSizeBase &&other)
: rank(other.rank), dims(other.dims)
{
other.dims = nullptr;
other.rank = 0;
}
//copy and move assignment operator (not tested, see above)
NDSizeBase& operator=(NDSizeBase other) {
swap(other);
return *this;
}
T& operator[] (const size_t index) {
const NDSizeBase *this_const = const_cast<const NDSizeBase*>(this);
return const_cast<T&>(this_const->operator[](index));
}
const T& operator[] (const size_t index) const {
if (index + 1 > rank) {
throw std::out_of_range ("Index out of bounds");
}
return dims[index];
}
NDSizeBase<T>& operator++() {
std::for_each(begin(), end(), [](T &val) {
val++;
});
return *this;
}
NDSizeBase<T> operator++(int) {
NDSizeBase<T> snapshot(*this);
operator++();
return snapshot;
}
NDSizeBase<T>& operator+=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] += rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator+=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] += val;
}
return *this;
}
NDSizeBase<T>& operator+=(int val) {
return operator+=(static_cast<T>(val));
}
NDSizeBase<T>& operator--() {
std::for_each(begin(), end(), [](T &val) {
val--;
});
return *this;
}
NDSizeBase<T> operator--(int) {
NDSizeBase<T> snapshot(*this);
operator--();
return snapshot;
}
NDSizeBase<T>& operator-=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] -= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator-=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] -= val;
}
return *this;
}
NDSizeBase<T>& operator-=(int val) {
return operator-=(static_cast<T>(val));
}
void swap(NDSizeBase &other) {
using std::swap;
swap(dims, other.dims);
rank = other.rank;
}
NDSizeBase<T>& operator*=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] *= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator/=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] /= rhs.dims[i];
}
return *this;
}
size_t size() const { return rank; }
size_t nelms() const {
size_t product = 1;
std::for_each(begin(), end(), [&](T val) {
product *= val;
});
return product;
}
size_t dot(const NDSizeBase<T> &other) const {
if(size() != other.size()) {
throw std::out_of_range ("Dimensions do not match"); //fixme: use different exception
}
size_t res = 0;
for (size_t i = 0; i < rank; i++) {
res += dims[i] * other.dims[i];
}
return res;
}
T* data() { return dims; }
const T* data() const {return dims; }
void fill(T value) {
std::fill_n(dims, rank, value);
}
~NDSizeBase(){
delete[] dims;
}
//we are modelling a boost::Collection
iterator begin() { return dims; }
iterator end() { return dims + rank; }
const_iterator begin() const { return dims; }
const_iterator end() const { return dims + rank; }
bool empty() const { return rank == 0; }
private:
void allocate() {
if (rank > 0) {
dims = new T[rank];
}
}
size_t rank;
T *dims;
};
template<typename T>
NDSizeBase<T> operator-(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs -= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, T rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(T lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, int rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(int lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, T rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(T lhs, const NDSizeBase<T> &rhs)
{
return operator*(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, T rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(T lhs, const NDSizeBase<T> &rhs)
{
return operator/(rhs, lhs);
}
template<typename T>
inline bool operator==(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size())
return false;
for (size_t i = 0; i < lhs.size(); i++) {
if (lhs[i] != rhs[i])
return false;
}
return true;
}
template<typename T>
inline bool operator!=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !operator==(lhs, rhs);
}
template<typename T>
inline std::ostream& operator<<(std::ostream &os, const NDSizeBase<T> &ndsize)
{
os << "NDSize {";
for(size_t i = 0; i < ndsize.size(); i++) {
if (i != 0) {
os << ", ";
}
os << ndsize[i];
}
os << "}\n";
return os;
}
/* ***** */
//Ideally we would use unit64_t (and int64_t) here to directly specify
//the size we want, but for now we stick with how the hdf5 library
//defines hsize_t, otherwise we will run into issues when on plaforms
// where unit64_t is an incompatible type to the type of hsize_t
//(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)
typedef NDSizeBase<unsigned long long int> NDSize;
typedef NDSizeBase<long long int> NDSSize;
} // namespace nix
#endif // PANDORA_PSIZE_H
<|endoftext|> |
<commit_before>#include <vector>
#include <fstream>
#include <iostream>
#include <cassert>
#include <cmath>
#include "RandomNumberGenerator.h"
using namespace std;
using namespace DNest3;
class Data
{
private:
vector<double> logw, run_id;
vector< vector<double> > scalars;
int N;
public:
Data()
{ }
void load()
{
logw.clear(); run_id.clear(); scalars.clear();
double temp;
fstream fin("logw.txt", ios::in);
int k = 0;
while(fin >> temp)
{
logw.push_back(temp);
if(k == 0)
run_id.push_back(0);
else if(logw.back() == -1.)
run_id.push_back(run_id.back() + 1);
else
run_id.push_back(run_id.back());
k++;
}
fin.close();
fin.open("scalars.txt", ios::in);
double temp2;
while(fin >> temp && fin >> temp2)
{
vector<double> vec(2);
vec[0] = temp; vec[1] = temp2;
scalars.push_back(vec);
}
fin.close();
if(scalars.size() < logw.size())
{
logw.erase(logw.begin() + scalars.size(),
logw.end());
run_id.erase(run_id.begin() + scalars.size(),
run_id.end());
}
if(logw.size() < scalars.size())
{
scalars.erase(scalars.begin() + logw.size(),
scalars.end());
}
assert(logw.size() == scalars.size());
assert(logw.size() == run_id.size());
N = logw.size();
cout<<"# Loaded "<<N<<" points."<<endl;
}
friend class Assignment;
};
/************************************************************************/
class Assignment
{
private:
const Data& data;
vector<double> logX;
public:
Assignment(const Data& data)
:data(data)
{
}
void initialise()
{
logX.assign(data.N, 0.);
for(int i=0; i<data.N; i++)
{
if(data.logw[i] == -1.)
logX[i] = log(randomU());
else
logX[i] = logX[i-1] + log(randomU());
}
}
int update_all()
{
int total = 0;
for(int i=0; i<data.N; i++)
{
total += update(i);
cout<<"."<<flush;
}
cout<<endl;
return total;
}
// Gibbs sample one value
int update(int i)
{
double proposal;
// Range of values for proposal
double lower = -1E300;
double upper = 0.;
// Lower limit -- next point in same run (if it exists)
if( (i != (data.N-1)) &&
(data.run_id[i+1] == data.run_id[i]))
lower = logX[i+1];
// Upper limit -- previous point in same run (if it exists)
if( (i != 0) &&
(data.run_id[i-1] == data.run_id[i]))
upper = logX[i-1];
// If lower limit exists, generate uniformly between limits
if(lower != -1E300)
proposal = lower + (upper - lower)*randomU();
else // otherwise use exponential distribution
proposal = upper + log(randomU());
// Measure inconsistency
int inconsistency_old = 0;
int inconsistency_new = 0;
bool outside, inside;
for(int j=0; j<data.N; j++)
{
if(data.run_id[j] != data.run_id[i])
{
// See if distribution j is outside,
// inside, or unknown
outside = true;
inside = true;
for(int k=0; k<2; k++)
{
if(data.scalars[j][k] > data.scalars[i][k])
outside = false;
if(data.scalars[j][k] < data.scalars[i][k])
inside = false;
}
if(outside && (logX[j] < logX[i]))
inconsistency_old++;
if(inside && (logX[j] > logX[i]))
inconsistency_old++;
if(outside && (logX[j] < proposal))
inconsistency_new++;
if(inside && (logX[j] > proposal))
inconsistency_new++;
}
}
int inconsistency = inconsistency_old;
if(inconsistency_new <= inconsistency_old)
{
logX[i] = proposal;
inconsistency = inconsistency_new;
}
return inconsistency;
}
void save()
{
fstream fout("logX.txt", ios::out);
for(int i=0; i<data.N; i++)
fout<<logX[i]<<endl;
fout.close();
}
};
int main()
{
RandomNumberGenerator::initialise_instance();
RandomNumberGenerator::get_instance().set_seed(time(0));
Data data;
data.load();
Assignment assignment(data);
assignment.initialise();
int inconsistency;
int when_finished = -1;
int i=0;
while(true)
{
inconsistency = assignment.update_all();
assignment.save();
i++;
if(when_finished == -1 && inconsistency == 0)
when_finished = i;
cout<<i<<' '<<inconsistency<<endl;
if(when_finished != -1 && i > (1 + 1.2*when_finished))
break;
}
return 0;
}
<commit_msg>Don't print dots<commit_after>#include <vector>
#include <fstream>
#include <iostream>
#include <cassert>
#include <cmath>
#include "RandomNumberGenerator.h"
using namespace std;
using namespace DNest3;
class Data
{
private:
vector<double> logw, run_id;
vector< vector<double> > scalars;
int N;
public:
Data()
{ }
void load()
{
logw.clear(); run_id.clear(); scalars.clear();
double temp;
fstream fin("logw.txt", ios::in);
int k = 0;
while(fin >> temp)
{
logw.push_back(temp);
if(k == 0)
run_id.push_back(0);
else if(logw.back() == -1.)
run_id.push_back(run_id.back() + 1);
else
run_id.push_back(run_id.back());
k++;
}
fin.close();
fin.open("scalars.txt", ios::in);
double temp2;
while(fin >> temp && fin >> temp2)
{
vector<double> vec(2);
vec[0] = temp; vec[1] = temp2;
scalars.push_back(vec);
}
fin.close();
if(scalars.size() < logw.size())
{
logw.erase(logw.begin() + scalars.size(),
logw.end());
run_id.erase(run_id.begin() + scalars.size(),
run_id.end());
}
if(logw.size() < scalars.size())
{
scalars.erase(scalars.begin() + logw.size(),
scalars.end());
}
assert(logw.size() == scalars.size());
assert(logw.size() == run_id.size());
N = logw.size();
cout<<"# Loaded "<<N<<" points."<<endl;
}
friend class Assignment;
};
/************************************************************************/
class Assignment
{
private:
const Data& data;
vector<double> logX;
public:
Assignment(const Data& data)
:data(data)
{
}
void initialise()
{
logX.assign(data.N, 0.);
for(int i=0; i<data.N; i++)
{
if(data.logw[i] == -1.)
logX[i] = log(randomU());
else
logX[i] = logX[i-1] + log(randomU());
}
}
int update_all()
{
int total = 0;
for(int i=0; i<data.N; i++)
total += update(i);
return total;
}
// Gibbs sample one value
int update(int i)
{
double proposal;
// Range of values for proposal
double lower = -1E300;
double upper = 0.;
// Lower limit -- next point in same run (if it exists)
if( (i != (data.N-1)) &&
(data.run_id[i+1] == data.run_id[i]))
lower = logX[i+1];
// Upper limit -- previous point in same run (if it exists)
if( (i != 0) &&
(data.run_id[i-1] == data.run_id[i]))
upper = logX[i-1];
// If lower limit exists, generate uniformly between limits
if(lower != -1E300)
proposal = lower + (upper - lower)*randomU();
else // otherwise use exponential distribution
proposal = upper + log(randomU());
// Measure inconsistency
int inconsistency_old = 0;
int inconsistency_new = 0;
bool outside, inside;
for(int j=0; j<data.N; j++)
{
if(data.run_id[j] != data.run_id[i])
{
// See if distribution j is outside,
// inside, or unknown
outside = true;
inside = true;
for(int k=0; k<2; k++)
{
if(data.scalars[j][k] > data.scalars[i][k])
outside = false;
if(data.scalars[j][k] < data.scalars[i][k])
inside = false;
}
if(outside && (logX[j] < logX[i]))
inconsistency_old++;
if(inside && (logX[j] > logX[i]))
inconsistency_old++;
if(outside && (logX[j] < proposal))
inconsistency_new++;
if(inside && (logX[j] > proposal))
inconsistency_new++;
}
}
int inconsistency = inconsistency_old;
if(inconsistency_new <= inconsistency_old)
{
logX[i] = proposal;
inconsistency = inconsistency_new;
}
return inconsistency;
}
void save()
{
fstream fout("logX.txt", ios::out);
for(int i=0; i<data.N; i++)
fout<<logX[i]<<endl;
fout.close();
}
};
int main()
{
RandomNumberGenerator::initialise_instance();
RandomNumberGenerator::get_instance().set_seed(time(0));
Data data;
data.load();
Assignment assignment(data);
assignment.initialise();
int inconsistency;
int when_finished = -1;
int i=0;
while(true)
{
inconsistency = assignment.update_all();
assignment.save();
i++;
if(when_finished == -1 && inconsistency == 0)
when_finished = i;
cout<<i<<' '<<inconsistency<<endl;
if(when_finished != -1 && i > (1 + 1.2*when_finished))
break;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of // TODO: needs to adjusted for checkpoint checks, also see main.cpp
( 1, uint256("0xfd2e17af86267e6cb3b0e7446472ac431a6ffec868531464cad968cd20864015"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>changes<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of // TODO: needs to adjusted for checkpoint checks, also see main.cpp
( 1, uint256("0xf9a531d730b3881da6b19d8dc7de224ba8307f298e3a68839b"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|> |
<commit_before>// -----------------------------------------------------------------------------
// Copyright 2016 Marco Biasini
//
// 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 TYPUS_FLAGS_HH
#define TYPUS_FLAGS_HH
#include <type_traits>
namespace typus {
/**
* \brief A type-safe bitset for enums
*/
template <typename E>
class flags {
public:
using flag_storage_type = typename std::underlying_type<E>::type;
flags(): bits_(0) {}
flags(const flags<E> &rhs) = default;
explicit flags(E value):
bits_(reinterpret_cast<flag_storage_type&>(value)) {
}
flags<E> & operator |=(E value) {
bits_ |= reinterpret_cast<flag_storage_type&>(value);
return *this;
}
flags<E> operator | (E value) {
flags<E> rv(*this);
rv |= value;
return rv;
}
flag_storage_type bits() const {
return bits_;
}
void clear() {
bits_ = 0;
}
bool is_set(E value) const {
flag_storage_type t = reinterpret_cast<flag_storage_type&>(value);
return (bits_ & t) == t;
}
private:
flag_storage_type bits_;
};
}
#endif // TYPUS_FLAGS_HH
<commit_msg>add const<commit_after>// -----------------------------------------------------------------------------
// Copyright 2016 Marco Biasini
//
// 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 TYPUS_FLAGS_HH
#define TYPUS_FLAGS_HH
#include <type_traits>
namespace typus {
/**
* \brief A type-safe bitset for enums
*/
template <typename E>
class flags {
public:
using flag_storage_type = typename std::underlying_type<E>::type;
flags(): bits_(0) {}
flags(const flags<E> &rhs) = default;
explicit flags(E value):
bits_(reinterpret_cast<flag_storage_type&>(value)) {
}
flags<E> & operator |=(E value) {
bits_ |= reinterpret_cast<flag_storage_type&>(value);
return *this;
}
flags<E> operator | (E value) const {
flags<E> rv(*this);
rv |= value;
return rv;
}
flag_storage_type bits() const {
return bits_;
}
void clear() {
bits_ = 0;
}
bool is_set(E value) const {
flag_storage_type t = reinterpret_cast<flag_storage_type&>(value);
return (bits_ & t) == t;
}
private:
flag_storage_type bits_;
};
}
#endif // TYPUS_FLAGS_HH
<|endoftext|> |
<commit_before><commit_msg>typo<commit_after><|endoftext|> |
<commit_before>// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2005 2006 2009 2010 2013 2014 2015 2018 2019 2020 HörTech gGmbH
// Copyright © 2021 HörTech gGmbH
//
// openMHA 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, version 3 of the License.
//
// openMHA 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 Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>.
#include "mha_plugin.hh"
#include "mha_signal.hh"
#include "mha_parser.hh"
#include "mha_defs.h"
#include <math.h>
#include <time.h>
#include "mha_events.h"
#include "mha_filter.hh"
/**
\file gtfb_analyzer.cpp
\brief Gammatone Filterbank Analyzer Plugin
*/
namespace gtfb_analyzer {
/// Configuration for Gammatone Filterbank Analyzer.
struct gtfb_analyzer_cfg_t {
/// The order of the gammatone filters.
unsigned order;
/// The complex coefficients of the gammatone filter bands.
std::vector<mha_complex_t> coeff;
/// Combination of normalization and phase correction factor.
std::vector<mha_complex_t> norm_phase;
/** Storage for the (complex) output signal. Each of the
* real input audio channels is split into frequency bands with
* complex time signal output. The split complex time signal is
* again stored in a mha_wave_t buffer. Each complex time signal
* is stored as adjacent real and imaginary channels. Complex
* output from one source channel is stored in adjacent complex
* output channels.
*
* Example: If the input has 2 channels ch0 ch1, and gtfb_analyzer
* splits into 3 bands b0 b1 b2, then the order of output channels
* in s_out is:
* ch0_b0_real ch0_b0_imag ch0_b1_real ch0_b1_imag ch0_b2_real ch0_b2_imag
* ch1_b0_real ch1_b1_imag ch1_b1_real ch1_b1_imag ch1_b2_real ch1_b2_imag
*/
mha_wave_t s_out;
/** Storage for Filter state.
* Holds channels() * bands() * order complex filter states.
* Layout: state[(bands()*channel+band)*order+stage]
*/
std::vector<mha_complex_t> state;
/// Each band is split into this number of bands.
unsigned bands() const {return coeff.size();}
/// The number of separate audio channels.
unsigned channels() const {return s_out.num_channels / bands() / 2;}
/// The number of frames in one chunk.
unsigned frames() const {return s_out.num_frames;}
/// Returns pointer to filter states for that band
mha_complex_t * states(unsigned channel, unsigned band)
{ return &state[(bands()*channel+band)*order]; }
/**
* Create a configuration for Gammatone Filterbank Analyzer.
* @param ch Number of Audio channels.
* @param frames Number of Audio frames per chunk.
* @param ord The order of the gammatone filters.
* @param _coeff Complex gammatone filter coefficients.
* @param _norm_phase Normalization and phase correction factors.
*/
gtfb_analyzer_cfg_t(unsigned ch, unsigned frames, unsigned ord,
const std::vector<mha_complex_t> & _coeff,
const std::vector<mha_complex_t> & _norm_phase)
: order(ord),
coeff(_coeff),
norm_phase(_norm_phase),
state(_coeff.size() * ch * ord, mha_complex(0))
{
if (coeff.size() != norm_phase.size())
throw MHA_Error(__FILE__,__LINE__,
"Number (%zu) of coefficients differs from number "\
"(%zu) of normalization/phase-correction factors",
coeff.size(), norm_phase.size());
s_out.num_channels = ch * coeff.size() * 2;
s_out.num_frames = frames;
s_out.channel_info = 0;
s_out.buf = new mha_real_t[ch * bands() * frames * 2];
}
~gtfb_analyzer_cfg_t()
{delete [] s_out.buf; s_out.buf = 0;}
mha_complex_t & cvalue(unsigned frame, unsigned channel, unsigned band)
{
return *(reinterpret_cast<mha_complex_t *>(s_out.buf) +
(frame * channels() * bands() + channel * bands() + band));
}
};
/// Gammatone Filterbank Analyzer Plugin
class gtfb_analyzer_t : public MHAPlugin::plugin_t<gtfb_analyzer_cfg_t> {
public:
gtfb_analyzer_t(algo_comm_t iac, const std::string & configured_name);
mha_wave_t* process(mha_wave_t*);
void prepare(mhaconfig_t&);
private:
void update_cfg();
MHAEvents::patchbay_t<gtfb_analyzer_t> patchbay;
bool prepared;
MHAParser::int_t order;
MHAParser::vcomplex_t coeff;
MHAParser::vcomplex_t norm_phase;
};
}
/********************************************************************/
using MHAParser::StrCnv::val2str;
void gtfb_analyzer::gtfb_analyzer_t::update_cfg()
{
if (prepared) {
gtfb_analyzer_cfg_t * c =
new gtfb_analyzer_cfg_t(tftype.channels,
tftype.fragsize,
order.data,
coeff.data,
norm_phase.data);
push_config(c);
}
}
gtfb_analyzer::
gtfb_analyzer_t::gtfb_analyzer_t(algo_comm_t iac, const std::string &)
: MHAPlugin::plugin_t<gtfb_analyzer_cfg_t>("Gammatone Filterbank Analyzer",
iac),
prepared(false),
order("Order of gammatone filters", "4", "[0,["),
coeff("Filter coefficients of gammatone filters", "[]"),
norm_phase("Normalization & phase correction factors", "[]")
{
insert_item("coeff", &coeff);
patchbay.connect(&coeff.writeaccess,this,>fb_analyzer::gtfb_analyzer_t::update_cfg);
insert_item("norm_phase", &norm_phase);
patchbay.connect(&norm_phase.writeaccess,this,>fb_analyzer::gtfb_analyzer_t::update_cfg);
insert_item("order",&order);
patchbay.connect(&order.writeaccess,this,>fb_analyzer::gtfb_analyzer_t::update_cfg);
}
void gtfb_analyzer::gtfb_analyzer_t::prepare(mhaconfig_t& tf)
{
if (prepared)
throw MHA_ErrorMsg("gtfb_analyzer::gtfb_analyzer_t::prepare is called a second time");
if( tf.domain != MHA_WAVEFORM)
throw MHA_ErrorMsg("gtfb_analyzer: Only waveform input can be processed.");
tftype = tf;
tf.channels *= coeff.data.size() * 2;
prepared = true;
update_cfg();
}
/**
* Filters a complex input sample with the given filter coefficient.
* No normalization takes place. The implementation is
* tail-recursive and to exploit compiler optimization.
*
* @param input The complex input sample
*
* @param coeff The complex filter coefficient
*
* @param states Pointer to the array of complex filter states.
*
* @param orders The filter order
*
* @return A const ref to the filtered sample
*
*/
static inline const mha_complex_t &
filter_complex(const mha_complex_t & input,
const mha_complex_t & coeff,
mha_complex_t * states,
unsigned orders)
{
if (orders == 0) return input;
return filter_complex(((*states) *= coeff) += input,
coeff, states+1, orders-1);
}
/**
* Filters a real input sample with the given filter coefficient and
* applies the given normalization with phase correction.
*
* @param input The real input sample
*
* @param tmp_complex A reference to a mha_complex_t used for intermediate
* results. No assumptions should be made about the state of tmp_complex
* after the return of filter_real. This is an optimization to reduce the number
* of dtor/ctor calls of mha_complex_t
*
* @param coeff The complex filter coefficient
*
* @param states Pointer to the array of complex filter states.
*
* @param orders The filter order
*
* @param normphase Normalization coefficient including the phase correction
*
* @return A const ref to the filtered sample
*
*/
static inline const mha_complex_t &
filter_real(mha_real_t input,
mha_complex_t & tmp_complex,
const mha_complex_t & coeff,
mha_complex_t * states,
unsigned orders,
const mha_complex_t & normphase)
{
return filter_complex((tmp_complex = normphase) *= input,
coeff, states, orders);
}
mha_wave_t* gtfb_analyzer::gtfb_analyzer_t::process(mha_wave_t* s)
{
poll_config();
mha_complex_t tmp_complex = {0,0};
for (unsigned frame = 0; frame < s->num_frames; ++frame) {
for (unsigned channel = 0; channel < s->num_channels; ++channel) {
for (unsigned band = 0; band < cfg->bands(); ++band) {
cfg->cvalue(frame, channel, band) =
filter_real(value(s,frame,channel),
tmp_complex,
cfg->coeff[band],
cfg->states(channel,band),
cfg->order,
cfg->norm_phase[band]);
MHAFilter::make_friendly_number(cfg->cvalue(frame, channel, band));
}
}
}
return &cfg->s_out;
}
MHAPLUGIN_CALLBACKS(gtfb_analyzer,gtfb_analyzer::gtfb_analyzer_t,wave,wave)
MHAPLUGIN_DOCUMENTATION\
(gtfb_analyzer,
"filterbank",
"Implements a complex-valued gammatone filterbank using"
" cascaded first-order filters as described in"
" Hohmann(2002)\\footnote{"
" Volker Hohmann,"
" Frequency analysis and synthesis using a Gammatone"
" filterbank."
" Acta Acustica united with Acustica 88(3),"
" pp. 433-442, 2002."
"}, and Herzke and Hohmann(2007)\\footnote{"
" Tobias Herzke and Volker Hohmann,"
" Improved Numerical Methods for Gammatone Filterbank"
" Analysis and Synthesis."
" Acta Acustica united with Acustica 93(3), "
" pp. 498-500, 2007."
"}. Set the parameter order to the desired gammatone"
" filter order. The coeff is a vector of complex filter"
" coefficients, one for each filterbank frequency band."
" The complex coefficients need to be computed outside"
" of the MHA, e.g. with the help of the matlab"
" implementation of the gammatone filterbank which can"
" be downloaded from"
" https://uol.de/mediphysik/downloads/. Similarly, the"
" combination of normalization factors and phases also"
" have to be computed outside of the MHA, e.g. also"
" with the same matlab implementation of this gammatone"
" filterbank."
"\n\n"
" The output signal produced by this plugin contains"
" the complex output signal produced by the cascaded"
" gammatone filters in each band. Because the MHA time "
" domain signal representation does not support storing"
" of complex values, real and imaginary parts are"
" stored in different output channels."
"\n\n"
" Example: If the input has 2 channels (ch0, ch1),"
" and \\texttt{gtfb\\_analyzer} splits into 3 bands (b0, b1, b2),"
" then the order of output channels produced by"
" \\texttt{gtfb\\_analyzer} is:"
" ch0\\_b0\\_real, ch0\\_b0\\_imag, ch0\\_b1\\_real, ch0\\_b1\\_imag,"
" ch0\\_b2\\_real, ch0\\_b2\\_imag, ch1\\_b0\\_real, ch1\\_b1\\_imag,"
" ch1\\_b1\\_real, ch1\\_b1\\_imag, ch1\\_b2\\_real, ch1\\_b2\\_imag"
)
// Local Variables:
// compile-command: "make"
// c-basic-offset: 4
// indent-tabs-mode: nil
// coding: utf-8-unix
// End:
<commit_msg>Enhance gtfb_analyzer docs and implementation<commit_after>// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2005 2006 2009 2010 2013 2014 2015 2018 2019 2020 HörTech gGmbH
// Copyright © 2021 HörTech gGmbH
//
// openMHA 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, version 3 of the License.
//
// openMHA 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 Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>.
#include "mha_plugin.hh"
#include "mha_signal.hh"
#include "mha_parser.hh"
#include "mha_defs.h"
#include <math.h>
#include <time.h>
#include "mha_events.h"
#include "mha_filter.hh"
/**
\file gtfb_analyzer.cpp
\brief Gammatone Filterbank Analyzer Plugin
*/
namespace gtfb_analyzer {
/// Configuration for Gammatone Filterbank Analyzer.
struct gtfb_analyzer_cfg_t {
/// The order of the gammatone filters.
unsigned order;
/// The complex coefficients of the gammatone filter bands.
std::vector<mha_complex_t> coeff;
/// Combination of normalization and phase correction factor.
std::vector<mha_complex_t> norm_phase;
/** Storage for the (complex) output signal. Each of the
* real input audio channels is split into frequency bands with
* complex time signal output. The split complex time signal is
* again stored in a mha_wave_t buffer. Each complex time signal
* is stored as adjacent real and imaginary channels. Complex
* output from one source channel is stored in adjacent complex
* output channels.
*
* Example: If the input has 2 channels ch0 ch1, and gtfb_analyzer
* splits into 3 bands b0 b1 b2, then the order of output channels
* in s_out is:
* ch0_b0_real ch0_b0_imag ch0_b1_real ch0_b1_imag ch0_b2_real ch0_b2_imag
* ch1_b0_real ch1_b1_imag ch1_b1_real ch1_b1_imag ch1_b2_real ch1_b2_imag
*/
mha_wave_t s_out;
/** Storage for Filter state.
* Holds channels() * bands() * order complex filter states.
* Layout: state[(bands()*channel+band)*order+stage]
*/
std::vector<mha_complex_t> state;
/// Each band is split into this number of bands.
unsigned bands() const {return coeff.size();}
/// The number of separate audio channels.
unsigned channels() const {return s_out.num_channels / bands() / 2;}
/// The number of frames in one chunk.
unsigned frames() const {return s_out.num_frames;}
/// Returns pointer to filter states for that band
mha_complex_t * states(unsigned channel, unsigned band)
{ return &state[(bands()*channel+band)*order]; }
/**
* Create a configuration for Gammatone Filterbank Analyzer.
* @param ch Number of Audio channels.
* @param frames Number of Audio frames per chunk.
* @param ord The order of the gammatone filters.
* @param _coeff Complex gammatone filter coefficients.
* @param _norm_phase Normalization and phase correction factors.
*/
gtfb_analyzer_cfg_t(unsigned ch, unsigned frames, unsigned ord,
const std::vector<mha_complex_t> & _coeff,
const std::vector<mha_complex_t> & _norm_phase)
: order(ord),
coeff(_coeff),
norm_phase(_norm_phase),
state(_coeff.size() * ch * ord, mha_complex(0))
{
if (coeff.size() != norm_phase.size())
throw MHA_Error(__FILE__,__LINE__,
"Number (%zu) of coefficients differs from number "\
"(%zu) of normalization/phase-correction factors",
coeff.size(), norm_phase.size());
s_out.num_channels = ch * coeff.size() * 2;
s_out.num_frames = frames;
s_out.channel_info = 0;
s_out.buf = new mha_real_t[ch * bands() * frames * 2];
}
~gtfb_analyzer_cfg_t()
{delete [] s_out.buf; s_out.buf = 0;}
mha_complex_t & cvalue(unsigned frame, unsigned channel, unsigned band)
{
return *(reinterpret_cast<mha_complex_t *>(s_out.buf) +
(frame * channels() * bands() + channel * bands() + band));
}
};
/// Gammatone Filterbank Analyzer Plugin
class gtfb_analyzer_t : public MHAPlugin::plugin_t<gtfb_analyzer_cfg_t> {
public:
gtfb_analyzer_t(algo_comm_t iac, const std::string & configured_name);
mha_wave_t* process(mha_wave_t*);
void prepare(mhaconfig_t&);
void release();
private:
void update_cfg();
MHAEvents::patchbay_t<gtfb_analyzer_t> patchbay;
bool prepared;
MHAParser::int_t order;
MHAParser::vcomplex_t coeff;
MHAParser::vcomplex_t norm_phase;
};
}
/********************************************************************/
using MHAParser::StrCnv::val2str;
void gtfb_analyzer::gtfb_analyzer_t::update_cfg()
{
if (prepared) {
gtfb_analyzer_cfg_t * c =
new gtfb_analyzer_cfg_t(tftype.channels,
tftype.fragsize,
order.data,
coeff.data,
norm_phase.data);
push_config(c);
}
}
gtfb_analyzer::
gtfb_analyzer_t::gtfb_analyzer_t(algo_comm_t iac, const std::string &)
: MHAPlugin::plugin_t<gtfb_analyzer_cfg_t>("Gammatone Filterbank Analyzer",
iac),
prepared(false),
order("Order of gammatone filters", "4", "[0,["),
coeff("Filter coefficients of gammatone filters", "[]"),
norm_phase("Normalization & phase correction factors", "[]")
{
insert_item("coeff", &coeff);
patchbay.connect(&coeff.writeaccess,this,>fb_analyzer::gtfb_analyzer_t::update_cfg);
insert_item("norm_phase", &norm_phase);
patchbay.connect(&norm_phase.writeaccess,this,>fb_analyzer::gtfb_analyzer_t::update_cfg);
insert_item("order",&order);
patchbay.connect(&order.writeaccess,this,>fb_analyzer::gtfb_analyzer_t::update_cfg);
}
void gtfb_analyzer::gtfb_analyzer_t::prepare(mhaconfig_t& tf)
{
if (prepared)
throw MHA_ErrorMsg("gtfb_analyzer::gtfb_analyzer_t::prepare is called a second time");
if( tf.domain != MHA_WAVEFORM)
throw MHA_ErrorMsg("gtfb_analyzer: Only waveform input can be processed.");
tftype = tf;
tf.channels *= coeff.data.size() * 2;
prepared = true;
update_cfg();
}
void gtfb_analyzer::gtfb_analyzer_t::release()
{
prepared = false;
}
/**
* Filters a complex input sample with the given filter coefficient.
* No normalization takes place. The implementation is
* tail-recursive and to exploit compiler optimization.
*
* @param input The complex input sample
*
* @param coeff The complex filter coefficient
*
* @param states Pointer to the array of complex filter states.
*
* @param orders The filter order
*
* @return A const ref to the filtered sample
*
*/
static inline const mha_complex_t &
filter_complex(const mha_complex_t & input,
const mha_complex_t & coeff,
mha_complex_t * states,
unsigned orders)
{
if (orders == 0) return input;
return filter_complex(((*states) *= coeff) += input,
coeff, states+1, orders-1);
}
/**
* Filters a real input sample with the given filter coefficient and
* applies the given normalization with phase correction.
*
* @param input The real input sample
*
* @param tmp_complex A reference to a mha_complex_t used for intermediate
* results. No assumptions should be made about the state of tmp_complex
* after the return of filter_real. This is an optimization to reduce the number
* of dtor/ctor calls of mha_complex_t
*
* @param coeff The complex filter coefficient
*
* @param states Pointer to the array of complex filter states.
*
* @param orders The filter order
*
* @param normphase Normalization coefficient including the phase correction
*
* @return A const ref to the filtered sample
*
*/
static inline const mha_complex_t &
filter_real(mha_real_t input,
mha_complex_t & tmp_complex,
const mha_complex_t & coeff,
mha_complex_t * states,
unsigned orders,
const mha_complex_t & normphase)
{
return filter_complex((tmp_complex = normphase) *= input,
coeff, states, orders);
}
mha_wave_t* gtfb_analyzer::gtfb_analyzer_t::process(mha_wave_t* s)
{
poll_config();
mha_complex_t tmp_complex = {0,0};
for (unsigned frame = 0; frame < s->num_frames; ++frame) {
for (unsigned channel = 0; channel < s->num_channels; ++channel) {
for (unsigned band = 0; band < cfg->bands(); ++band) {
cfg->cvalue(frame, channel, band) =
filter_real(value(s,frame,channel),
tmp_complex,
cfg->coeff[band],
cfg->states(channel,band),
cfg->order,
cfg->norm_phase[band]);
MHAFilter::make_friendly_number(cfg->cvalue(frame, channel, band));
}
}
}
return &cfg->s_out;
}
MHAPLUGIN_CALLBACKS(gtfb_analyzer,gtfb_analyzer::gtfb_analyzer_t,wave,wave)
MHAPLUGIN_DOCUMENTATION\
(gtfb_analyzer,
"filterbank",
"Implements a complex-valued gammatone filterbank using"
" cascaded first-order filters as described in"
" Hohmann(2002)\\footnote{"
" Volker Hohmann,"
" Frequency analysis and synthesis using a Gammatone"
" filterbank."
" Acta Acustica united with Acustica 88(3),"
" pp. 433-442, 2002."
"}, and Herzke and Hohmann(2007)\\footnote{"
" Tobias Herzke and Volker Hohmann,"
" Improved Numerical Methods for Gammatone Filterbank"
" Analysis and Synthesis."
" Acta Acustica united with Acustica 93(3), "
" pp. 498-500, 2007."
"}. Set the parameter order to the desired gammatone"
" filter order. The coeff is a vector of complex filter"
" coefficients, one for each filterbank frequency band."
" The complex coefficients need to be computed outside"
" of the MHA, e.g. with the help of the matlab"
" implementation of the gammatone filterbank which can"
" be downloaded from"
" https://uol.de/mediphysik/downloads/. Similarly, the"
" combination of normalization factors and phases also"
" have to be computed outside of the MHA, e.g. also"
" with the same matlab implementation of this gammatone"
" filterbank."
"\n\n"
" The output signal produced by this plugin contains"
" the complex output signal produced by the cascaded"
" gammatone filters in each band. Because the MHA time "
" domain signal representation does not support storing"
" of complex values, real and imaginary parts are"
" stored in different output channels."
"\n\n"
" Example: If the input has 2 channels (ch0, ch1),"
" and \\texttt{gtfb\\_analyzer} splits into 3 bands (b0, b1, b2),"
" then the order of output channels produced by"
" \\texttt{gtfb\\_analyzer} is:"
" ch0\\_b0\\_real, ch0\\_b0\\_imag, ch0\\_b1\\_real, ch0\\_b1\\_imag,"
" ch0\\_b2\\_real, ch0\\_b2\\_imag, ch1\\_b0\\_real, ch1\\_b1\\_imag,"
" ch1\\_b1\\_real, ch1\\_b1\\_imag, ch1\\_b2\\_real, ch1\\_b2\\_imag"
"\n\n\n"
"\\textbf{Attention:}\n\n"
"The recursive low-pass filters in this plugin have no protection against"
" subnormals. In real-time processing tasks, input signal of absolute"
" silence (amplitude 0.0) must therefore be avoided. The \\texttt{noise}"
" plugin can be used for this purpose, by adding inaudible noise"
" to the signal that enters this plugin."
)
// Local Variables:
// compile-command: "make"
// c-basic-offset: 4
// indent-tabs-mode: nil
// coding: utf-8-unix
// End:
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "test.hpp"
#include "date.hpp"
TEST_CASE("date/minus/days") {
budget::date a(2010, 5, 6);
a -= budget::days(1);
FAST_CHECK_EQ(a.year(), 2010);
FAST_CHECK_EQ(a.month(), 5);
FAST_CHECK_EQ(a.day(), 5);
}
<commit_msg>Draft plan for date unit tests<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "test.hpp"
#include "date.hpp"
using namespace std::string_literals;
TEST_CASE("date/to_string") {
budget::date a(1988, 4, 9);
FAST_CHECK_EQ(budget::date_to_string(a), "1988-04-09"s);
FAST_CHECK_EQ(budget::to_string(a), "1988-04-09"s);
budget::date b(2111, 10, 10);
FAST_CHECK_EQ(budget::date_to_string(b), "2111-10-10"s);
FAST_CHECK_EQ(budget::to_string(b), "2111-10-10"s);
}
TEST_CASE("date/from_string") {
auto as = budget::from_string("1988-04-09");
auto bs = budget::from_string("2111-10-10");
budget::date a(1988, 4, 9);
budget::date b(2111, 10, 10);
FAST_CHECK_EQ(a, as);
FAST_CHECK_EQ(b, bs);
}
TEST_CASE("date/minus/days") {
budget::date a(2010, 5, 6);
a -= budget::days(1);
FAST_CHECK_EQ(a.year(), 2010);
FAST_CHECK_EQ(a.month(), 5);
FAST_CHECK_EQ(a.day(), 5);
a -= budget::days(10);
FAST_CHECK_EQ(a.year(), 2010);
FAST_CHECK_EQ(a.month(), 4);
FAST_CHECK_EQ(a.day(), 25);
}
TEST_CASE("date/minus/month") {
budget::date a(2010, 5, 6);
a -= budget::months(1);
FAST_CHECK_EQ(a.year(), 2010);
FAST_CHECK_EQ(a.month(), 4);
FAST_CHECK_EQ(a.day(), 6);
a -= budget::months(10);
FAST_CHECK_EQ(a.year(), 2009);
FAST_CHECK_EQ(a.month(), 6);
FAST_CHECK_EQ(a.day(), 6);
}
TEST_CASE("date/minus/years") {
budget::date a(2010, 5, 6);
a -= budget::years(1);
FAST_CHECK_EQ(a.year(), 2009);
FAST_CHECK_EQ(a.month(), 5);
FAST_CHECK_EQ(a.day(), 6);
a -= budget::years(10);
FAST_CHECK_EQ(a.year(), 1999);
FAST_CHECK_EQ(a.month(), 5);
FAST_CHECK_EQ(a.day(), 6);
}
// TODO Test for plus
// TODO Test for leap years
// TODO Test for start_of_week
// TODO Test for start_of_month
// TODO Test for week()
// TODO Test for year_days()
// TODO Test for day_of_the_week
// TODO Test for comparisons
// TODO Test for date differences
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCPluginManager.cpp
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCPluginManager
//
// -------------------------------------------------------------------------
//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"
#pragma comment( lib, "ws2_32.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif
#endif
bool NFCPluginManager::LoadPlugin()
{
rapidxml::file<> fdoc( "Plugin.xml" );
rapidxml::xml_document<> doc;
doc.parse<0>( fdoc.data() );
rapidxml::xml_node<>* pRoot = doc.first_node();
for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
{
const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
const char* strMain = pPluginNode->first_attribute( "Main" )->value();
mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));
}
rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
if (!pPluginAppNode)
{
NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
if (!strAppID)
{
NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
if (!NF_StrTo(strAppID, mAppID))
{
NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
return false;
}
return true;
}
void NFCPluginManager::Registered(NFIPlugin* plugin)
{
std::string strPluginName = plugin->GetPluginName();
if (!FindPlugin(strPluginName))
{
bool bFind = false;
PluginNameMap::iterator it = mPluginNameMap.begin();
for (it; it != mPluginNameMap.end(); ++it)
{
if (strPluginName == it->first)
{
bFind = true;
break;
}
}
if (bFind)
{
mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
plugin->Install();
}
}
}
void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
if (it != mPluginInstanceMap.end())
{
it->second->Uninstall();
delete it->second;
it->second = NULL;
mPluginInstanceMap.erase(it);
}
}
NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
if (it != mPluginInstanceMap.end())
{
return it->second;
}
return NULL;
}
bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
bool bRet = true;
PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
for (; it != mPluginInstanceMap.end(); ++it)
{
bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
bRet = bRet && tembRet;
}
ExecuteEvent();
return bRet;
}
void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
if (!FindModule(strModuleName))
{
mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
}
}
void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
if (it != mModuleInstanceMap.end())
{
mModuleInstanceMap.erase(it);
}
}
NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
if (it != mModuleInstanceMap.end())
{
return it->second;
}
return NULL;
}
bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
LoadPlugin();
#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
PluginNameMap::iterator it = mPluginNameMap.begin();
for (it; it != mPluginNameMap.end(); ++it)
{
LoadPluginLibrary(it->first);
}
#endif
#else
// PluginNameList::iterator it = mPluginNameList.begin();
// for (it; it != mPluginNameList.end(); it++)
// {
// const std::string& strPluginName = *it;
// CREATE_PLUGIN( this, strPluginName );
// }
// CREATE_PLUGIN(this, NFKernelPlugin)
// CREATE_PLUGIN(this, NFEventProcessPlugin)
// CREATE_PLUGIN(this, NFConfigPlugin)
#endif
PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
{
itInstance->second->Init();
}
return true;
}
bool NFCPluginManager::AfterInit()
{
PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
{
itAfterInstance->second->AfterInit();
}
return true;
}
bool NFCPluginManager::CheckConfig()
{
PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
{
itCheckInstance->second->CheckConfig();
}
return true;
}
bool NFCPluginManager::BeforeShut()
{
PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
{
itBeforeInstance->second->BeforeShut();
}
return true;
}
bool NFCPluginManager::Shut()
{
PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
{
itInstance->second->Shut();
}
#ifdef NF_DYNAMIC_PLUGIN
PluginNameMap::iterator it = mPluginNameMap.begin();
for (it; it != mPluginNameMap.end(); it++)
{
UnLoadPluginLibrary(it->first);
}
#else
// DESTROY_PLUGIN(this, NFConfigPlugin)
// DESTROY_PLUGIN(this, NFEventProcessPlugin)
// DESTROY_PLUGIN(this, NFKernelPlugin)
#endif
mPluginInstanceMap.clear();
mPluginNameMap.clear();
return true;
}
bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
if (it == mPluginLibMap.end())
{
NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
bool bLoad = pLib->Load();
if (bLoad)
{
mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));
DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
if (!pFunc)
{
std::cout << "Find function DllStartPlugin Failed in " << strPluginDLLName << std::endl;
assert(0);
return false;
}
pFunc(this);
return true;
}
else
{
assert(0);
std::cout << "Load " << strPluginDLLName << "Failed" << std::endl;
}
}
return false;
}
bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
if (it != mPluginLibMap.end())
{
NFCDynLib* pLib = it->second;
DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");
if (pFunc)
{
pFunc(this);
}
pLib->UnLoad();
delete pLib;
pLib = NULL;
mPluginLibMap.erase(it);
return true;
}
return false;
}
bool NFCPluginManager::ReInitialize()
{
PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
{
itBeforeInstance->second->BeforeShut();
}
PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
{
itShutDownInstance->second->Shut();
}
PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
{
itInstance->second->Init();
}
PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
{
itAfterInstance->second->AfterInit();
}
PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
{
itCheckInstance->second->CheckConfig();
}
return true;
}
void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
//ӵУÿִ֡
mxQueue.Push(message);
}
bool NFCPluginManager::ExecuteEvent()
{
NFIActorMessage xMsg;
bool bRet = false;
bRet = mxQueue.Pop(xMsg);
while (bRet)
{
if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
{
xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nSubMsgID, xMsg.data);
}
bRet = mxQueue.Pop(xMsg);
}
return true;
}
<commit_msg>modify printing<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCPluginManager.cpp
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCPluginManager
//
// -------------------------------------------------------------------------
//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"
#pragma comment( lib, "ws2_32.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif
#endif
bool NFCPluginManager::LoadPlugin()
{
rapidxml::file<> fdoc( "Plugin.xml" );
rapidxml::xml_document<> doc;
doc.parse<0>( fdoc.data() );
rapidxml::xml_node<>* pRoot = doc.first_node();
for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
{
const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
const char* strMain = pPluginNode->first_attribute( "Main" )->value();
mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));
}
rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
if (!pPluginAppNode)
{
NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
if (!strAppID)
{
NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
if (!NF_StrTo(strAppID, mAppID))
{
NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
return false;
}
return true;
}
void NFCPluginManager::Registered(NFIPlugin* plugin)
{
std::string strPluginName = plugin->GetPluginName();
if (!FindPlugin(strPluginName))
{
bool bFind = false;
PluginNameMap::iterator it = mPluginNameMap.begin();
for (it; it != mPluginNameMap.end(); ++it)
{
if (strPluginName == it->first)
{
bFind = true;
break;
}
}
if (bFind)
{
mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
plugin->Install();
}
}
}
void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
if (it != mPluginInstanceMap.end())
{
it->second->Uninstall();
delete it->second;
it->second = NULL;
mPluginInstanceMap.erase(it);
}
}
NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
if (it != mPluginInstanceMap.end())
{
return it->second;
}
return NULL;
}
bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
bool bRet = true;
PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
for (; it != mPluginInstanceMap.end(); ++it)
{
bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
bRet = bRet && tembRet;
}
ExecuteEvent();
return bRet;
}
void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
if (!FindModule(strModuleName))
{
mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
}
}
void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
if (it != mModuleInstanceMap.end())
{
mModuleInstanceMap.erase(it);
}
}
NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
if (it != mModuleInstanceMap.end())
{
return it->second;
}
return NULL;
}
bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
LoadPlugin();
#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
PluginNameMap::iterator it = mPluginNameMap.begin();
for (it; it != mPluginNameMap.end(); ++it)
{
LoadPluginLibrary(it->first);
}
#endif
#else
// PluginNameList::iterator it = mPluginNameList.begin();
// for (it; it != mPluginNameList.end(); it++)
// {
// const std::string& strPluginName = *it;
// CREATE_PLUGIN( this, strPluginName );
// }
// CREATE_PLUGIN(this, NFKernelPlugin)
// CREATE_PLUGIN(this, NFEventProcessPlugin)
// CREATE_PLUGIN(this, NFConfigPlugin)
#endif
PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
{
itInstance->second->Init();
}
return true;
}
bool NFCPluginManager::AfterInit()
{
PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
{
itAfterInstance->second->AfterInit();
}
return true;
}
bool NFCPluginManager::CheckConfig()
{
PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
{
itCheckInstance->second->CheckConfig();
}
return true;
}
bool NFCPluginManager::BeforeShut()
{
PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
{
itBeforeInstance->second->BeforeShut();
}
return true;
}
bool NFCPluginManager::Shut()
{
PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
{
itInstance->second->Shut();
}
#ifdef NF_DYNAMIC_PLUGIN
PluginNameMap::iterator it = mPluginNameMap.begin();
for (it; it != mPluginNameMap.end(); it++)
{
UnLoadPluginLibrary(it->first);
}
#else
// DESTROY_PLUGIN(this, NFConfigPlugin)
// DESTROY_PLUGIN(this, NFEventProcessPlugin)
// DESTROY_PLUGIN(this, NFKernelPlugin)
#endif
mPluginInstanceMap.clear();
mPluginNameMap.clear();
return true;
}
bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
if (it == mPluginLibMap.end())
{
NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
bool bLoad = pLib->Load();
if (bLoad)
{
mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));
DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
if (!pFunc)
{
std::cout << "Find function DllStartPlugin Failed in " << strPluginDLLName << std::endl;
assert(0);
return false;
}
pFunc(this);
return true;
}
else
{
std::cout << "Load " << strPluginDLLName << "Failed" << std::endl;
assert(0);
}
}
return false;
}
bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
if (it != mPluginLibMap.end())
{
NFCDynLib* pLib = it->second;
DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");
if (pFunc)
{
pFunc(this);
}
pLib->UnLoad();
delete pLib;
pLib = NULL;
mPluginLibMap.erase(it);
return true;
}
return false;
}
bool NFCPluginManager::ReInitialize()
{
PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
{
itBeforeInstance->second->BeforeShut();
}
PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
{
itShutDownInstance->second->Shut();
}
PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
{
itInstance->second->Init();
}
PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
{
itAfterInstance->second->AfterInit();
}
PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
{
itCheckInstance->second->CheckConfig();
}
return true;
}
void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
//ӵУÿִ֡
mxQueue.Push(message);
}
bool NFCPluginManager::ExecuteEvent()
{
NFIActorMessage xMsg;
bool bRet = false;
bRet = mxQueue.Pop(xMsg);
while (bRet)
{
if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
{
xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nSubMsgID, xMsg.data);
}
bRet = mxQueue.Pop(xMsg);
}
return true;
}
<|endoftext|> |
<commit_before>#include "renderer/render_view_observer.h"
#include "base/strings/stringprintf.h"
#include "base/strings/string_util.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "v8/include/v8.h"
namespace brightray_example {
namespace {
void HelloWorld(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(v8::String::New(base::StringPrintf("Hello, World from %s:%d!", __FILE__, __LINE__).c_str()));
}
v8::Local<v8::ObjectTemplate> CreateConstructorTemplate() {
auto constructor_template = v8::ObjectTemplate::New();
constructor_template->SetAccessor(v8::String::New("helloWorld"), HelloWorld);
return constructor_template;
}
v8::Local<v8::ObjectTemplate> ConstructorTemplate() {
auto isolate = v8::Isolate::GetCurrent();
static v8::Persistent<v8::ObjectTemplate> constructor_template(isolate, CreateConstructorTemplate());
return v8::Local<v8::ObjectTemplate>::New(isolate, constructor_template);
}
}
RenderViewObserver::RenderViewObserver(content::RenderView *render_view)
: content::RenderViewObserver(render_view) {
}
RenderViewObserver::~RenderViewObserver() {
}
void RenderViewObserver::DidClearWindowObject(WebKit::WebFrame* frame) {
GURL url = frame->document().url();
if (!url.SchemeIs("http") ||
!url.DomainIs("adam.roben.org") ||
!StartsWithASCII(url.path(), "/brightray_example/", true))
return;
v8::HandleScope scope(v8::Isolate::GetCurrent());
auto context = frame->mainWorldScriptContext();
v8::Context::Scope contextScope(context);
context->Global()->Set(v8::String::New("brightray_example"), ConstructorTemplate()->NewInstance());
}
}
<commit_msg>Update for V8 API changes<commit_after>#include "renderer/render_view_observer.h"
#include "base/strings/stringprintf.h"
#include "base/strings/string_util.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "v8/include/v8.h"
namespace brightray_example {
namespace {
void HelloWorld(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), base::StringPrintf("Hello, World from %s:%d!", __FILE__, __LINE__).c_str()));
}
v8::Local<v8::ObjectTemplate> CreateConstructorTemplate() {
auto constructor_template = v8::ObjectTemplate::New();
constructor_template->SetAccessor(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), "helloWorld"), HelloWorld);
return constructor_template;
}
v8::Local<v8::ObjectTemplate> ConstructorTemplate() {
auto isolate = v8::Isolate::GetCurrent();
static v8::Persistent<v8::ObjectTemplate> constructor_template(isolate, CreateConstructorTemplate());
return v8::Local<v8::ObjectTemplate>::New(isolate, constructor_template);
}
}
RenderViewObserver::RenderViewObserver(content::RenderView *render_view)
: content::RenderViewObserver(render_view) {
}
RenderViewObserver::~RenderViewObserver() {
}
void RenderViewObserver::DidClearWindowObject(WebKit::WebFrame* frame) {
GURL url = frame->document().url();
if (!url.SchemeIs("http") ||
!url.DomainIs("adam.roben.org") ||
!StartsWithASCII(url.path(), "/brightray_example/", true))
return;
v8::HandleScope scope(v8::Isolate::GetCurrent());
auto context = frame->mainWorldScriptContext();
v8::Context::Scope contextScope(context);
context->Global()->Set(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), "brightray_example"), ConstructorTemplate()->NewInstance());
}
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
if (m_Options.RawInput)
// FIXME: What kind of result we are looking for in that case?
m_Interp.declare(input);
else
m_Interp.processLine(input, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
if (CurPtr == MB->getBufferEnd()) {
// Already at end of the buffer, return just the zero byte at the end.
return StringRef(CurPtr, 0);
}
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
if(Str.empty())
return Str;
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
ends = begins + 1;
return llvm::StringRef(Str.c_str() + begins, ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
Interpreter::CompilationResult interpRes
= m_Interp.declare(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""));
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<commit_msg>Forgotten changes.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
if (m_Options.RawInput)
m_Interp.declare(input);
else
m_Interp.process(input, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
if (CurPtr == MB->getBufferEnd()) {
// Already at end of the buffer, return just the zero byte at the end.
return StringRef(CurPtr, 0);
}
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
if(Str.empty())
return Str;
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
ends = begins + 1;
return llvm::StringRef(Str.c_str() + begins, ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
Interpreter::CompilationResult interpRes
= m_Interp.declare(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""));
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
if (CurPtr == MB->getBufferEnd()) {
// Already at end of the buffer, return just the zero byte at the end.
return StringRef(CurPtr, 0);
}
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
if(Str.empty())
return Str;
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
ends = begins + 1;
return llvm::StringRef(Str.c_str(), ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
//fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());
Interpreter::CompilationResult interpRes
= m_Interp.processLine(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""), true /*raw*/);
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<commit_msg>Use declare in the meta processor as well.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
if (CurPtr == MB->getBufferEnd()) {
// Already at end of the buffer, return just the zero byte at the end.
return StringRef(CurPtr, 0);
}
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
if(Str.empty())
return Str;
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
ends = begins + 1;
return llvm::StringRef(Str.c_str(), ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
Interpreter::CompilationResult interpRes
= m_Interp.declare(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""));
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<|endoftext|> |
<commit_before>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/AutoUpgrade.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/SymbolTable.h"
#include <iostream>
using namespace llvm;
// Utility function for getting the correct suffix given a type
static inline const char* get_suffix(const Type* Ty) {
switch (Ty->getTypeID()) {
case Type::UIntTyID: return ".i32";
case Type::UShortTyID: return ".i16";
case Type::UByteTyID: return ".i8";
case Type::ULongTyID: return ".i64";
case Type::FloatTyID: return ".f32";
case Type::DoubleTyID: return ".f64";
default: break;
}
return 0;
}
static inline const Type* get_type(Function* F) {
// If there's no function, we can't get the argument type.
if (!F)
return 0;
// Get the Function's name.
const std::string& Name = F->getName();
// Quickly eliminate it, if it's not a candidate.
if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
'v' || Name[3] != 'm' || Name[4] != '.')
return 0;
switch (Name[5]) {
case 'b':
if (Name == "llvm.bswap")
return F->getReturnType();
break;
case 'c':
if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
return F->getReturnType();
break;
case 'i':
if (Name == "llvm.isunordered") {
Function::const_arg_iterator ArgIt = F->arg_begin();
if (ArgIt != F->arg_end())
return ArgIt->getType();
}
break;
case 's':
if (Name == "llvm.sqrt")
return F->getReturnType();
break;
default:
break;
}
return 0;
}
bool llvm::IsUpgradeableIntrinsicName(const std::string& Name) {
// Quickly eliminate it, if it's not a candidate.
if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
'v' || Name[3] != 'm' || Name[4] != '.')
return false;
switch (Name[5]) {
case 'b':
if (Name == "llvm.bswap")
return true;
break;
case 'c':
if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
return true;
break;
case 'i':
if (Name == "llvm.isunordered")
return true;
break;
case 's':
if (Name == "llvm.sqrt")
return true;
break;
default:
break;
}
return false;
}
// UpgradeIntrinsicFunction - Convert overloaded intrinsic function names to
// their non-overloaded variants by appending the appropriate suffix based on
// the argument types.
Function* llvm::UpgradeIntrinsicFunction(Function* F) {
// See if its one of the name's we're interested in.
if (const Type* Ty = get_type(F)) {
const char* suffix = get_suffix(Ty);
if (Ty->isSigned())
suffix = get_suffix(Ty->getUnsignedVersion());
assert(suffix && "Intrinsic parameter type not recognized");
const std::string& Name = F->getName();
std::string new_name = Name + suffix;
std::cerr << "WARNING: change " << Name << " to " << new_name << "\n";
SymbolTable& SymTab = F->getParent()->getSymbolTable();
if (Value* V = SymTab.lookup(F->getType(),new_name))
if (Function* OtherF = dyn_cast<Function>(V))
return OtherF;
// There wasn't an existing function for the intrinsic, so now make sure the
// signedness of the arguments is correct.
if (Ty->isSigned()) {
const Type* newTy = Ty->getUnsignedVersion();
std::vector<const Type*> Params;
Params.push_back(newTy);
FunctionType* FT = FunctionType::get(newTy, Params,false);
return new Function(FT, GlobalValue::ExternalLinkage, new_name,
F->getParent());
}
// The argument was the correct type (unsigned or floating), so just
// rename the function to its correct name and return it.
F->setName(new_name);
return F;
}
return 0;
}
Instruction* llvm::UpgradeIntrinsicCall(CallInst *CI) {
Function *F = CI->getCalledFunction();
if (const Type* Ty = get_type(F)) {
Function* newF = UpgradeIntrinsicFunction(F);
std::vector<Value*> Oprnds;
for (User::op_iterator OI = CI->op_begin(), OE = CI->op_end();
OI != OE; ++OI)
Oprnds.push_back(CI);
CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
if (Ty->isSigned()) {
const Type* newTy = Ty->getUnsignedVersion();
newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
"autoupgrade_cast", newCI));
CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
newCI->moveBefore(final);
return final;
}
return newCI;
}
return 0;
}
bool llvm::UpgradeCallsToIntrinsic(Function* F) {
if (Function* newF = UpgradeIntrinsicFunction(F)) {
for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
UI != UE; ++UI) {
if (CallInst* CI = dyn_cast<CallInst>(*UI)) {
std::vector<Value*> Oprnds;
User::op_iterator OI = CI->op_begin();
++OI;
for (User::op_iterator OE = CI->op_end(); OI != OE; ++OI)
Oprnds.push_back(*OI);
CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
const Type* Ty = Oprnds[0]->getType();
if (Ty->isSigned()) {
const Type* newTy = Ty->getUnsignedVersion();
newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
"autoupgrade_cast", newCI));
CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
newCI->moveBefore(final);
CI->replaceAllUsesWith(final);
} else {
CI->replaceAllUsesWith(newCI);
}
CI->eraseFromParent();
}
}
if (newF != F)
F->eraseFromParent();
return true;
}
return false;
}
<commit_msg>Don't use invalidated use_iterator's. This fixes a crash compiling povray<commit_after>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/AutoUpgrade.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/SymbolTable.h"
#include <iostream>
using namespace llvm;
// Utility function for getting the correct suffix given a type
static inline const char* get_suffix(const Type* Ty) {
switch (Ty->getTypeID()) {
case Type::UIntTyID: return ".i32";
case Type::UShortTyID: return ".i16";
case Type::UByteTyID: return ".i8";
case Type::ULongTyID: return ".i64";
case Type::FloatTyID: return ".f32";
case Type::DoubleTyID: return ".f64";
default: break;
}
return 0;
}
static inline const Type* get_type(Function* F) {
// If there's no function, we can't get the argument type.
if (!F)
return 0;
// Get the Function's name.
const std::string& Name = F->getName();
// Quickly eliminate it, if it's not a candidate.
if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
'v' || Name[3] != 'm' || Name[4] != '.')
return 0;
switch (Name[5]) {
case 'b':
if (Name == "llvm.bswap")
return F->getReturnType();
break;
case 'c':
if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
return F->getReturnType();
break;
case 'i':
if (Name == "llvm.isunordered") {
Function::const_arg_iterator ArgIt = F->arg_begin();
if (ArgIt != F->arg_end())
return ArgIt->getType();
}
break;
case 's':
if (Name == "llvm.sqrt")
return F->getReturnType();
break;
default:
break;
}
return 0;
}
bool llvm::IsUpgradeableIntrinsicName(const std::string& Name) {
// Quickly eliminate it, if it's not a candidate.
if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] !=
'v' || Name[3] != 'm' || Name[4] != '.')
return false;
switch (Name[5]) {
case 'b':
if (Name == "llvm.bswap")
return true;
break;
case 'c':
if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz")
return true;
break;
case 'i':
if (Name == "llvm.isunordered")
return true;
break;
case 's':
if (Name == "llvm.sqrt")
return true;
break;
default:
break;
}
return false;
}
// UpgradeIntrinsicFunction - Convert overloaded intrinsic function names to
// their non-overloaded variants by appending the appropriate suffix based on
// the argument types.
Function* llvm::UpgradeIntrinsicFunction(Function* F) {
// See if its one of the name's we're interested in.
if (const Type* Ty = get_type(F)) {
const char* suffix = get_suffix(Ty);
if (Ty->isSigned())
suffix = get_suffix(Ty->getUnsignedVersion());
assert(suffix && "Intrinsic parameter type not recognized");
const std::string& Name = F->getName();
std::string new_name = Name + suffix;
std::cerr << "WARNING: change " << Name << " to " << new_name << "\n";
SymbolTable& SymTab = F->getParent()->getSymbolTable();
if (Value* V = SymTab.lookup(F->getType(),new_name))
if (Function* OtherF = dyn_cast<Function>(V))
return OtherF;
// There wasn't an existing function for the intrinsic, so now make sure the
// signedness of the arguments is correct.
if (Ty->isSigned()) {
const Type* newTy = Ty->getUnsignedVersion();
std::vector<const Type*> Params;
Params.push_back(newTy);
FunctionType* FT = FunctionType::get(newTy, Params,false);
return new Function(FT, GlobalValue::ExternalLinkage, new_name,
F->getParent());
}
// The argument was the correct type (unsigned or floating), so just
// rename the function to its correct name and return it.
F->setName(new_name);
return F;
}
return 0;
}
Instruction* llvm::UpgradeIntrinsicCall(CallInst *CI) {
Function *F = CI->getCalledFunction();
if (const Type* Ty = get_type(F)) {
Function* newF = UpgradeIntrinsicFunction(F);
std::vector<Value*> Oprnds;
for (User::op_iterator OI = CI->op_begin(), OE = CI->op_end();
OI != OE; ++OI)
Oprnds.push_back(CI);
CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
if (Ty->isSigned()) {
const Type* newTy = Ty->getUnsignedVersion();
newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
"autoupgrade_cast", newCI));
CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
newCI->moveBefore(final);
return final;
}
return newCI;
}
return 0;
}
bool llvm::UpgradeCallsToIntrinsic(Function* F) {
if (Function* newF = UpgradeIntrinsicFunction(F)) {
for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
UI != UE; UI) {
if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
std::vector<Value*> Oprnds;
User::op_iterator OI = CI->op_begin();
++OI;
for (User::op_iterator OE = CI->op_end(); OI != OE; ++OI)
Oprnds.push_back(*OI);
CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI);
const Type* Ty = Oprnds[0]->getType();
if (Ty->isSigned()) {
const Type* newTy = Ty->getUnsignedVersion();
newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy,
"autoupgrade_cast", newCI));
CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI);
newCI->moveBefore(final);
CI->replaceAllUsesWith(final);
} else {
CI->replaceAllUsesWith(newCI);
}
CI->eraseFromParent();
}
}
if (newF != F)
F->eraseFromParent();
return true;
}
return false;
}
<|endoftext|> |
<commit_before>// Copyright 2018 Google LLC
//
// 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
//
// https://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
#include <array>
#include <utility>
namespace polymorphic {
namespace detail {
template <typename T, typename Signature>
struct function_entry;
template <typename T, typename Return, typename Method, typename... Parameters>
struct function_entry<T, Return(Method, Parameters...)> {
static Return poly_call(Method method, void* t, Parameters... parameters) {
return poly_extend(method, *static_cast<T*>(t), parameters...);
}
};
template <typename T, typename... Signatures>
inline const auto vtable = std::array{
reinterpret_cast<void (*)()>(function_entry<T, Signatures>::poly_call)...};
template <size_t Index, typename Signature>
struct vtable_caller;
template <size_t Index, typename Return, typename Method,
typename... Parameters>
struct vtable_caller<Index, Return(Method, Parameters...)> {
template <size_t Size>
Return call_vtable(Method method, const std::array<void (*)(), Size>& table,
void* t, Parameters... parameters) {
return reinterpret_cast<Return (*)(Method, void*, Parameters...)>(
table[Index])(method, t, parameters...);
}
};
template <typename... implementations>
struct overload_call_vtable : implementations... {
using implementations::call_vtable...;
};
template <typename IntPack, typename... Signatures>
struct polymorphic_caller_implementation;
template <size_t... I, typename... Signatures>
struct polymorphic_caller_implementation<std::index_sequence<I...>,
Signatures...>
: overload_call_vtable<vtable_caller<I, Signatures>...> {};
} // namespace detail
template <typename... Signatures>
class polymorphic_view
: private detail::polymorphic_caller_implementation<
std::make_index_sequence<sizeof...(Signatures)>, Signatures...> {
const std::array<void (*)(), sizeof...(Signatures)>* vptr_ = nullptr;
void* t_ = nullptr;
public:
template <typename T>
explicit polymorphic_view(T& t)
: vptr_(&detail::vtable<std::decay_t<T>, Signatures...>), t_(&t) {}
explicit operator bool() const { return t != nullptr; }
template <typename Method, typename... Parameters>
decltype(auto) call(Parameters&&...) {
return this->call_vtable(Method{}, *vptr_, t_,
std::forward<Parameters>(parameters)...);
}
};
} // namespace polymorphic
#include <iostream>
#include <string>
struct draw {};
struct another {};
template <typename T>
void poly_extend(draw, T& t) {
std::cout << t << "\n";
}
template <typename T>
void poly_extend(another, T& t) {
t = t + t;
}
int main() {
int i = 5;
using poly = polymorphic::polymorphic_view<void(draw), void(another)>;
poly p1{i};
p1.call<draw>();
auto p2 = p1;
p2.call<draw>();
std::string s("hello world");
p2 = poly{s};
p2.call<another>();
p2.call<draw>();
}
<commit_msg>Add ability to subset polymorphic view<commit_after>// Copyright 2018 Google LLC
//
// 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
//
// https://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 <array>
#include <utility>
namespace polymorphic {
namespace detail {
template <typename T>
using ptr = T*;
template <typename T, typename Signature>
struct function_entry;
template <typename T, typename Return, typename Method, typename... Parameters>
struct function_entry<T, Return(Method, Parameters...)> {
static Return poly_call(Method method, void* t, Parameters... parameters) {
return poly_extend(method, *static_cast<T*>(t), parameters...);
}
};
template <typename T, typename... Signatures>
inline const auto vtable = std::array{
reinterpret_cast<ptr<void()>>(function_entry<T, Signatures>::poly_call)...};
template <size_t Index, typename Signature>
struct vtable_caller;
template <size_t Index, typename Return, typename Method,
typename... Parameters>
struct vtable_caller<Index, Return(Method, Parameters...)> {
static Return call_vtable(Method method, ptr<const ptr<void()>> table,
void* t, Parameters... parameters) {
return reinterpret_cast<ptr<Return(Method, void*, Parameters...)>>(
table[Index])(method, t, parameters...);
}
constexpr static std::size_t get_index(ptr<Return(Method, Parameters...)>) {
return Index;
}
};
template <typename... implementations>
struct overload_call_vtable : implementations... {
using implementations::call_vtable...;
using implementations::get_index...;
};
template <typename IntPack, typename... Signatures>
struct polymorphic_caller_implementation;
template <size_t... I, typename... Signatures>
struct polymorphic_caller_implementation<std::index_sequence<I...>,
Signatures...>
: overload_call_vtable<vtable_caller<I, Signatures>...> {};
} // namespace detail
template <typename... Signatures>
class polymorphic_view;
template <typename T>
struct is_polymorphic_view {
static constexpr bool value = false;
};
template <typename... Signatures>
struct is_polymorphic_view<polymorphic_view<Signatures...>> {
static constexpr bool value = true;
};
template <typename... Signatures>
class polymorphic_view
: private detail::polymorphic_caller_implementation<
std::make_index_sequence<sizeof...(Signatures)>, Signatures...> {
const std::array<detail::ptr<void()>, sizeof...(Signatures)>* vptr_ = nullptr;
void* t_ = nullptr;
template <typename... OtherSignatures>
static auto get_vtable(const polymorphic_view<OtherSignatures...>& other) {
static const std::array<detail::ptr<void()>, sizeof...(Signatures)> vtable{
other.get_entry<Signatures>()...};
return &vtable;
}
template <typename Signature>
detail::ptr<void()> get_entry() const {
return (*vptr_)[this->get_index(detail::ptr<Signature>{})];
}
template <typename... OtherSignatures>
friend class polymorphic_view;
public:
template <typename T, typename = std::enable_if_t<
!is_polymorphic_view<std::decay_t<T>>::value>>
explicit polymorphic_view(T& t)
: vptr_(&detail::vtable<std::decay_t<T>, Signatures...>), t_(&t) {}
template <typename... OtherSignatures>
explicit polymorphic_view(const polymorphic_view<OtherSignatures...>& other)
: vptr_(get_vtable(other)), t_(other.t_) {}
explicit operator bool() const { return t_ != nullptr; }
template <typename Method, typename... Parameters>
decltype(auto) call(Parameters&&... parameters) {
return this->call_vtable(Method{}, vptr_->data(), t_,
std::forward<Parameters>(parameters)...);
}
};
} // namespace polymorphic
#include <iostream>
#include <string>
struct draw {};
struct another {};
template <typename T>
void poly_extend(draw, T& t) {
std::cout << t << "\n";
}
template <typename T>
void poly_extend(another, T& t) {
t = t + t;
}
int main() {
int i = 5;
using poly = polymorphic::polymorphic_view<void(draw), void(another)>;
poly p1{i};
p1.call<draw>();
auto p2 = p1;
p2.call<draw>();
std::string s("hello world");
p2 = poly{s};
p2.call<another>();
p2.call<draw>();
polymorphic::polymorphic_view<void(draw)> p3{p2};
p3.call<draw>();
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007 Austin Robot Technology, Patrick Beeson
* Copyright (C) 2009, 2010 Austin Robot Technology, Jack O'Quin
*
* License: Modified BSD Software License Agreement
*
* $Id$
*/
/** \file
*
* ROS driver nodelet for the Velodyne HDL-64E 3D LIDAR
*/
#include <string>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <ros/ros.h>
#include <velodyne/input.h>
#include <velodyne_common/RawScan.h>
class DriverNodelet: public nodelet::Nodelet
{
public:
DriverNodelet()
: input_(0)
{}
~DriverNodelet()
{
if (input_) delete input_;
}
private:
virtual void onInit();
velodyne::Input *input_;
ros::Publisher output_;
};
void DriverNodelet::onInit()
{
// use private node handle to get parameters
ros::NodeHandle private_nh = getPrivateNodeHandle();
std::string dump_file;
private_nh.param("pcap", dump_file, std::string(""));
if (dump_file != "")
{
NODELET_INFO("reading data from file: %s", dump_file.c_str());
input_ = new velodyne::InputPCAP(dump_file);
}
else
{
NODELET_INFO("reading data from socket");
input_ = new velodyne::InputSocket();
}
if (input_->getParams() != 0)
{
NODELET_FATAL("Failed to read Velodyne packet input parameters.");
return;
}
ros::NodeHandle node = getNodeHandle();
using velodyne_common::RawScan;
// open Velodyne input device or file
if(input_->vopen() != 0)
{
NODELET_FATAL("Cannot open Velodyne input.");
return;
}
output_ = node.advertise<RawScan>("velodyne/rawscan", 1);
RawScan rawscan;
int npackets = RawScan::PACKETS_PER_REVOLUTION;
rawscan.data.resize(npackets * RawScan::PACKET_SIZE);
rawscan.header.frame_id = "/velodyne";
// Loop until shut down.
while(ros::ok())
{
double time;
// Since the velodyne delivers data at a very high rate, keep
// reading and publishing scans as fast as possible.
int packets_left = input_->getPackets(&rawscan.data[0], npackets, &time);
if (packets_left != 0) // incomplete scan received?
{
if (packets_left < 0) // end of file reached?
break;
if (packets_left < npackets) // partial scan read?
NODELET_WARN("Incomplete Velodyne scan: %d packets missing",
packets_left);
}
else
{
NODELET_DEBUG("Publishing a full Velodyne scan.");
rawscan.header.stamp = ros::Time(time);
output_.publish(rawscan);
}
}
input_->vclose();
}
// Register this plugin with pluginlib. Names must match nodelet_velodyne.xml.
//
// parameters are: package, class name, class type, base class type
PLUGINLIB_DECLARE_CLASS(velodyne_common, DriverNodelet,
DriverNodelet, nodelet::Nodelet);
<commit_msg>Allocate a shared pointer for zero-copy sharing of raw scans with other nodelets. <commit_after>/*
* Copyright (C) 2007 Austin Robot Technology, Patrick Beeson
* Copyright (C) 2009, 2010 Austin Robot Technology, Jack O'Quin
*
* License: Modified BSD Software License Agreement
*
* $Id$
*/
/** \file
*
* ROS driver nodelet for the Velodyne HDL-64E 3D LIDAR
*/
#include <string>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <ros/ros.h>
#include <velodyne/input.h>
#include <velodyne_common/RawScan.h>
class DriverNodelet: public nodelet::Nodelet
{
public:
DriverNodelet()
: input_(0)
{}
~DriverNodelet()
{
if (input_) delete input_;
}
private:
virtual void onInit();
velodyne::Input *input_;
ros::Publisher output_;
};
void DriverNodelet::onInit()
{
// use private node handle to get parameters
ros::NodeHandle private_nh = getPrivateNodeHandle();
std::string dump_file;
private_nh.param("pcap", dump_file, std::string(""));
if (dump_file != "")
{
NODELET_INFO("reading data from file: %s", dump_file.c_str());
input_ = new velodyne::InputPCAP(dump_file);
}
else
{
NODELET_INFO("reading data from socket");
input_ = new velodyne::InputSocket();
}
if (input_->getParams() != 0)
{
NODELET_FATAL("Failed to read Velodyne packet input parameters.");
return;
}
ros::NodeHandle node = getNodeHandle();
// open Velodyne input device or file
if(input_->vopen() != 0)
{
NODELET_FATAL("Cannot open Velodyne input.");
return;
}
output_ = node.advertise<velodyne_common::RawScan>("velodyne/rawscan", 1);
int npackets = velodyne_common::RawScan::PACKETS_PER_REVOLUTION;
// Loop until shut down.
while(ros::ok())
{
double time;
// allocate a new shared pointer for zero-copy sharing with other nodelets
velodyne_common::RawScanPtr scan(new velodyne_common::RawScan);
scan->data.resize(npackets * velodyne_common::RawScan::PACKET_SIZE);
// Since the velodyne delivers data at a very high rate, keep
// reading and publishing scans as fast as possible.
int packets_left = input_->getPackets(&scan->data[0], npackets, &time);
if (packets_left != 0) // incomplete scan received?
{
if (packets_left < 0) // end of file reached?
break;
if (packets_left < npackets) // partial scan read?
NODELET_WARN("Incomplete Velodyne scan: %d packets missing",
packets_left);
}
else
{
NODELET_DEBUG("Publishing a full Velodyne scan.");
scan->header.stamp = ros::Time(time);
scan->header.frame_id = "/velodyne";
output_.publish(scan);
}
}
input_->vclose();
}
// Register this plugin with pluginlib. Names must match nodelet_velodyne.xml.
//
// parameters are: package, class name, class type, base class type
PLUGINLIB_DECLARE_CLASS(velodyne_common, DriverNodelet,
DriverNodelet, nodelet::Nodelet);
<|endoftext|> |
<commit_before>#define MYSQLPP_NOT_HEADER
#include "platform.h"
#include "connection.h"
#include "query.h"
#include "result.h"
#if defined(HAVE_MYSQL_SHUTDOWN_LEVEL_ARG)
# define SHUTDOWN_ARG ,SHUTDOWN_DEFAULT
#else
# define SHUTDOWN_ARG
#endif
using namespace std;
namespace mysqlpp {
Connection::Connection() :
throw_exceptions(true),
locked(false)
{
mysql_init(&mysql);
}
Connection::Connection(bool te) :
throw_exceptions(te),
is_connected(false),
locked(true),
Success(false)
{
mysql_init(&mysql);
}
Connection::Connection(const char* db, const char* host,
const char* user, const char* passwd, bool te) :
throw_exceptions(te),
locked(false)
{
mysql_init(&mysql);
if (real_connect(db, host, user, passwd, 3306, 0, 60, NULL, 0)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
Success = is_connected = false;
if (throw_exceptions) {
throw BadQuery(error());
}
}
}
Connection::Connection(const char* db, const char* host,
const char* user, const char* passwd, uint port,
my_bool compress, unsigned int connect_timeout,
bool te, const char* socket_name,
unsigned client_flag) :
throw_exceptions(te),
locked(false)
{
mysql_init(&mysql);
if (real_connect(db, host, user, passwd, port, compress,
connect_timeout, socket_name, client_flag)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
Success = is_connected = false;
if (throw_exceptions) {
throw BadQuery(error());
}
}
}
bool Connection::real_connect(cchar* db, cchar* host, cchar* user,
cchar* passwd, uint port, my_bool compress,
unsigned int connect_timeout, const char* socket_name,
unsigned int client_flag)
{
mysql.options.compress = compress;
mysql.options.connect_timeout = connect_timeout;
locked = true; //mysql.options.my_cnf_file="my";
mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, "my");
if (mysql_real_connect(&mysql, host, user, passwd, db, port,
socket_name, client_flag)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
Success = is_connected = false;
if (throw_exceptions) {
throw BadQuery(error());
}
}
if (!Success) {
return Success;
}
if (db && db[0]) {
// db is not empty
Success = select_db(db);
}
return Success;
}
Connection::~Connection()
{
mysql_close(&mysql);
}
bool Connection::select_db(const char *db)
{
bool suc = !(mysql_select_db(&mysql, db));
if (throw_exceptions && !suc) {
throw BadQuery(error());
}
else {
return suc;
}
}
bool Connection::reload()
{
bool suc = !mysql_reload(&mysql);
if (throw_exceptions && !suc) {
throw BadQuery(error());
}
else {
return suc;
}
}
bool Connection::shutdown()
{
bool suc = !(mysql_shutdown(&mysql SHUTDOWN_ARG));
if (throw_exceptions && !suc) {
throw BadQuery(error());
}
else {
return suc;
}
}
bool Connection::connect(cchar* db, cchar* host, cchar* user,
cchar* passwd)
{
locked = true; // mysql.options.my_cnf_file="my";
mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, "my");
if (mysql_real_connect
(&mysql, host, user, passwd, db, 3306, NULL, 0)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
if (throw_exceptions)
throw BadQuery(error());
Success = is_connected = false;
}
// mysql.options.my_cnf_file=0;
if (!Success)
return Success;
if (db && db[0]) // if db is not empty
Success = select_db(db);
return Success;
}
string Connection::info()
{
const char *i = mysql_info(&mysql);
if (!i)
return string();
else
return string(i);
}
ResNSel Connection::execute(const string& str, bool throw_excptns)
{
Success = false;
if (lock()) {
if (throw_excptns) {
throw BadQuery("lock failed");
}
else {
return ResNSel();
}
}
Success = !mysql_query(&mysql, str.c_str());
unlock();
if (Success) {
return ResNSel(this);
}
else {
if (throw_excptns) {
throw BadQuery(error());
}
else {
return ResNSel();
}
}
}
bool Connection::exec(const string& str)
{
Success = !mysql_query(&mysql, str.c_str());
if (!Success && throw_exceptions)
throw BadQuery(error());
return Success;
}
Result Connection::store(const string& str, bool throw_excptns)
{
Success = false;
if (lock()) {
if (throw_excptns) {
throw BadQuery("lock failed");
}
else {
return Result();
}
}
Success = !mysql_query(&mysql, str.c_str());
if (Success) {
MYSQL_RES* res = mysql_store_result(&mysql);
if (res) {
unlock();
return Result(res);
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_excptns) {
throw BadQuery(error());
}
else {
return Result();
}
}
ResUse Connection::use(const string& str, bool throw_excptns)
{
Success = false;
if (lock()) {
if (throw_excptns) {
throw BadQuery("lock failed");
}
else {
return ResUse();
}
}
Success = !mysql_query(&mysql, str.c_str());
if (Success) {
MYSQL_RES* res = mysql_use_result(&mysql);
if (res) {
unlock();
return ResUse(res, this);
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_excptns) {
throw BadQuery(error());
}
else {
return ResUse();
}
}
Query Connection::query()
{
return Query(this, throw_exceptions);
}
} // end namespace mysqlpp
<commit_msg>Changed some parameter types to match the header exactly. (Was using "const char*" instead of "cchar", for instance.) This doesn't change the code's function, but it allows Doxygen to realize that it is seeing the same function that it found in the header.<commit_after>#define MYSQLPP_NOT_HEADER
#include "platform.h"
#include "connection.h"
#include "query.h"
#include "result.h"
#if defined(HAVE_MYSQL_SHUTDOWN_LEVEL_ARG)
# define SHUTDOWN_ARG ,SHUTDOWN_DEFAULT
#else
# define SHUTDOWN_ARG
#endif
using namespace std;
namespace mysqlpp {
Connection::Connection() :
throw_exceptions(true),
locked(false)
{
mysql_init(&mysql);
}
Connection::Connection(bool te) :
throw_exceptions(te),
is_connected(false),
locked(true),
Success(false)
{
mysql_init(&mysql);
}
Connection::Connection(const char* db, const char* host,
const char* user, const char* passwd, bool te) :
throw_exceptions(te),
locked(false)
{
mysql_init(&mysql);
if (real_connect(db, host, user, passwd, 3306, 0, 60, NULL, 0)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
Success = is_connected = false;
if (throw_exceptions) {
throw BadQuery(error());
}
}
}
Connection::Connection(const char* db, const char* host,
const char* user, const char* passwd, uint port,
my_bool compress, unsigned int connect_timeout,
bool te, cchar* socket_name, unsigned int client_flag) :
throw_exceptions(te),
locked(false)
{
mysql_init(&mysql);
if (real_connect(db, host, user, passwd, port, compress,
connect_timeout, socket_name, client_flag)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
Success = is_connected = false;
if (throw_exceptions) {
throw BadQuery(error());
}
}
}
bool Connection::real_connect(cchar* db, cchar* host, cchar* user,
cchar* passwd, uint port, my_bool compress,
unsigned int connect_timeout, cchar* socket_name,
unsigned int client_flag)
{
mysql.options.compress = compress;
mysql.options.connect_timeout = connect_timeout;
locked = true; //mysql.options.my_cnf_file="my";
mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, "my");
if (mysql_real_connect(&mysql, host, user, passwd, db, port,
socket_name, client_flag)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
Success = is_connected = false;
if (throw_exceptions) {
throw BadQuery(error());
}
}
if (!Success) {
return Success;
}
if (db && db[0]) {
// db is not empty
Success = select_db(db);
}
return Success;
}
Connection::~Connection()
{
mysql_close(&mysql);
}
bool Connection::select_db(const char *db)
{
bool suc = !(mysql_select_db(&mysql, db));
if (throw_exceptions && !suc) {
throw BadQuery(error());
}
else {
return suc;
}
}
bool Connection::reload()
{
bool suc = !mysql_reload(&mysql);
if (throw_exceptions && !suc) {
throw BadQuery(error());
}
else {
return suc;
}
}
bool Connection::shutdown()
{
bool suc = !(mysql_shutdown(&mysql SHUTDOWN_ARG));
if (throw_exceptions && !suc) {
throw BadQuery(error());
}
else {
return suc;
}
}
bool Connection::connect(cchar* db, cchar* host, cchar* user,
cchar* passwd)
{
locked = true; // mysql.options.my_cnf_file="my";
mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, "my");
if (mysql_real_connect
(&mysql, host, user, passwd, db, 3306, NULL, 0)) {
locked = false;
Success = is_connected = true;
}
else {
locked = false;
if (throw_exceptions)
throw BadQuery(error());
Success = is_connected = false;
}
// mysql.options.my_cnf_file=0;
if (!Success)
return Success;
if (db && db[0]) // if db is not empty
Success = select_db(db);
return Success;
}
string Connection::info()
{
const char *i = mysql_info(&mysql);
if (!i)
return string();
else
return string(i);
}
ResNSel Connection::execute(const string& str, bool throw_excptns)
{
Success = false;
if (lock()) {
if (throw_excptns) {
throw BadQuery("lock failed");
}
else {
return ResNSel();
}
}
Success = !mysql_query(&mysql, str.c_str());
unlock();
if (Success) {
return ResNSel(this);
}
else {
if (throw_excptns) {
throw BadQuery(error());
}
else {
return ResNSel();
}
}
}
bool Connection::exec(const string& str)
{
Success = !mysql_query(&mysql, str.c_str());
if (!Success && throw_exceptions)
throw BadQuery(error());
return Success;
}
Result Connection::store(const string& str, bool throw_excptns)
{
Success = false;
if (lock()) {
if (throw_excptns) {
throw BadQuery("lock failed");
}
else {
return Result();
}
}
Success = !mysql_query(&mysql, str.c_str());
if (Success) {
MYSQL_RES* res = mysql_store_result(&mysql);
if (res) {
unlock();
return Result(res);
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_excptns) {
throw BadQuery(error());
}
else {
return Result();
}
}
ResUse Connection::use(const string& str, bool throw_excptns)
{
Success = false;
if (lock()) {
if (throw_excptns) {
throw BadQuery("lock failed");
}
else {
return ResUse();
}
}
Success = !mysql_query(&mysql, str.c_str());
if (Success) {
MYSQL_RES* res = mysql_use_result(&mysql);
if (res) {
unlock();
return ResUse(res, this);
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_excptns) {
throw BadQuery(error());
}
else {
return ResUse();
}
}
Query Connection::query()
{
return Query(this, throw_exceptions);
}
} // end namespace mysqlpp
<|endoftext|> |
<commit_before>/** -*- c++ -*-
* progressdialog.cpp
*
* Copyright (c) 2004 Till Adam <adam@kde.org>,
* David Faure <faure@kde.org>
*
* 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; version 2 of the License
*
* 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>
#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include "kmmainwidget.h"
using KMail::ProgressItem;
using KMail::ProgressManager;
namespace KMail {
class TransactionItem;
TransactionItemView::TransactionItemView( QWidget * parent,
const char * name,
WFlags f )
: QScrollView( parent, name, f ) {
setFrameStyle( NoFrame );
mBigBox = new QVBox( viewport() );
mBigBox->setSpacing( 5 );
addChild( mBigBox );
setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}
TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
TransactionItem *ti = new TransactionItem( mBigBox, item, first );
ti->show();
return ti;
}
void TransactionItemView::resizeContents( int w, int h )
{
//kdDebug(5006) << k_funcinfo << w << "," << h << endl;
QScrollView::resizeContents( w, h );
// Tell the layout in the parent (progressdialog) that our size changed
updateGeometry();
// Resize the parent (progressdialog) - this works but resize horizontally too often
//parentWidget()->adjustSize();
QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
QSize sz = parentWidget()->sizeHint();
int currentWidth = parentWidget()->width();
// Don't resize to sz.width() every time when it only reduces a little bit
if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
currentWidth = sz.width();
parentWidget()->resize( currentWidth, sz.height() );
}
QSize TransactionItemView::sizeHint() const
{
return minimumSizeHint();
}
QSize TransactionItemView::minimumSizeHint() const
{
int f = 2 * frameWidth();
// Make room for a vertical scrollbar in all cases, to avoid a horizontal one
int vsbExt = verticalScrollBar()->sizeHint().width();
int minw = topLevelWidget()->width() / 3;
int maxh = topLevelWidget()->height() / 2;
QSize sz( mBigBox->minimumSizeHint() );
sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
sz.setHeight( QMIN( sz.height(), maxh ) + f );
return sz;
}
void TransactionItemView::slotLayoutFirstItem()
{
/*
The below relies on some details in Qt's behaviour regarding deleting
objects. This slot is called from the destroyed signal of an item just
going away. That item is at that point still in the list of chilren, but
since the vtable is already gone, it will have type QObject. The first
one with both the right name and the right class therefor is what will
be the first item very shortly. That's the one we want to remove the
hline for.
*/
QObject *o = mBigBox->child( "TransactionItem", "KMail::TransactionItem" );
TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
if ( ti ) {
ti->hideHLine();
}
}
// ----------------------------------------------------------------------------
TransactionItem::TransactionItem( QWidget* parent,
ProgressItem *item, bool first )
: QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )
{
setSpacing( 2 );
setMargin( 2 );
setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mFrame = new QFrame( this );
mFrame->setFrameShape( QFrame::HLine );
mFrame->setFrameShadow( QFrame::Raised );
mFrame->show();
setStretchFactor( mFrame, 3 );
QHBox *h = new QHBox( this );
h->setSpacing( 5 );
mItemLabel = new QLabel( item->label(), h );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mProgress = new QProgressBar( 100, h );
mProgress->setProgress( item->progress() );
if ( item->canBeCanceled() ) {
mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
connect ( mCancelButton, SIGNAL( clicked() ),
this, SLOT( slotItemCanceled() ));
}
h = new QHBox( this );
h->setSpacing( 5 );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mSSLLabel = new SSLLabel( h );
mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
mItemStatus = new QLabel( item->status(), h );
setCrypto( item->usesCrypto() );
if( first ) hideHLine();
}
TransactionItem::~TransactionItem()
{
}
void TransactionItem::hideHLine()
{
mFrame->hide();
}
void TransactionItem::setProgress( int progress )
{
mProgress->setProgress( progress );
}
void TransactionItem::setLabel( const QString& label )
{
mItemLabel->setText( label );
}
void TransactionItem::setStatus( const QString& status )
{
mItemStatus->setText( status );
}
void TransactionItem::setCrypto( bool on )
{
if (on)
mSSLLabel->setEncrypted( true );
else
mSSLLabel->setEncrypted( false );
mSSLLabel->setState( mSSLLabel->lastState() );
}
void TransactionItem::slotItemCanceled()
{
if ( mItem )
mItem->cancel();
}
void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{
}
// ---------------------------------------------------------------------------
ProgressDialog::ProgressDialog( QWidget* alignWidget, KMMainWidget* mainWidget, const char* name )
: OverlayWidget( alignWidget, mainWidget, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
setSpacing( 0 ); // QHBox
setMargin( 1 );
mScrollView = new TransactionItemView( this, "ProgressScrollView" );
QVBox* rightBox = new QVBox( this );
QToolButton* pbClose = new QToolButton( rightBox );
pbClose->setAutoRaise(true);
pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
pbClose->setFixedSize( 16, 16 );
pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
connect(pbClose, SIGNAL(clicked()), this, SLOT(close()));
QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
rightBox->setStretchFactor( spacer, 100 );
/*
* Get the singleton ProgressManager item which will inform us of
* appearing and vanishing items.
*/
ProgressManager *pm = ProgressManager::instance();
connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemLabel( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionLabel( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemUsesCrypto( ProgressItem*, bool ) ),
this, SLOT( slotTransactionUsesCrypto( ProgressItem*, bool ) ) );
}
void ProgressDialog::closeEvent( QCloseEvent* e )
{
e->accept();
hide();
}
/*
* Destructor
*/
ProgressDialog::~ProgressDialog()
{
// no need to delete child widgets.
}
void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
TransactionItem *parent = 0;
if ( item->parent() ) {
if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
parent = mTransactionsToListviewItems[ item->parent() ];
parent->addSubTransaction( item );
}
} else {
TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
if ( ti )
mTransactionsToListviewItems.replace( item, ti );
}
}
void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
mTransactionsToListviewItems.remove( item );
ti->setItemComplete();
QTimer::singleShot( 5000, ti, SLOT( deleteLater() ) );
// see the slot for comments as to why that works
connect ( ti, SIGNAL( destroyed() ),
mScrollView, SLOT( slotLayoutFirstItem() ) );
}
// This was the last item, hide.
if ( mTransactionsToListviewItems.empty() )
QTimer::singleShot( 5000, this, SLOT( slotHide() ) );
}
void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}
void ProgressDialog::slotTransactionProgress( ProgressItem *item,
unsigned int progress )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setProgress( progress );
}
}
void ProgressDialog::slotTransactionStatus( ProgressItem *item,
const QString& status )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setStatus( status );
}
}
void ProgressDialog::slotTransactionLabel( ProgressItem *item,
const QString& label )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setLabel( label );
}
}
void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
bool value )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setCrypto( value );
}
}
void ProgressDialog::slotHide()
{
// check if a new item showed up since we started the timer. If not, hide
if ( mTransactionsToListviewItems.isEmpty() ) {
// [save a member var by simply getting the parent mainwidget from qwidget]
KMMainWidget* mainWidget = ::qt_cast<KMMainWidget *>( parentWidget() );
// not only hide(), but also toggling the statusbar icon
mainWidget->setProgressDialogVisible( false );
}
}
}
#include "progressdialog.moc"
<commit_msg>David's wife noticed the cancel and close buttons are very close to each other and suggested putting the cancel button to the left of the progress bar. Let's try that. Comments?<commit_after>/** -*- c++ -*-
* progressdialog.cpp
*
* Copyright (c) 2004 Till Adam <adam@kde.org>,
* David Faure <faure@kde.org>
*
* 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; version 2 of the License
*
* 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>
#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include "kmmainwidget.h"
using KMail::ProgressItem;
using KMail::ProgressManager;
namespace KMail {
class TransactionItem;
TransactionItemView::TransactionItemView( QWidget * parent,
const char * name,
WFlags f )
: QScrollView( parent, name, f ) {
setFrameStyle( NoFrame );
mBigBox = new QVBox( viewport() );
mBigBox->setSpacing( 5 );
addChild( mBigBox );
setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}
TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
TransactionItem *ti = new TransactionItem( mBigBox, item, first );
ti->show();
return ti;
}
void TransactionItemView::resizeContents( int w, int h )
{
//kdDebug(5006) << k_funcinfo << w << "," << h << endl;
QScrollView::resizeContents( w, h );
// Tell the layout in the parent (progressdialog) that our size changed
updateGeometry();
// Resize the parent (progressdialog) - this works but resize horizontally too often
//parentWidget()->adjustSize();
QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
QSize sz = parentWidget()->sizeHint();
int currentWidth = parentWidget()->width();
// Don't resize to sz.width() every time when it only reduces a little bit
if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
currentWidth = sz.width();
parentWidget()->resize( currentWidth, sz.height() );
}
QSize TransactionItemView::sizeHint() const
{
return minimumSizeHint();
}
QSize TransactionItemView::minimumSizeHint() const
{
int f = 2 * frameWidth();
// Make room for a vertical scrollbar in all cases, to avoid a horizontal one
int vsbExt = verticalScrollBar()->sizeHint().width();
int minw = topLevelWidget()->width() / 3;
int maxh = topLevelWidget()->height() / 2;
QSize sz( mBigBox->minimumSizeHint() );
sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
sz.setHeight( QMIN( sz.height(), maxh ) + f );
return sz;
}
void TransactionItemView::slotLayoutFirstItem()
{
/*
The below relies on some details in Qt's behaviour regarding deleting
objects. This slot is called from the destroyed signal of an item just
going away. That item is at that point still in the list of chilren, but
since the vtable is already gone, it will have type QObject. The first
one with both the right name and the right class therefor is what will
be the first item very shortly. That's the one we want to remove the
hline for.
*/
QObject *o = mBigBox->child( "TransactionItem", "KMail::TransactionItem" );
TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
if ( ti ) {
ti->hideHLine();
}
}
// ----------------------------------------------------------------------------
TransactionItem::TransactionItem( QWidget* parent,
ProgressItem *item, bool first )
: QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )
{
setSpacing( 2 );
setMargin( 2 );
setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mFrame = new QFrame( this );
mFrame->setFrameShape( QFrame::HLine );
mFrame->setFrameShadow( QFrame::Raised );
mFrame->show();
setStretchFactor( mFrame, 3 );
QHBox *h = new QHBox( this );
h->setSpacing( 5 );
mItemLabel = new QLabel( item->label(), h );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
if ( item->canBeCanceled() ) {
mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
connect ( mCancelButton, SIGNAL( clicked() ),
this, SLOT( slotItemCanceled() ));
}
mProgress = new QProgressBar( 100, h );
mProgress->setProgress( item->progress() );
h = new QHBox( this );
h->setSpacing( 5 );
h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
mSSLLabel = new SSLLabel( h );
mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
mItemStatus = new QLabel( item->status(), h );
setCrypto( item->usesCrypto() );
if( first ) hideHLine();
}
TransactionItem::~TransactionItem()
{
}
void TransactionItem::hideHLine()
{
mFrame->hide();
}
void TransactionItem::setProgress( int progress )
{
mProgress->setProgress( progress );
}
void TransactionItem::setLabel( const QString& label )
{
mItemLabel->setText( label );
}
void TransactionItem::setStatus( const QString& status )
{
mItemStatus->setText( status );
}
void TransactionItem::setCrypto( bool on )
{
if (on)
mSSLLabel->setEncrypted( true );
else
mSSLLabel->setEncrypted( false );
mSSLLabel->setState( mSSLLabel->lastState() );
}
void TransactionItem::slotItemCanceled()
{
if ( mItem )
mItem->cancel();
}
void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{
}
// ---------------------------------------------------------------------------
ProgressDialog::ProgressDialog( QWidget* alignWidget, KMMainWidget* mainWidget, const char* name )
: OverlayWidget( alignWidget, mainWidget, name )
{
setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
setSpacing( 0 ); // QHBox
setMargin( 1 );
mScrollView = new TransactionItemView( this, "ProgressScrollView" );
QVBox* rightBox = new QVBox( this );
QToolButton* pbClose = new QToolButton( rightBox );
pbClose->setAutoRaise(true);
pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
pbClose->setFixedSize( 16, 16 );
pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
connect(pbClose, SIGNAL(clicked()), this, SLOT(close()));
QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
rightBox->setStretchFactor( spacer, 100 );
/*
* Get the singleton ProgressManager item which will inform us of
* appearing and vanishing items.
*/
ProgressManager *pm = ProgressManager::instance();
connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemLabel( ProgressItem*, const QString& ) ),
this, SLOT( slotTransactionLabel( ProgressItem*, const QString& ) ) );
connect ( pm, SIGNAL( progressItemUsesCrypto( ProgressItem*, bool ) ),
this, SLOT( slotTransactionUsesCrypto( ProgressItem*, bool ) ) );
}
void ProgressDialog::closeEvent( QCloseEvent* e )
{
e->accept();
hide();
}
/*
* Destructor
*/
ProgressDialog::~ProgressDialog()
{
// no need to delete child widgets.
}
void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
TransactionItem *parent = 0;
if ( item->parent() ) {
if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
parent = mTransactionsToListviewItems[ item->parent() ];
parent->addSubTransaction( item );
}
} else {
TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
if ( ti )
mTransactionsToListviewItems.replace( item, ti );
}
}
void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
mTransactionsToListviewItems.remove( item );
ti->setItemComplete();
QTimer::singleShot( 5000, ti, SLOT( deleteLater() ) );
// see the slot for comments as to why that works
connect ( ti, SIGNAL( destroyed() ),
mScrollView, SLOT( slotLayoutFirstItem() ) );
}
// This was the last item, hide.
if ( mTransactionsToListviewItems.empty() )
QTimer::singleShot( 5000, this, SLOT( slotHide() ) );
}
void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}
void ProgressDialog::slotTransactionProgress( ProgressItem *item,
unsigned int progress )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setProgress( progress );
}
}
void ProgressDialog::slotTransactionStatus( ProgressItem *item,
const QString& status )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setStatus( status );
}
}
void ProgressDialog::slotTransactionLabel( ProgressItem *item,
const QString& label )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setLabel( label );
}
}
void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
bool value )
{
if ( mTransactionsToListviewItems.contains( item ) ) {
TransactionItem *ti = mTransactionsToListviewItems[ item ];
ti->setCrypto( value );
}
}
void ProgressDialog::slotHide()
{
// check if a new item showed up since we started the timer. If not, hide
if ( mTransactionsToListviewItems.isEmpty() ) {
// [save a member var by simply getting the parent mainwidget from qwidget]
KMMainWidget* mainWidget = ::qt_cast<KMMainWidget *>( parentWidget() );
// not only hide(), but also toggling the statusbar icon
mainWidget->setProgressDialogVisible( false );
}
}
}
#include "progressdialog.moc"
<|endoftext|> |
<commit_before>/***************************************************************************
filter_ldif.cxx - description
-------------------
begin : Fri Dec 1, 2000
copyright : (C) 2000 by Oliver Strutynski
email : olistrut@gmx.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <iostream.h>
#include <stdlib.h>
#include <qtextstream.h>
#include <kfiledialog.h>
#include <klocale.h>
#include "filter_ldif.hxx"
filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Adress Book 1(.LDIF)"),"Oliver Strutynski")
{}
filter_ldif::~filter_ldif()
{}
void filter_ldif::import(filterInfo *info) {
QString _file;
char file[1024];
char dir[1024];
QWidget *parent=info->parent();
cout << parent << "\n";
sprintf(dir,getenv("HOME"));
_file=KFileDialog::getOpenFileName(dir,"*.ldif *.LDIF *.Ldif",parent);
if (_file.length()==0) {
info->alert(name(),i18n("No Adressbook choosen"));
return;
}
strcpy(file,_file.latin1());
QString from=i18n("from: "),to=i18n("to: ");
from+="\t"; from+=file;
to+="\t"; to+=i18n("the K Address Book");
info->from(from);
info->to(to);
info->current(i18n("Currently converting .LDIF address file to Kab"));
convert(file, info);
info->current(100.0);
info->overall(100.0);
info->current(i18n("Done converting .LDIF address file to Kab"));
}
bool filter_ldif::convert(const char *filename, filterInfo *info) {
QString caption;
caption=i18n("Import Netscape LDIF Personal Adressbook (.LDIF)");
if (!kabStart(info)) {
info->alert(caption,"Error starting KAB");
return false;
}
QFile f(filename);
QString firstName="", email="", lastName="";
QString title=""; QString givenName=""; QString comment="";
QString organization=""; QString homepage=""; QString locality="";
QString street=""; QString zipCode=""; QString phone="";
QString fax=""; QString country=""; QString mobile=""; QString state="";
QString department=""; QString empty="";
// Initializing code table for base64 decoding
initCodeTable();
if ( f.open(IO_ReadOnly) ) {
QTextStream t( &f );
QString s;
QString fieldname;
// We need this for calculating progress
uint fileSize = f.size();
uint bytesProcessed = 0;
// Set to true if data currently read is part of
// a list of names. Lists will be ignored.
bool isGroup=false;
while ( !t.eof() ) {
s = t.readLine();
bytesProcessed += s.length();
if (s.isEmpty()) {
// Newline: Write data
if (!isGroup) {
kabAddress( info,i18n("Netscape Addressbook"), givenName, email, title,firstName,empty,lastName,
street, locality, state, zipCode, country, organization, department,
empty, empty, phone, fax, mobile, empty, homepage, empty,
comment,empty);
firstName=""; email=""; lastName=""; title="";
givenName=""; comment=""; organization=""; homepage="";
locality=""; street=""; zipCode=""; phone="";
fax=""; country=""; mobile=""; state=""; department="";
} else {
info->log("Warning: List data is being ignored.");
}
isGroup=false;
} else {
int position = s.find("::");
if (position != -1) {
// String is BASE64 encoded
fieldname = s.left(position);
s = decodeBase64(s.mid(position+3, s.length()-position-2));
} else {
position = s.find(":");
fieldname = s.left(position);
// Convert Utf8 string to unicode so special characters are preserved
// We need this since we are reading normal strings from the file
// which are not converted automatically
s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
}
if (fieldname == "givenname") {
firstName=s;
} else if (fieldname == "sn") {
lastName=s;
} else if (fieldname == "mail") {
email=s;
} else if (fieldname == "title") {
title=s;
} else if (fieldname == "cn") {
givenName=s;
} else if (fieldname == "o") {
organization=s;
} else if (fieldname == "description") {
comment=s;
} else if (fieldname == "homeurl") {
homepage=s;
} else if (fieldname == "homephone") {
if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
phone=s;
} else if (fieldname == "telephonenumber") {
if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
phone=s;
} else if (fieldname == "postalcode") {
zipCode=s;
} else if (fieldname == "facsimiletelephonenumber") {
fax=s;
} else if (fieldname == "streetaddress") {
street=s;
} else if (fieldname == "locality") {
locality=s;
} else if (fieldname == "countryname") {
country=s;
} else if (fieldname == "cellphone") {
mobile=s;
} else if (fieldname == "st") {
state=s;
} else if (fieldname == "ou") {
department=s;
} else if (fieldname == "objectclass") {
if (s == "groupOfNames") { isGroup = true; }
}
// update progress information
info->current((float)bytesProcessed/fileSize*100);
info->overall((float)bytesProcessed/fileSize*100);
}
}
f.close();
} else {
char msg[1024];
sprintf(msg,i18n("Can't open '%s' for reading").latin1(),filename);
info->alert(caption,msg);
return false;
}
kabStop(info);
return true;
}
/*
* Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
* Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
* published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{
// cout << " Trying to decode base64 string: " << input << "\n";
QString result;
int tempLen = input.length();
for(unsigned int i=0; i<input.length(); i++) {
if(codes[ input[i].latin1() ] < 0) {
// cout << "Invalid character in base64 string: " << input[i].latin1() << "\n";
--tempLen; // ignore non-valid chars and padding
}
}
// calculate required length:
// -- 3 bytes for every 4 valid base64 chars
// -- plus 2 bytes if there are 3 extra base64 chars,
// or plus 1 byte if there are 2 extra.
int len = (tempLen / 4) * 3;
if ((tempLen % 4) == 3) len += 2;
if ((tempLen % 4) == 2) len += 1;
int shift = 0; // # of excess bits stored in accum
int accum = 0; // excess bits
// we now loop over through the entire string
for (unsigned int i=0; i<input.length(); i++) {
int value = codes[ input[i].latin1() ];
if ( value >= 0 ) { // skip over non-code
accum <<= 6; // bits shift up by 6 each time thru
shift += 6; // loop, with new bits being put in
accum |= value; // at the bottom.
if ( shift >= 8 ) { // whenever there are 8 or more shifted in,
shift -= 8; // write them out (from the top, leaving any
// excess at the bottom for next iteration.
result += (char) ((accum >> shift) & 0xff);
}
}
}
// Remove any linefeeds, tabs and multiple space from decoded string and
// convert to unicode.
result = QString::fromUtf8(result.latin1());
result = result.simplifyWhiteSpace();
return result;
}
/* Initialize lookup */
void filter_ldif::initCodeTable() {
// chars for 0..63
for (int i=0; i<256; i++) codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}
<commit_msg>oh my goodness...<commit_after>/***************************************************************************
filter_ldif.cxx - description
-------------------
begin : Fri Dec 1, 2000
copyright : (C) 2000 by Oliver Strutynski
email : olistrut@gmx.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <iostream.h>
#include <stdlib.h>
#include <qtextstream.h>
#include <kfiledialog.h>
#include <klocale.h>
#include "filter_ldif.hxx"
filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Adress Book 1(.LDIF)"),"Oliver Strutynski")
{}
filter_ldif::~filter_ldif()
{}
void filter_ldif::import(filterInfo *info) {
QString _file;
char file[1024];
char dir[1024];
QWidget *parent=info->parent();
cout << parent << "\n";
sprintf(dir,getenv("HOME"));
_file=KFileDialog::getOpenFileName(dir,"*.ldif *.LDIF *.Ldif",parent);
if (_file.length()==0) {
info->alert(name(),i18n("No Adressbook choosen"));
return;
}
strcpy(file,_file.latin1()); //lukas: FIXME no strcpy nor .latin1() for filenames!!!
QString from=i18n("from: "),to=i18n("to: ");
from+="\t"; from+=file;
to+="\t"; to+=i18n("the K Address Book");
info->from(from);
info->to(to);
info->current(i18n("Currently converting .LDIF address file to Kab"));
convert(file, info);
info->current(100.0);
info->overall(100.0);
info->current(i18n("Done converting .LDIF address file to Kab"));
}
bool filter_ldif::convert(const char *filename, filterInfo *info) {
QString caption;
caption=i18n("Import Netscape LDIF Personal Adressbook (.LDIF)");
if (!kabStart(info)) {
info->alert(caption,"Error starting KAB");
return false;
}
QFile f(filename);
QString firstName="", email="", lastName="";
QString title=""; QString givenName=""; QString comment="";
QString organization=""; QString homepage=""; QString locality="";
QString street=""; QString zipCode=""; QString phone="";
QString fax=""; QString country=""; QString mobile=""; QString state="";
QString department=""; QString empty="";
// Initializing code table for base64 decoding
initCodeTable();
if ( f.open(IO_ReadOnly) ) {
QTextStream t( &f );
QString s;
QString fieldname;
// We need this for calculating progress
uint fileSize = f.size();
uint bytesProcessed = 0;
// Set to true if data currently read is part of
// a list of names. Lists will be ignored.
bool isGroup=false;
while ( !t.eof() ) {
s = t.readLine();
bytesProcessed += s.length();
if (s.isEmpty()) {
// Newline: Write data
if (!isGroup) {
kabAddress( info,i18n("Netscape Addressbook"), givenName, email, title,firstName,empty,lastName,
street, locality, state, zipCode, country, organization, department,
empty, empty, phone, fax, mobile, empty, homepage, empty,
comment,empty);
firstName=""; email=""; lastName=""; title="";
givenName=""; comment=""; organization=""; homepage="";
locality=""; street=""; zipCode=""; phone="";
fax=""; country=""; mobile=""; state=""; department="";
} else {
info->log("Warning: List data is being ignored.");
}
isGroup=false;
} else {
int position = s.find("::");
if (position != -1) {
// String is BASE64 encoded
fieldname = s.left(position);
s = decodeBase64(s.mid(position+3, s.length()-position-2));
} else {
position = s.find(":");
fieldname = s.left(position);
// Convert Utf8 string to unicode so special characters are preserved
// We need this since we are reading normal strings from the file
// which are not converted automatically
s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
}
if (fieldname == "givenname") {
firstName=s;
} else if (fieldname == "sn") {
lastName=s;
} else if (fieldname == "mail") {
email=s;
} else if (fieldname == "title") {
title=s;
} else if (fieldname == "cn") {
givenName=s;
} else if (fieldname == "o") {
organization=s;
} else if (fieldname == "description") {
comment=s;
} else if (fieldname == "homeurl") {
homepage=s;
} else if (fieldname == "homephone") {
if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
phone=s;
} else if (fieldname == "telephonenumber") {
if (phone.length() > 0) { info->log("Discarding Phone Number "+s); }
phone=s;
} else if (fieldname == "postalcode") {
zipCode=s;
} else if (fieldname == "facsimiletelephonenumber") {
fax=s;
} else if (fieldname == "streetaddress") {
street=s;
} else if (fieldname == "locality") {
locality=s;
} else if (fieldname == "countryname") {
country=s;
} else if (fieldname == "cellphone") {
mobile=s;
} else if (fieldname == "st") {
state=s;
} else if (fieldname == "ou") {
department=s;
} else if (fieldname == "objectclass") {
if (s == "groupOfNames") { isGroup = true; }
}
// update progress information
info->current((float)bytesProcessed/fileSize*100);
info->overall((float)bytesProcessed/fileSize*100);
}
}
f.close();
} else {
char msg[1024];
sprintf(msg,i18n("Can't open '%s' for reading").latin1(),filename);
//lukas: noooo! no sprintf nor .latin1() please!!!
info->alert(caption,msg);
return false;
}
kabStop(info);
return true;
}
/*
* Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
* Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
* published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{
// cout << " Trying to decode base64 string: " << input << "\n";
QString result;
int tempLen = input.length();
for(unsigned int i=0; i<input.length(); i++) {
if(codes[ input[i].latin1() ] < 0) {
// cout << "Invalid character in base64 string: " << input[i].latin1() << "\n";
--tempLen; // ignore non-valid chars and padding
}
}
// calculate required length:
// -- 3 bytes for every 4 valid base64 chars
// -- plus 2 bytes if there are 3 extra base64 chars,
// or plus 1 byte if there are 2 extra.
int len = (tempLen / 4) * 3;
if ((tempLen % 4) == 3) len += 2;
if ((tempLen % 4) == 2) len += 1;
int shift = 0; // # of excess bits stored in accum
int accum = 0; // excess bits
// we now loop over through the entire string
for (unsigned int i=0; i<input.length(); i++) {
int value = codes[ input[i].latin1() ];
if ( value >= 0 ) { // skip over non-code
accum <<= 6; // bits shift up by 6 each time thru
shift += 6; // loop, with new bits being put in
accum |= value; // at the bottom.
if ( shift >= 8 ) { // whenever there are 8 or more shifted in,
shift -= 8; // write them out (from the top, leaving any
// excess at the bottom for next iteration.
result += (char) ((accum >> shift) & 0xff);
}
}
}
// Remove any linefeeds, tabs and multiple space from decoded string and
// convert to unicode.
result = QString::fromUtf8(result.latin1()); //lukas: nah!!! FIXME
result = result.simplifyWhiteSpace();
return result;
}
/* Initialize lookup */
void filter_ldif::initCodeTable() {
// chars for 0..63
for (int i=0; i<256; i++) codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}
<|endoftext|> |
<commit_before>// Halide tutorial lesson 12.
// This lesson demonstrates how to use Halide to run code on a GPU.
// On linux, you can compile and run it like so:
// g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_12
// LD_LIBRARY_PATH=../bin ./lesson_12
// On os x:
// g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide -lpng -o lesson_12
// DYLD_LIBRARY_PATH=../bin ./lesson_12
#include <Halide.h>
#include <stdio.h>
using namespace Halide;
// Include some support code for loading pngs.
#include "image_io.h"
// Include a clock to do performance testing.
#include "clock.h"
// Define some Vars to use.
Var x, y, c, i;
// We're going to want to schedule a pipeline in several ways, so we
// define the pipeline in a class so that we can recreate it several
// times with different schedules.
class Pipeline {
public:
Func lut, padded, padded16, sharpen, curved;
Image<uint8_t> input;
Pipeline(Image<uint8_t> in) : input(in) {
// For this lesson, we'll use a two-stage pipeline that sharpens
// and then applies a look-up-table (LUT).
// First we'll define the LUT. It will be a gamma curve.
lut(i) = cast<uint8_t>(clamp(pow(i / 255.0f, 1.2f) * 255.0f, 0, 255));
// Augment the input with a boundary condition.
padded(x, y, c) = input(clamp(x, 0, input.width()-1),
clamp(y, 0, input.height()-1), c);
// Cast it to 16-bit to do the math.
padded16(x, y, c) = cast<uint16_t>(padded(x, y, c));
// Next we sharpen it with a five-tap filter.
sharpen(x, y, c) = (padded16(x, y, c) * 2-
(padded16(x - 1, y, c) +
padded16(x, y - 1, c) +
padded16(x + 1, y, c) +
padded16(x, y + 1, c)) / 4);
// Then apply the LUT.
curved(x, y, c) = lut(sharpen(x, y, c));
}
// Now we define methods that give our pipeline several different
// schedules.
void schedule_for_cpu() {
// Compute the look-up-table ahead of time.
lut.compute_root();
// Compute color channels innermost. Promise that there will
// be three of them and unroll across them.
curved.reorder(c, x, y)
.bound(c, 0, 3)
.unroll(c);
// Look-up-tables don't vectorize well, so just parallelize
// curved in slices of 16 scanlines.
Var yo, yi;
curved.split(y, yo, yi, 16)
.parallel(yo);
// Compute sharpen as needed per scanline of curved, reusing
// previous values computed within the same strip of 16
// scanlines.
sharpen.store_at(curved, yo)
.compute_at(curved, yi);
// Vectorize the sharpen. It's 16-bit so we'll vectorize it 8-wide.
sharpen.vectorize(x, 8);
// Compute the padded input at the same granularity as the
// sharpen. We'll leave the cast to 16-bit inlined into
// sharpen.
padded.store_at(curved, yo)
.compute_at(curved, yi);
// Also vectorize the padding. It's 8-bit, so we'll vectorize
// 16-wide.
padded.vectorize(x, 16);
// JIT-compile the pipeline for the CPU.
curved.compile_jit();
}
// Now a schedule that uses CUDA or OpenCL.
void schedule_for_gpu() {
// We make the decision about whether to use the GPU for each
// Func independently. If you have one Func computed on the
// CPU, and the next computed on the GPU, Halide will do the
// copy-to-gpu under the hood. For this pipeline, there's no
// reason to use the CPU for any of the stages. Halide will
// copy the input image to the GPU the first time we run the
// pipeline, and leave it there to reuse on subsequent runs.
// As before, we'll compute the LUT once at the start of the
// pipeline.
lut.compute_root();
// Let's compute the look-up-table using the GPU in 16-wide
// one-dimensional thread blocks. First we split the index
// into blocks of size 16:
Var block, thread;
lut.split(i, block, thread, 16);
// Then we tell cuda that our Vars 'block' and 'thread'
// correspond to CUDA's notions of blocks and threads, or
// OpenCL's notions of thread groups and threads.
lut.gpu_blocks(block)
.gpu_threads(thread);
// This is a very common scheduling pattern on the GPU, so
// there's a shorthand for it:
// lut.gpu_tile(i, 16);
// Func::gpu_tile method is similar to Func::tile, except that
// it also specifies that the tile coordinates correspond to
// GPU blocks, and the coordinates within each tile correspond
// to GPU threads.
// Compute color channels innermost. Promise that there will
// be three of them and unroll across them.
curved.reorder(c, x, y)
.bound(c, 0, 3)
.unroll(c);
// Compute curved in 2D 8x8 tiles using the GPU.
curved.gpu_tile(x, y, 8, 8);
// This is equivalent to:
// curved.tile(x, y, xo, yo, xi, yi, 8, 8)
// .gpu_blocks(xo, yo)
// .gpu_threads(xi, yi);
// We'll leave sharpen as inlined into curved.
// Compute the padded input as needed per GPU block, storing the
// intermediate result in shared memory. Var::gpu_blocks, and
// Var::gpu_threads exist to help you schedule producers within
// GPU threads and blocks.
padded.compute_at(curved, Var::gpu_blocks());
// Use the GPU threads for the x and y coordinates of the
// padded input.
padded.gpu_threads(x, y);
// JIT-compile the pipeline for the GPU. CUDA or OpenCL are
// not enabled by default. We have to construct a Target
// object, enable one of them, and then pass that target
// object to compile_jit. Otherwise your CPU will very slowly
// pretend it's a GPU, and use one thread per output pixel.
// Start with a target suitable for the machine you're running
// this on.
Target target = get_host_target();
// Then enable OpenCL or CUDA.
// We'll enable OpenCL here, because it tends to give better
// performance than CUDA, even with NVidia's drivers, because
// NVidia's open source LLVM backend doesn't seem to do all
// the same optimizations their proprietary compiler does.
target.set_feature(Target::OpenCL);
// Uncomment the next line and comment out the line above to
// try CUDA instead.
// target.set_feature(Target::CUDA);
// If you want to see all of the OpenCL or CUDA API calls done
// by the pipeline, you can also enable the Debug
// flag. This is helpful for figuring out which stages are
// slow, or when CPU -> GPU copies happen. It hurts
// performance though, so we'll leave it commented out.
// target.set_feature(Target::Debug);
curved.compile_jit(target);
}
void test_performance() {
// Test the performance of the scheduled Pipeline.
// If we realize curved into a Halide::Image, that will
// unfairly penalize GPU performance by including a GPU->CPU
// copy in every run. Halide::Image objects always exist on
// the CPU.
// Halide::Buffer, however, represents a buffer that may
// exist on either CPU or GPU or both.
Buffer output(UInt(8), input.width(), input.height(), input.channels());
// Run the filter once to initialize any GPU runtime state.
curved.realize(output);
// Now take the best of 3 runs for timing.
double best_time;
for (int i = 0; i < 3; i++) {
double t1 = current_time();
// Run the filter 100 times.
for (int j = 0; j < 100; j++) {
curved.realize(output);
}
// Force any GPU code to finish by copying the buffer back to the CPU.
output.copy_to_host();
double t2 = current_time();
double elapsed = (t2 - t1)/100;
if (i == 0 || elapsed < best_time) {
best_time = elapsed;
}
}
printf("%1.4f milliseconds\n", best_time);
}
void test_correctness(Image<uint8_t> reference_output) {
Image<uint8_t> output = curved.realize(input.width(), input.height(), input.channels());
// Check against the reference output.
for (int c = 0; c < input.channels(); c++) {
for (int y = 0; y < input.height(); y++) {
for (int x = 0; x < input.width(); x++) {
if (output(x, y, c) != reference_output(x, y, c)) {
printf("Mismatch between output (%d) and "
"reference output (%d) at %d, %d, %d\n",
output(x, y, c),
reference_output(x, y, c),
x, y, c);
}
}
}
}
}
};
int main(int argc, char **argv) {
// Load an input image.
Image<uint8_t> input = load<uint8_t>("images/rgb.png");
// Allocated an image that will store the correct output
Image<uint8_t> reference_output(input.width(), input.height(), input.channels());
printf("Testing performance on CPU:\n");
Pipeline p1(input);
p1.schedule_for_cpu();
p1.test_performance();
p1.curved.realize(reference_output);
printf("Testing performance on GPU:\n");
Pipeline p2(input);
p2.schedule_for_gpu();
p2.test_performance();
p2.test_correctness(reference_output);
return 0;
}
<commit_msg>Only run tutorial lesson 12 if it can find libOpenCL<commit_after>// Halide tutorial lesson 12.
// This lesson demonstrates how to use Halide to run code on a GPU.
// On linux, you can compile and run it like so:
// g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_12
// LD_LIBRARY_PATH=../bin ./lesson_12
// On os x:
// g++ lesson_12*.cpp -g -I ../include -L ../bin -lHalide -lpng -o lesson_12
// DYLD_LIBRARY_PATH=../bin ./lesson_12
#include <Halide.h>
#include <stdio.h>
using namespace Halide;
// Include some support code for loading pngs.
#include "image_io.h"
// Include a clock to do performance testing.
#include "clock.h"
// Define some Vars to use.
Var x, y, c, i;
// We're going to want to schedule a pipeline in several ways, so we
// define the pipeline in a class so that we can recreate it several
// times with different schedules.
class Pipeline {
public:
Func lut, padded, padded16, sharpen, curved;
Image<uint8_t> input;
Pipeline(Image<uint8_t> in) : input(in) {
// For this lesson, we'll use a two-stage pipeline that sharpens
// and then applies a look-up-table (LUT).
// First we'll define the LUT. It will be a gamma curve.
lut(i) = cast<uint8_t>(clamp(pow(i / 255.0f, 1.2f) * 255.0f, 0, 255));
// Augment the input with a boundary condition.
padded(x, y, c) = input(clamp(x, 0, input.width()-1),
clamp(y, 0, input.height()-1), c);
// Cast it to 16-bit to do the math.
padded16(x, y, c) = cast<uint16_t>(padded(x, y, c));
// Next we sharpen it with a five-tap filter.
sharpen(x, y, c) = (padded16(x, y, c) * 2-
(padded16(x - 1, y, c) +
padded16(x, y - 1, c) +
padded16(x + 1, y, c) +
padded16(x, y + 1, c)) / 4);
// Then apply the LUT.
curved(x, y, c) = lut(sharpen(x, y, c));
}
// Now we define methods that give our pipeline several different
// schedules.
void schedule_for_cpu() {
// Compute the look-up-table ahead of time.
lut.compute_root();
// Compute color channels innermost. Promise that there will
// be three of them and unroll across them.
curved.reorder(c, x, y)
.bound(c, 0, 3)
.unroll(c);
// Look-up-tables don't vectorize well, so just parallelize
// curved in slices of 16 scanlines.
Var yo, yi;
curved.split(y, yo, yi, 16)
.parallel(yo);
// Compute sharpen as needed per scanline of curved, reusing
// previous values computed within the same strip of 16
// scanlines.
sharpen.store_at(curved, yo)
.compute_at(curved, yi);
// Vectorize the sharpen. It's 16-bit so we'll vectorize it 8-wide.
sharpen.vectorize(x, 8);
// Compute the padded input at the same granularity as the
// sharpen. We'll leave the cast to 16-bit inlined into
// sharpen.
padded.store_at(curved, yo)
.compute_at(curved, yi);
// Also vectorize the padding. It's 8-bit, so we'll vectorize
// 16-wide.
padded.vectorize(x, 16);
// JIT-compile the pipeline for the CPU.
curved.compile_jit();
}
// Now a schedule that uses CUDA or OpenCL.
void schedule_for_gpu() {
// We make the decision about whether to use the GPU for each
// Func independently. If you have one Func computed on the
// CPU, and the next computed on the GPU, Halide will do the
// copy-to-gpu under the hood. For this pipeline, there's no
// reason to use the CPU for any of the stages. Halide will
// copy the input image to the GPU the first time we run the
// pipeline, and leave it there to reuse on subsequent runs.
// As before, we'll compute the LUT once at the start of the
// pipeline.
lut.compute_root();
// Let's compute the look-up-table using the GPU in 16-wide
// one-dimensional thread blocks. First we split the index
// into blocks of size 16:
Var block, thread;
lut.split(i, block, thread, 16);
// Then we tell cuda that our Vars 'block' and 'thread'
// correspond to CUDA's notions of blocks and threads, or
// OpenCL's notions of thread groups and threads.
lut.gpu_blocks(block)
.gpu_threads(thread);
// This is a very common scheduling pattern on the GPU, so
// there's a shorthand for it:
// lut.gpu_tile(i, 16);
// Func::gpu_tile method is similar to Func::tile, except that
// it also specifies that the tile coordinates correspond to
// GPU blocks, and the coordinates within each tile correspond
// to GPU threads.
// Compute color channels innermost. Promise that there will
// be three of them and unroll across them.
curved.reorder(c, x, y)
.bound(c, 0, 3)
.unroll(c);
// Compute curved in 2D 8x8 tiles using the GPU.
curved.gpu_tile(x, y, 8, 8);
// This is equivalent to:
// curved.tile(x, y, xo, yo, xi, yi, 8, 8)
// .gpu_blocks(xo, yo)
// .gpu_threads(xi, yi);
// We'll leave sharpen as inlined into curved.
// Compute the padded input as needed per GPU block, storing the
// intermediate result in shared memory. Var::gpu_blocks, and
// Var::gpu_threads exist to help you schedule producers within
// GPU threads and blocks.
padded.compute_at(curved, Var::gpu_blocks());
// Use the GPU threads for the x and y coordinates of the
// padded input.
padded.gpu_threads(x, y);
// JIT-compile the pipeline for the GPU. CUDA or OpenCL are
// not enabled by default. We have to construct a Target
// object, enable one of them, and then pass that target
// object to compile_jit. Otherwise your CPU will very slowly
// pretend it's a GPU, and use one thread per output pixel.
// Start with a target suitable for the machine you're running
// this on.
Target target = get_host_target();
// Then enable OpenCL or CUDA.
// We'll enable OpenCL here, because it tends to give better
// performance than CUDA, even with NVidia's drivers, because
// NVidia's open source LLVM backend doesn't seem to do all
// the same optimizations their proprietary compiler does.
target.set_feature(Target::OpenCL);
// Uncomment the next line and comment out the line above to
// try CUDA instead.
// target.set_feature(Target::CUDA);
// If you want to see all of the OpenCL or CUDA API calls done
// by the pipeline, you can also enable the Debug
// flag. This is helpful for figuring out which stages are
// slow, or when CPU -> GPU copies happen. It hurts
// performance though, so we'll leave it commented out.
// target.set_feature(Target::Debug);
curved.compile_jit(target);
}
void test_performance() {
// Test the performance of the scheduled Pipeline.
// If we realize curved into a Halide::Image, that will
// unfairly penalize GPU performance by including a GPU->CPU
// copy in every run. Halide::Image objects always exist on
// the CPU.
// Halide::Buffer, however, represents a buffer that may
// exist on either CPU or GPU or both.
Buffer output(UInt(8), input.width(), input.height(), input.channels());
// Run the filter once to initialize any GPU runtime state.
curved.realize(output);
// Now take the best of 3 runs for timing.
double best_time;
for (int i = 0; i < 3; i++) {
double t1 = current_time();
// Run the filter 100 times.
for (int j = 0; j < 100; j++) {
curved.realize(output);
}
// Force any GPU code to finish by copying the buffer back to the CPU.
output.copy_to_host();
double t2 = current_time();
double elapsed = (t2 - t1)/100;
if (i == 0 || elapsed < best_time) {
best_time = elapsed;
}
}
printf("%1.4f milliseconds\n", best_time);
}
void test_correctness(Image<uint8_t> reference_output) {
Image<uint8_t> output = curved.realize(input.width(), input.height(), input.channels());
// Check against the reference output.
for (int c = 0; c < input.channels(); c++) {
for (int y = 0; y < input.height(); y++) {
for (int x = 0; x < input.width(); x++) {
if (output(x, y, c) != reference_output(x, y, c)) {
printf("Mismatch between output (%d) and "
"reference output (%d) at %d, %d, %d\n",
output(x, y, c),
reference_output(x, y, c),
x, y, c);
}
}
}
}
}
};
bool have_opencl();
int main(int argc, char **argv) {
// Load an input image.
Image<uint8_t> input = load<uint8_t>("images/rgb.png");
// Allocated an image that will store the correct output
Image<uint8_t> reference_output(input.width(), input.height(), input.channels());
printf("Testing performance on CPU:\n");
Pipeline p1(input);
p1.schedule_for_cpu();
p1.test_performance();
p1.curved.realize(reference_output);
if (have_opencl()) {
printf("Testing performance on GPU:\n");
Pipeline p2(input);
p2.schedule_for_gpu();
p2.test_performance();
p2.test_correctness(reference_output);
} else {
printf("Not testing performance on GPU, because I can't find the opencl library\n");
}
return 0;
}
// A helper function to check if OpenCL seems to exist on this machine.
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
bool have_opencl() {
#ifdef _WIN32
return LoadLibrary("opengl.dll") != NULL;
#elif __APPLE__
return dlopen("/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL", RTLD_LAZY) != NULL;
#else
return dlopen("libOpenCL.so", RTLD_LAZY) != NULL;
#endif
}
<|endoftext|> |
<commit_before>#include "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"
#include "itkThreeDCircularProjectionGeometryXMLFile.h"
#include "itkProjectionsReader.h"
#include "itkDisplacedDetectorImageFilter.h"
#include "itkFDKWeightProjectionFilter.h"
#include "itkFFTRampImageFilter.h"
#include "itkFDKBackProjectionImageFilter.h"
#if CUDA_FOUND
# include "itkCudaFDKBackProjectionImageFilter.h"
#endif
#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkTimeProbe.h>
#include <itkStreamingImageFilter.h>
int main(int argc, char * argv[])
{
GGO(rtkfdk, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
// Generate file names
itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
names->SetDirectory(args_info.path_arg);
names->SetNumericSort(false);
names->SetRegularExpression(args_info.regexp_arg);
names->SetSubMatch(0);
if(args_info.verbose_flag)
std::cout << "Regular expression matches "
<< names->GetFileNames().size()
<< " file(s)..."
<< std::endl;
// Projections reader
typedef itk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileNames( names->GetFileNames() );
reader->GenerateOutputInformation();
itk::TimeProbe readerProbe;
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Reading... " << std::flush;
try {
readerProbe.Start();
reader->Update();
readerProbe.Stop();
} catch( itk::ExceptionObject & err ) {
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if(args_info.verbose_flag)
std::cout << "It took " << readerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Geometry
if(args_info.verbose_flag)
std::cout << "Reading geometry information from "
<< args_info.geometry_arg
<< "..."
<< std::endl;
itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New();
geometryReader->SetFilename(args_info.geometry_arg);
geometryReader->GenerateOutputInformation();
// Displaced detector weighting
typedef itk::DisplacedDetectorImageFilter< OutputImageType > DDFType;
DDFType::Pointer ddf = DDFType::New();
ddf->SetInput( reader->GetOutput() );
ddf->SetGeometry( geometryReader->GetOutputObject() );
// Weight projections according to fdk algorithm
typedef itk::FDKWeightProjectionFilter< OutputImageType > WeightFilterType;
WeightFilterType::Pointer weightFilter = WeightFilterType::New();
weightFilter->SetInput( ddf->GetOutput() );
weightFilter->SetSourceToDetectorDistance( geometryReader->GetOutputObject()->GetSourceToDetectorDistance() );
weightFilter->SetInPlace(false); //SR: there seems to be a bug in ITK: incompatibility between InPlace and streaming?
// Ramp filter
typedef itk::FFTRampImageFilter<OutputImageType> RampFilterType;
RampFilterType::Pointer rampFilter = RampFilterType::New();
rampFilter->SetInput( weightFilter->GetOutput() );
rampFilter->SetTruncationCorrection(args_info.pad_arg);
rampFilter->SetHannCutFrequency(args_info.hann_arg);
// Streaming filter
typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
StreamerType::Pointer streamer = StreamerType::New();
streamer->SetInput( rampFilter->GetOutput() );
streamer->SetNumberOfStreamDivisions( geometryReader->GetOutputObject()->GetMatrices().size() );
// Try to do all 2D pre-processing
itk::TimeProbe streamerProbe;
if(!args_info.lowmem_flag)
{
try
{
if(args_info.verbose_flag)
std::cout << "Weighting and filtering projections... " << std::flush;
streamerProbe.Start();
streamer->Update();
streamerProbe.Stop();
if(args_info.verbose_flag)
std::cout << "It took " << streamerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
}
// Create reconstructed volume
OutputImageType::Pointer tomography = rtk::CreateImageFromGgo<OutputImageType>(args_info);
// Backprojection
typedef itk::FDKBackProjectionImageFilter<OutputImageType, OutputImageType> BackProjectionFilterType;
BackProjectionFilterType::Pointer bpFilter;
if(!strcmp(args_info.hardware_arg, "cpu"))
bpFilter = BackProjectionFilterType::New();
else if(!strcmp(args_info.hardware_arg, "cuda"))
{
#if CUDA_FOUND
bpFilter = itk::CudaFDKBackProjectionImageFilter::New();
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
bpFilter->SetInput( 0, tomography );
bpFilter->SetUpdateProjectionPerProjection(args_info.lowmem_flag);
if(args_info.lowmem_flag)
bpFilter->SetInput( 1, rampFilter->GetOutput() );
else
bpFilter->SetInput( 1, streamer->GetOutput() );
bpFilter->SetGeometry( geometryReader->GetOutputObject() );
bpFilter->SetInPlace( true );
// SR: this appears to trigger 2 updates in cuda mode with the lowmem option
// and an off-centered geometry. No clue why... Disable this update
// until the problem is understood and solved.
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Backprojecting using "
<< args_info.hardware_arg
<< "... " << std::flush;
itk::TimeProbe bpProbe;
try {
bpProbe.Start();
bpFilter->Update();
bpProbe.Stop();
} catch( itk::ExceptionObject & err ) {
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if(args_info.verbose_flag)
std::cout << "It took " << bpProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Write
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( bpFilter->GetOutput() );
if(args_info.verbose_flag)
std::cout << "Writing... " << std::flush;
itk::TimeProbe writerProbe;
try {
writerProbe.Start();
writer->Update();
writerProbe.Stop();
} catch( itk::ExceptionObject & err ) {
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if(args_info.verbose_flag)
std::cout << "It took " << writerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>Added parker weighting for short scan in fdk pipeline<commit_after>#include "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"
#include "itkThreeDCircularProjectionGeometryXMLFile.h"
#include "itkProjectionsReader.h"
#include "itkDisplacedDetectorImageFilter.h"
#include "itkParkerShortScanImageFilter.h"
#include "itkFDKWeightProjectionFilter.h"
#include "itkFFTRampImageFilter.h"
#include "itkFDKBackProjectionImageFilter.h"
#if CUDA_FOUND
# include "itkCudaFDKBackProjectionImageFilter.h"
#endif
#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkTimeProbe.h>
#include <itkStreamingImageFilter.h>
int main(int argc, char * argv[])
{
GGO(rtkfdk, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
// Generate file names
itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
names->SetDirectory(args_info.path_arg);
names->SetNumericSort(false);
names->SetRegularExpression(args_info.regexp_arg);
names->SetSubMatch(0);
if(args_info.verbose_flag)
std::cout << "Regular expression matches "
<< names->GetFileNames().size()
<< " file(s)..."
<< std::endl;
// Projections reader
typedef itk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileNames( names->GetFileNames() );
reader->GenerateOutputInformation();
itk::TimeProbe readerProbe;
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Reading... " << std::flush;
try {
readerProbe.Start();
reader->Update();
readerProbe.Stop();
} catch( itk::ExceptionObject & err ) {
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if(args_info.verbose_flag)
std::cout << "It took " << readerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Geometry
if(args_info.verbose_flag)
std::cout << "Reading geometry information from "
<< args_info.geometry_arg
<< "..."
<< std::endl;
itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New();
geometryReader->SetFilename(args_info.geometry_arg);
geometryReader->GenerateOutputInformation();
// Displaced detector weighting
typedef itk::DisplacedDetectorImageFilter< OutputImageType > DDFType;
DDFType::Pointer ddf = DDFType::New();
ddf->SetInput( reader->GetOutput() );
ddf->SetGeometry( geometryReader->GetOutputObject() );
ddf->InPlaceOff();
// Short scan image filter
typedef itk::ParkerShortScanImageFilter< OutputImageType > PSSFType;
PSSFType::Pointer pssf = PSSFType::New();
pssf->SetInput( ddf->GetOutput() );
pssf->SetGeometry( geometryReader->GetOutputObject() );
pssf->SetNumberOfThreads(1);
pssf->InPlaceOff();
// Weight projections according to fdk algorithm
typedef itk::FDKWeightProjectionFilter< OutputImageType > WeightFilterType;
WeightFilterType::Pointer weightFilter = WeightFilterType::New();
weightFilter->SetInput( pssf->GetOutput() );
weightFilter->SetSourceToDetectorDistance( geometryReader->GetOutputObject()->GetSourceToDetectorDistance() );
weightFilter->SetInPlace(false); //SR: there seems to be a bug in ITK: incompatibility between InPlace and streaming?
// Ramp filter
typedef itk::FFTRampImageFilter<OutputImageType> RampFilterType;
RampFilterType::Pointer rampFilter = RampFilterType::New();
rampFilter->SetInput( weightFilter->GetOutput() );
rampFilter->SetTruncationCorrection(args_info.pad_arg);
rampFilter->SetHannCutFrequency(args_info.hann_arg);
// Streaming filter
typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
StreamerType::Pointer streamer = StreamerType::New();
streamer->SetInput( rampFilter->GetOutput() );
streamer->SetNumberOfStreamDivisions( geometryReader->GetOutputObject()->GetMatrices().size() );
// Try to do all 2D pre-processing
itk::TimeProbe streamerProbe;
if(!args_info.lowmem_flag)
{
try
{
if(args_info.verbose_flag)
std::cout << "Weighting and filtering projections... " << std::flush;
streamerProbe.Start();
streamer->Update();
streamerProbe.Stop();
if(args_info.verbose_flag)
std::cout << "It took " << streamerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
}
// Create reconstructed volume
OutputImageType::Pointer tomography = rtk::CreateImageFromGgo<OutputImageType>(args_info);
// Backprojection
typedef itk::FDKBackProjectionImageFilter<OutputImageType, OutputImageType> BackProjectionFilterType;
BackProjectionFilterType::Pointer bpFilter;
if(!strcmp(args_info.hardware_arg, "cpu"))
bpFilter = BackProjectionFilterType::New();
else if(!strcmp(args_info.hardware_arg, "cuda"))
{
#if CUDA_FOUND
bpFilter = itk::CudaFDKBackProjectionImageFilter::New();
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
bpFilter->SetInput( 0, tomography );
bpFilter->SetUpdateProjectionPerProjection(args_info.lowmem_flag);
if(args_info.lowmem_flag)
bpFilter->SetInput( 1, rampFilter->GetOutput() );
else
bpFilter->SetInput( 1, streamer->GetOutput() );
bpFilter->SetGeometry( geometryReader->GetOutputObject() );
bpFilter->SetInPlace( true );
// SR: this appears to trigger 2 updates in cuda mode with the lowmem option
// and an off-centered geometry. No clue why... Disable this update
// until the problem is understood and solved.
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Backprojecting using "
<< args_info.hardware_arg
<< "... " << std::flush;
itk::TimeProbe bpProbe;
try {
bpProbe.Start();
bpFilter->Update();
bpProbe.Stop();
} catch( itk::ExceptionObject & err ) {
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if(args_info.verbose_flag)
std::cout << "It took " << bpProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Write
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( bpFilter->GetOutput() );
if(args_info.verbose_flag)
std::cout << "Writing... " << std::flush;
itk::TimeProbe writerProbe;
try {
writerProbe.Start();
writer->Update();
writerProbe.Stop();
} catch( itk::ExceptionObject & err ) {
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if(args_info.verbose_flag)
std::cout << "It took " << writerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*!
\file WindowManager.cpp
\author Dane Gardner <dane.gardner@gmail.com>
\section LICENSE
This file is part of the Parallel Tools GUI Framework (PTGF)
Copyright (C) 2010-2013 Argo Navis Technologies, LLC
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "WindowManagerPrivate.h"
#include <QMenuBar>
#include <CoreWindow/CoreWindow.h>
#include <ActionManager/ActionManager.h>
#include <PluginManager/PluginManager.h>
#include "IMainWindow.h"
#include "AboutDialog.h"
namespace Core {
namespace WindowManager {
/*! \class WindowManager
\brief Manages the main window interface implementors
\todo documentation
*/
WindowManager &WindowManager::instance()
{
static WindowManager m_Instance;
return m_Instance;
}
WindowManager::WindowManager() :
QObject(0),
d(new WindowManagerPrivate)
{
d->q = this;
AboutDialog::splash();
}
WindowManager::~WindowManager()
{
}
bool WindowManager::initialize()
{
if(d->m_Initialized) {
return false;
}
try {
/*** Register our menu structure ***/
ActionManager::ActionManager &actionManager = ActionManager::ActionManager::instance();
ActionManager::MenuPath path("Help");
d->m_AboutPage = actionManager.createAction(NULL, path);
d->m_AboutPage->setText(tr("About"));
d->m_AboutPage->setToolTip(tr("Displays the about dialog"));
d->m_AboutPage->setIcon(QIcon(":/CoreWindow/app.png"));
d->m_AboutPage->setIconVisibleInMenu(true);
connect(d->m_AboutPage, SIGNAL(triggered()), d.data(), SLOT(aboutDialog()));
/* Check the object pool for anything we should manage */
PluginManager::PluginManager &pluginManager = PluginManager::PluginManager::instance();
foreach(QObject *object, pluginManager.allObjects()) { d->pluginObjectRegistered(object); }
connect(&pluginManager, SIGNAL(objectAdded(QObject*)), d.data(), SLOT(pluginObjectRegistered(QObject*)));
connect(&pluginManager, SIGNAL(objectRemoving(QObject*)), d.data(), SLOT(pluginObjectDeregistered(QObject*)));
} catch(...) {
return false;
}
return d->m_Initialized = true;
}
void WindowManager::shutdown()
{
if(!d->m_Initialized) {
return;
}
// ...
}
/*! \internal
\returns sorted list of all registered MainWindows
*/
QList<IMainWindow *> WindowManager::mainWindows()
{
// Resort by priority
if(d->m_MainWindows.count() > 1) {
qSort(d->m_MainWindows.begin(), d->m_MainWindows.end(), d->ascending);
}
return d->m_MainWindows;
}
/*! \internal
\returns sorted list of all registered about dialog widgets
*/
QList<QWidget *> WindowManager::aboutWidgets()
{
QList<QWidget *> aboutWidgets;
foreach(IMainWindow *mainWindow, mainWindows()) {
QWidget *aboutWidget = mainWindow->createAboutWidget();
if(aboutWidget && !aboutWidgets.contains(aboutWidget)) {
aboutWidgets.append(aboutWidget);
}
}
return aboutWidgets;
}
/***** PRIVATE IMPLEMENTATION *****/
WindowManagerPrivate::WindowManagerPrivate() :
QObject(NULL),
q(NULL),
m_Initialized(false),
m_AboutPage(NULL)
{
}
void WindowManagerPrivate::aboutDialog()
{
// try {
AboutDialog aboutDialog;
aboutDialog.exec();
// } catch(QString err) {
// Core::CoreWindow::CoreWindow::instance().notify(tr("Failed to open about dialog: %1").arg(err), NotificationWidget::Critical);
// } catch(...) {
// using namespace Core::CoreWindow;
// Core::CoreWindow::CoreWindow::instance().notify(tr("Failed to open about dialog."), NotificationWidget::Critical);
// }
}
void WindowManagerPrivate::pluginObjectRegistered(QObject *object)
{
IMainWindow *mainWindow = qobject_cast<IMainWindow *>(object);
if(mainWindow) registerMainWindow(mainWindow);
}
void WindowManagerPrivate::pluginObjectDeregistered(QObject *object)
{
IMainWindow *mainWindow = qobject_cast<IMainWindow *>(object);
if(mainWindow) deregisterMainWindow(mainWindow);
}
void WindowManagerPrivate::registerMainWindow(IMainWindow *window)
{
m_MainWindows.append(window);
connect(window, SIGNAL(active()), this, SLOT(windowActivated()));
CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance();
coreWindow.setWindowTitle(window->mainWindowWidget()->windowTitle());
coreWindow.setWindowIcon(window->mainWindowWidget()->windowIcon());
/*** Set our main widget in the main window ***/
coreWindow.addCentralWidget(window->mainWindowWidget(),
window->mainWindowPriority(),
window->mainWindowName(),
window->mainWindowIcon());
}
void WindowManagerPrivate::deregisterMainWindow(IMainWindow *window)
{
if(m_MainWindows.contains(window)) {
m_MainWindows.removeOne(window);
disconnect(window, SIGNAL(active()), this, SLOT(windowActivated()));
CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance();
coreWindow.removeCentralWidget(window->mainWindowWidget());
}
}
void WindowManagerPrivate::windowActivated()
{
IMainWindow *mainWindow = qobject_cast<IMainWindow *>(sender());
if(!mainWindow) {
return;
}
//! \todo Hide all windows' actions
//! \todo Show the activated window's actions
}
/*! \fn WindowManagerPrivate::ascending()
\internal
\brief Used by qSort to sort the m_MainWindows QList in order of priority
\sa qSort
*/
bool WindowManagerPrivate::ascending(IMainWindow *left, IMainWindow *right)
{
return left->mainWindowPriority() < right->mainWindowPriority();
}
} // namespace WindowManager
} // namespace Core
<commit_msg>Fixed error handling in WindowManager about dialog handling<commit_after>/*!
\file WindowManager.cpp
\author Dane Gardner <dane.gardner@gmail.com>
\section LICENSE
This file is part of the Parallel Tools GUI Framework (PTGF)
Copyright (C) 2010-2013 Argo Navis Technologies, LLC
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "WindowManagerPrivate.h"
#include <QMenuBar>
#include <QDebug>
#include <CoreWindow/CoreWindow.h>
#include <ActionManager/ActionManager.h>
#include <PluginManager/PluginManager.h>
#include "IMainWindow.h"
#include "AboutDialog.h"
namespace Core {
namespace WindowManager {
/*! \class WindowManager
\brief Manages the main window interface implementors
\todo documentation
*/
WindowManager &WindowManager::instance()
{
static WindowManager m_Instance;
return m_Instance;
}
WindowManager::WindowManager() :
QObject(0),
d(new WindowManagerPrivate)
{
d->q = this;
AboutDialog::splash();
}
WindowManager::~WindowManager()
{
}
bool WindowManager::initialize()
{
if(d->m_Initialized) {
return false;
}
try {
/*** Register our menu structure ***/
ActionManager::ActionManager &actionManager = ActionManager::ActionManager::instance();
ActionManager::MenuPath path("Help");
d->m_AboutPage = actionManager.createAction(NULL, path);
d->m_AboutPage->setText(tr("About"));
d->m_AboutPage->setToolTip(tr("Displays the about dialog"));
d->m_AboutPage->setIcon(QIcon(":/CoreWindow/app.png"));
d->m_AboutPage->setIconVisibleInMenu(true);
connect(d->m_AboutPage, SIGNAL(triggered()), d.data(), SLOT(aboutDialog()));
/* Check the object pool for anything we should manage */
PluginManager::PluginManager &pluginManager = PluginManager::PluginManager::instance();
foreach(QObject *object, pluginManager.allObjects()) { d->pluginObjectRegistered(object); }
connect(&pluginManager, SIGNAL(objectAdded(QObject*)), d.data(), SLOT(pluginObjectRegistered(QObject*)));
connect(&pluginManager, SIGNAL(objectRemoving(QObject*)), d.data(), SLOT(pluginObjectDeregistered(QObject*)));
} catch(...) {
return false;
}
return d->m_Initialized = true;
}
void WindowManager::shutdown()
{
if(!d->m_Initialized) {
return;
}
// ...
}
/*! \internal
\returns sorted list of all registered MainWindows
*/
QList<IMainWindow *> WindowManager::mainWindows()
{
// Resort by priority
if(d->m_MainWindows.count() > 1) {
qSort(d->m_MainWindows.begin(), d->m_MainWindows.end(), d->ascending);
}
return d->m_MainWindows;
}
/*! \internal
\returns sorted list of all registered about dialog widgets
*/
QList<QWidget *> WindowManager::aboutWidgets()
{
QList<QWidget *> aboutWidgets;
foreach(IMainWindow *mainWindow, mainWindows()) {
QWidget *aboutWidget = mainWindow->createAboutWidget();
if(aboutWidget && !aboutWidgets.contains(aboutWidget)) {
aboutWidgets.append(aboutWidget);
}
}
return aboutWidgets;
}
/***** PRIVATE IMPLEMENTATION *****/
WindowManagerPrivate::WindowManagerPrivate() :
QObject(NULL),
q(NULL),
m_Initialized(false),
m_AboutPage(NULL)
{
}
void WindowManagerPrivate::aboutDialog()
{
try {
AboutDialog aboutDialog;
aboutDialog.exec();
} catch(QString err) {
qCritical() << tr("Failed to open about dialog: %1").arg(err);
} catch(...) {
qCritical() << tr("Failed to open about dialog.");
}
}
void WindowManagerPrivate::pluginObjectRegistered(QObject *object)
{
IMainWindow *mainWindow = qobject_cast<IMainWindow *>(object);
if(mainWindow) registerMainWindow(mainWindow);
}
void WindowManagerPrivate::pluginObjectDeregistered(QObject *object)
{
IMainWindow *mainWindow = qobject_cast<IMainWindow *>(object);
if(mainWindow) deregisterMainWindow(mainWindow);
}
void WindowManagerPrivate::registerMainWindow(IMainWindow *window)
{
m_MainWindows.append(window);
connect(window, SIGNAL(active()), this, SLOT(windowActivated()));
CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance();
coreWindow.setWindowTitle(window->mainWindowWidget()->windowTitle());
coreWindow.setWindowIcon(window->mainWindowWidget()->windowIcon());
/*** Set our main widget in the main window ***/
coreWindow.addCentralWidget(window->mainWindowWidget(),
window->mainWindowPriority(),
window->mainWindowName(),
window->mainWindowIcon());
}
void WindowManagerPrivate::deregisterMainWindow(IMainWindow *window)
{
if(m_MainWindows.contains(window)) {
m_MainWindows.removeOne(window);
disconnect(window, SIGNAL(active()), this, SLOT(windowActivated()));
CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance();
coreWindow.removeCentralWidget(window->mainWindowWidget());
}
}
void WindowManagerPrivate::windowActivated()
{
IMainWindow *mainWindow = qobject_cast<IMainWindow *>(sender());
if(!mainWindow) {
return;
}
//! \todo Hide all windows' actions
//! \todo Show the activated window's actions
}
/*! \fn WindowManagerPrivate::ascending()
\internal
\brief Used by qSort to sort the m_MainWindows QList in order of priority
\sa qSort
*/
bool WindowManagerPrivate::ascending(IMainWindow *left, IMainWindow *right)
{
return left->mainWindowPriority() < right->mainWindowPriority();
}
} // namespace WindowManager
} // namespace Core
<|endoftext|> |
<commit_before>#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
// Good diagram: https://engmrk.com/wp-content/uploads/2018/09/Image-Architecture-of-Convolutional-Neural-Network.png
class Layer {
public:
vector<vector<vector<double>>> h(vector<vector<vector<double>>> x);
// Helper function
static void rand_init(vector<vector<double>> matrix, int height, int width) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// use numbers between -100 and 100
double n = (double)rand() / RAND_MAX; // scales rand() to [0, 1].
n = n * 200 - 100;
matrix[i][j] = n; // (possibly) change to use float to save memory
}
}
}
};
class Conv : public Layer {
public:
int num_input_channels;
int num_filters;
vector<int> size_per_filter;
vector<int> stride_per_filter;
vector<vector<vector<double>>> filters;
Conv(int num_input_channels, int num_filters, vector<int> size_per_filter, vector<int> stride_per_filter) {
// TODO: Check if there is a better way to save these.
num_input_channels = num_input_channels;
num_filters = num_filters;
size_per_filter = size_per_filter;
stride_per_filter = stride_per_filter;
for (int filter_num; filter_num < num_filters; filter_num++) {
// Filters are square
int height = size_per_filter[filter_num];
int width = size_per_filter[filter_num];
vector<vector<double>> filter;
Layer().rand_init(filter, height, width);
filters[filter_num] = filter;
}
}
// vector<vector<vector<double>>> h(vector<vector<vector<double>>> a) {
// // Input and output is height x width x num_channels
// // First filter adds to the output of the first channel only, etc.
// // feature map (or activation map) is the output of one filter (or kernel or detector)
// vector<vector<vector<double>>> output_block;
// int num_filters = filters.size();
// for (int i = 0; i < num_filters; i++) { // Should be embarrassingly parallel
// vector<vector<double>> feature_map = convolve(a, filters[i], stride_per_filter[i]);
// }
// }
// static because this is a self-contained method
vector<vector<double>> static convolve(vector<vector<vector<double>>> a, vector<vector<double>> filter, int stride) {
// a is height x width x num_channels
// Let's say a is 10x10x3 and filter is 3x3
// The first convolutional step will use a's top left corner block of size 3x3x3
// For each (i, j, [1, 2, 3]) section of a, we use the same (i, j)th weight of filter to flatten it
// In other words, we do a[i][j][1]*w + a[i][j][2]*w + a[i][j][3]*w.
// This produces a 3x3x1 which we then element-wise multiply with filter which is also 3x3x1 to
// produce 3x3x1 multiplications. These are then all added together to produce one output per
// convolutional step.
// Reference:
//
// https://stats.stackexchange.com/questions/335321/in-a-convolutional-neural-network-cnn-when-convolving-the-image-is-the-opera
int height = a.size();
int width = a[0].size();
int depth = a[0][0].size();
int depth_of_a = a.size();
vector<vector<double>> feature_map = _convolve(a[0], filter, stride);
for (int depth = 1; depth < depth_of_a; depth++) {
vector<vector<double>> feature_map_for_depth = _convolve(a[depth], filter, stride);
feature_map = add_matrices(feature_map, feature_map_for_depth);
}
return feature_map;
}
vector<vector<double>> static add_matrices(vector<vector<double>> a, vector<vector<double>> b) {
vector<vector<double>> c;
for (int i = 0; i < a.size(); i++) {
vector<double> c_column;
for (int j = 0; j < a[0].size(); j++) {
c_column.push_back(a[i][j] + b[i][j]);
}
c.push_back(c_column);
}
return c;
}
vector<vector<double>> static _convolve(vector<vector<double>> a, vector<vector<double>> filter, int stride) {
// Maybe switch the order of i and j
int i = 0;
int j = 0;
vector<vector<double>> convolved;
while (i <= a.size() - filter.size()) {
vector<double> convolved_column;
while (j <= a[0].size() - filter[0].size()) {
double acc_sum{0.0};
for (int x = 0; x < filter.size(); ++x) {
for (int y = 0; y < filter[0].size(); ++y) {
acc_sum = acc_sum + a[i + x][j + y] * filter[x][y];
}
}
convolved_column.push_back(acc_sum);
j = j + stride;
}
convolved.push_back(convolved_column);
j = 0;
i = i + stride;
}
return convolved;
}
void static _convole_test() {
vector<vector<double>> a = {{1.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}};
vector<vector<double>> filter = {{1.0, 0.0, 1.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 1.0}};
vector<vector<double>> actual_output = _convolve(a, filter, 2);
vector<vector<double>> expected_output = {{4.0, 4.0}, {2.0, 4.0}};
for (int i = 0; i < actual_output.size(); i++) {
for (int j = 0; j < actual_output[i].size(); j++) {
cout << actual_output[i][j] << ",";
if (actual_output[i][j] != expected_output[i][j]) {
throw;
}
}
cout << endl;
}
vector<vector<double>> a2 = {{1.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}};
vector<vector<double>> filter2 = {{1.0}};
vector<vector<double>> actual_output2 = _convolve(a2, filter2, 1);
vector<vector<double>> expected_output2 = {{1.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}};
for (int i = 0; i < actual_output2.size(); i++) {
for (int j = 0; j < actual_output2[i].size(); j++) {
cout << actual_output2[i][j] << ",";
if (actual_output2[i][j] != expected_output2[i][j]) {
throw;
}
}
cout << endl;
}
}
};
class Pool : public Layer {};
class Act : public Layer {};
class Dense : public Layer {};
class ConvNet {
public:
vector<Layer> layers;
ConvNet(vector<Layer> layers) { layers = layers; }
// int h(vector<vector<vector<double>>> x) { // Returns an int, a classification
// vector<vector<vector<double>>> a = x;
// for (Layer layer : layers) {
// vector<vector<vector<double>>> a = layer.h(a);
// }
// // Convert the final output into a classification
// }
};
int main() {
// TEST
cout << "Starting test...\n";
// int num_images = 100;
// vector<vector<vector<vector<double>>>> X; // num_images x height x width x num_channels
// int Y[num_images]; // labels for each example
// // Randomly initialize X and Y
// for (int i = 0; i < num_images; i++) {
// for (int j = 0; j < 28; j++) {
// for (int k = 0; k < 28; k++) {
// // use numbers from 0 to 255
// X[i][j][k][1] = rand() % 255; //TODO: Use push_back
// }
// }
// Y[i] = rand() % 10; // TODO: Maybe decrease number of classes for the test?
// }
// // Look at first 2 "images"
// for (int i = 0; i < 2; i++) {
// for (int j = 0; j < 28; j++) {
// for (int k = 0; k < 28; k++) {
// cout << X[j][k][i][1] << ",";
// }
// cout << endl;
// }
// cout << endl;
// }
Conv::_convole_test();
// Intialize model
// Compound literal, (vector[]), helps initialize an array in function call
// ConvNet model = ConvNet(vector<Layer>{Conv(1, 4, (vector<int>){3, 3, 5, 5}, (vector<int>){1, 1, 2, 2})});
// Do a forward pass with the first "image"
// model.h(X[1]);
cout << "Test finished!\n";
// Main
return 0;
}
<commit_msg>add depth convolution and test<commit_after>#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
// Good diagram: https://engmrk.com/wp-content/uploads/2018/09/Image-Architecture-of-Convolutional-Neural-Network.png
class Layer {
public:
vector<vector<vector<double>>> h(vector<vector<vector<double>>> x);
// Helper function
static void rand_init(vector<vector<double>> matrix, int height, int width) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// use numbers between -100 and 100
double n = (double)rand() / RAND_MAX; // scales rand() to [0, 1].
n = n * 200 - 100;
matrix[i][j] = n; // (possibly) change to use float to save memory
}
}
}
};
class Conv : public Layer {
public:
int num_input_channels;
int num_filters;
vector<int> size_per_filter;
vector<int> stride_per_filter;
vector<vector<vector<double>>> filters;
Conv(int num_input_channels, int num_filters, vector<int> size_per_filter, vector<int> stride_per_filter) {
// TODO: Check if there is a better way to save these.
num_input_channels = num_input_channels;
num_filters = num_filters;
size_per_filter = size_per_filter;
stride_per_filter = stride_per_filter;
for (int filter_num; filter_num < num_filters; filter_num++) {
// Filters are square
int height = size_per_filter[filter_num];
int width = size_per_filter[filter_num];
vector<vector<double>> filter;
Layer().rand_init(filter, height, width);
filters[filter_num] = filter;
}
}
// vector<vector<vector<double>>> h(vector<vector<vector<double>>> a) {
// // Input and output is height x width x num_channels
// // First filter adds to the output of the first channel only, etc.
// // feature map (or activation map) is the output of one filter (or kernel or detector)
// vector<vector<vector<double>>> output_block;
// int num_filters = filters.size();
// for (int i = 0; i < num_filters; i++) { // Should be embarrassingly parallel
// vector<vector<double>> feature_map = convolve(a, filters[i], stride_per_filter[i]);
// }
// }
// static because this is a self-contained method
vector<vector<double>> static convolve(vector<vector<vector<double>>> a, vector<vector<double>> filter, int stride) {
// a is height x width x num_channels
// Let's say a is 10x10x3 and filter is 3x3
// The first convolutional step will use a's top left corner block of size 3x3x3
// For each (i, j, [1, 2, 3]) section of a, we use the same (i, j)th weight of filter to flatten it
// In other words, we do a[i][j][1]*w + a[i][j][2]*w + a[i][j][3]*w.
// This produces a 3x3x1 which we then element-wise multiply with filter which is also 3x3x1 to
// produce 3x3x1 multiplications. These are then all added together to produce one output per
// convolutional step.
// Reference:
//
// https://stats.stackexchange.com/questions/335321/in-a-convolutional-neural-network-cnn-when-convolving-the-image-is-the-opera
int height = a.size();
int width = a[0].size();
int depth = a[0][0].size();
int depth_of_a = a.size();
vector<vector<double>> feature_map = _convolve(a[0], filter, stride);
for (int depth = 1; depth < depth_of_a; depth++) {
vector<vector<double>> feature_map_for_depth = _convolve(a[depth], filter, stride);
feature_map = add_matrices(feature_map, feature_map_for_depth);
}
return feature_map;
}
vector<vector<double>> static add_matrices(vector<vector<double>> a, vector<vector<double>> b) {
vector<vector<double>> c;
for (int i = 0; i < a.size(); i++) {
vector<double> c_column;
for (int j = 0; j < a[0].size(); j++) {
c_column.push_back(a[i][j] + b[i][j]);
}
c.push_back(c_column);
}
return c;
}
vector<vector<double>> static _convolve(vector<vector<double>> a, vector<vector<double>> filter, int stride) {
// Maybe switch the order of i and j
int i = 0;
int j = 0;
vector<vector<double>> convolved;
while (i <= a.size() - filter.size()) {
vector<double> convolved_column;
while (j <= a[0].size() - filter[0].size()) {
double acc_sum{0.0};
for (int x = 0; x < filter.size(); ++x) {
for (int y = 0; y < filter[0].size(); ++y) {
acc_sum = acc_sum + a[i + x][j + y] * filter[x][y];
}
}
convolved_column.push_back(acc_sum);
j = j + stride;
}
convolved.push_back(convolved_column);
j = 0;
i = i + stride;
}
return convolved;
}
void static _convolve_test() {
vector<vector<double>> a = {{1.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}};
vector<vector<double>> filter = {{1.0, 0.0, 1.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 1.0}};
vector<vector<double>> actual_output = _convolve(a, filter, 2);
vector<vector<double>> expected_output = {{4.0, 4.0}, {2.0, 4.0}};
for (int i = 0; i < actual_output.size(); i++) {
for (int j = 0; j < actual_output[i].size(); j++) {
cout << actual_output[i][j] << ",";
if (actual_output[i][j] != expected_output[i][j]) {
throw;
}
}
cout << endl;
}
vector<vector<double>> a2 = {{1.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}};
vector<vector<double>> filter2 = {{1.0}};
vector<vector<double>> actual_output2 = _convolve(a2, filter2, 1);
vector<vector<double>> expected_output2 = {{1.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}};
for (int i = 0; i < actual_output2.size(); i++) {
for (int j = 0; j < actual_output2[i].size(); j++) {
cout << actual_output2[i][j] << ",";
if (actual_output2[i][j] != expected_output2[i][j]) {
throw;
}
}
cout << endl;
}
}
void static convolve_test() {
vector<vector<vector<double>>> a = {
{{1.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}},
{{0.0, 1.0, 0.0, 1.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 1.0},
{0.0, 1.0, 1.0, 0.0, 0.0}},
{{1.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 1.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0, 0.0},
{0.0, 0.0, 0.0, 1.0, 0.0},
{0.0, 0.0, 0.0, 0.0, 1.0}}
};
vector<vector<double>> filter = {{1, 0},{1, 1}};
vector<vector<double>> actual_output = convolve(a, filter, 2);
vector<vector<double>> expected_output = {{4.0, 5.0}, {1.0, 7.0}};
for (int i = 0; i < actual_output.size(); i++) {
for (int j = 0; j < actual_output[i].size(); j++) {
cout << actual_output[i][j] << ",";
//if (actual_output[i][j] != expected_output[i][j]) {
//throw;
//}
}
cout << endl;
}
vector<vector<vector<double>>> a2 = {{{9.0, 1.0, 9.0, 0.0, 9.0},
{0.0, 1.0, 9.0, 1.0, 0.0},
{9.0, 0.0, 9.0, 1.0, 9.0},
{0.0, 0.0, 9.0, 0.0, 0.0},
{9.0, 1.0, 9.0, 0.0, 9.0}},
// {{0.0, 1.0, 1.0, 1.0, 0.0},
// {0.0, 1.0, 0.0, 1.0, 0.0},
// {0.0, 0.0, 1.0, 1.0, 1.0},
// {0.0, 0.0, 1.0, 1.0, 0.0},
// {0.0, 1.0, 1.0, 0.0, 1.0}},
// {{1.0, 0.0, 0.0, 0.0, 0.0},
// {0.0, 1.0, 0.0, 0.0, 0.0},
// {0.0, 0.0, 1.0, 0.0, 0.0},
// {0.0, 0.0, 0.0, 1.0, 0.0},
// {0.0, 0.0, 0.0, 0.0, 1.0}}
};
vector<vector<double>> filter2 = {{1.0}};
vector<vector<double>> actual_output2 = convolve(a2, filter2, 2);
vector<vector<double>> expected_output2 = {{9.0, 9.0, 9.0},{9.0, 9.0, 9.0}, {9.0, 9.0, 9.0}};
for (int i = 0; i < actual_output2.size(); i++) {
for (int j = 0; j < actual_output2[i].size(); j++) {
cout << actual_output2[i][j] << ",";
//if (actual_output[i][j] != expected_output[i][j]) {
//throw;
//}
}
cout << endl;
}
}
};
class Pool : public Layer {};
class Act : public Layer {};
class Dense : public Layer {};
class ConvNet {
public:
vector<Layer> layers;
ConvNet(vector<Layer> layers) { layers = layers; }
// int h(vector<vector<vector<double>>> x) { // Returns an int, a classification
// vector<vector<vector<double>>> a = x;
// for (Layer layer : layers) {
// vector<vector<vector<double>>> a = layer.h(a);
// }
// // Convert the final output into a classification
// }
};
int main() {
// TEST
cout << "Starting test...\n";
// int num_images = 100;
// vector<vector<vector<vector<double>>>> X; // num_images x height x width x num_channels
// int Y[num_images]; // labels for each example
// // Randomly initialize X and Y
// for (int i = 0; i < num_images; i++) {
// for (int j = 0; j < 28; j++) {
// for (int k = 0; k < 28; k++) {
// // use numbers from 0 to 255
// X[i][j][k][1] = rand() % 255; //TODO: Use push_back
// }
// }
// Y[i] = rand() % 10; // TODO: Maybe decrease number of classes for the test?
// }
// // Look at first 2 "images"
// for (int i = 0; i < 2; i++) {
// for (int j = 0; j < 28; j++) {
// for (int k = 0; k < 28; k++) {
// cout << X[j][k][i][1] << ",";
// }
// cout << endl;
// }
// cout << endl;
// }
//Conv::_convole_test();
Conv::convolve_test();
// Intialize model
// Compound literal, (vector[]), helps initialize an array in function call
// ConvNet model = ConvNet(vector<Layer>{Conv(1, 4, (vector<int>){3, 3, 5, 5}, (vector<int>){1, 1, 2, 2})});
// Do a forward pass with the first "image"
// model.h(X[1]);
cout << "Test finished!\n";
// Main
return 0;
}
<|endoftext|> |
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layout/CListOfLayouts.cpp,v $
// $Revision: 1.6 $
// $Name: $
// $Author: ssahle $
// $Date: 2007/08/17 12:35:28 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include "CListOfLayouts.h"
#include "report/CKeyFactory.h"
#include "sbml/layout/Layout.h"
CListOfLayouts::CListOfLayouts(const std::string & name,
const CCopasiContainer * pParent):
CCopasiVector<CLayout>(name, pParent),
mKey(GlobalKeys.add("Layout", this))
{}
CListOfLayouts::~CListOfLayouts()
{
GlobalKeys.remove(mKey);
}
const std::string& CListOfLayouts::getKey()
{
return mKey;
}
void CListOfLayouts::addLayout(CLayout * layout, const std::map<std::string, std::string> & m)
{
if (layout)
add(layout, true);
//TODO: store map
}
void CListOfLayouts::exportToSBML(ListOf * lol, std::map<CCopasiObject*, SBase*> & copasimodelmap) const
{
unsigned C_INT32 i, imax = this->size();
for (i = 0; i < imax; ++i)
{
CLayout * tmp = (*this)[i];
//check if the layout exists in the libsbml data
std::map<CCopasiObject*, SBase*>::const_iterator it;
it = copasimodelmap.find(tmp);
Layout * pLayout;
if (it == copasimodelmap.end()) //not found
{
//create new object and add to libsbml data structures
pLayout = new Layout;
lol->append(pLayout);
//add object to map
copasimodelmap[tmp] = pLayout;
}
else
{
pLayout = dynamic_cast<Layout*>(it->second);
}
tmp->exportToSBML(pLayout, copasimodelmap);
}
//check if a something needs to be deleted from the sbml data structures
//TODO
}
<commit_msg>work in progress...<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layout/CListOfLayouts.cpp,v $
// $Revision: 1.7 $
// $Name: $
// $Author: ssahle $
// $Date: 2007/08/20 08:57:45 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include "CListOfLayouts.h"
#include "report/CKeyFactory.h"
#include "sbml/layout/Layout.h"
CListOfLayouts::CListOfLayouts(const std::string & name,
const CCopasiContainer * pParent):
CCopasiVector<CLayout>(name, pParent),
mKey(GlobalKeys.add("Layout", this))
{}
CListOfLayouts::~CListOfLayouts()
{
GlobalKeys.remove(mKey);
}
const std::string& CListOfLayouts::getKey()
{
return mKey;
}
void CListOfLayouts::addLayout(CLayout * layout, const std::map<std::string, std::string> & m)
{
if (layout)
add(layout, true);
//TODO: store map
}
void CListOfLayouts::exportToSBML(ListOf * lol, std::map<CCopasiObject*, SBase*> & copasimodelmap) const
{
if (!lol) return;
//this will contain the SBML objects that were touched by this method.
std::set<SBase*> writtenToSBML;
//write all copasi object to corresponding libsbml objects
unsigned C_INT32 i, imax = this->size();
for (i = 0; i < imax; ++i)
{
CLayout * tmp = (*this)[i];
//check if the layout exists in the libsbml data
std::map<CCopasiObject*, SBase*>::const_iterator it;
it = copasimodelmap.find(tmp);
Layout * pLayout;
if (it == copasimodelmap.end()) //not found
{
//create new object and add to libsbml data structures
pLayout = new Layout;
lol->append(pLayout);
//add object to map
copasimodelmap[tmp] = pLayout;
}
else
{
pLayout = dynamic_cast<Layout*>(it->second);
}
tmp->exportToSBML(pLayout, copasimodelmap);
writtenToSBML.insert(pLayout);
}
//check if a something needs to be deleted from the sbml data structures
for (i = lol->getNumItems(); i > 0;--i)
{
SBase* object = lol->get(i - 1);
if (writtenToSBML.find(object) == writtenToSBML.end())
{
lol->remove(i - 1);
pdelete(object);
//TODO: delete from map
}
}
}
<|endoftext|> |
<commit_before>// @(#)root/thread:$Id$
// Author: Xavier Valls March 2016
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TExecutor
#define ROOT_TExecutor
#include "ROOT/TSeq.hxx"
#include "TList.h"
#include <vector>
namespace ROOT {
template<class subc>
class TExecutor {
public:
explicit TExecutor() = default;
explicit TExecutor(size_t /* nThreads */ ){};
template< class F, class... T>
using noReferenceCond = typename std::enable_if<"Function can't return a reference" && !(std::is_reference<typename std::result_of<F(T...)>::type>::value)>::type;
// // Map
// //these late return types allow for a compile-time check of compatibility between function signatures and args,
// //and a compile-time check that the argument list implements a front() method (all STL sequence containers have it)
template<class F, class Cond = noReferenceCond<F>>
auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>;
// /// \cond doxygen should ignore these methods
template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>>
auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>;
template<class F, class T, class Cond = noReferenceCond<F, T>>
auto Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>;
template<class F, class T, class Cond = noReferenceCond<F, T>>
auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>;
// // // / \endcond
// // MapReduce
// // the late return types also check at compile-time whether redfunc is compatible with func,
// // other than checking that func is compatible with the type of arguments.
// // a static_assert check in TExecutor<subc>::Reduce is used to check that redfunc is compatible with the type returned by func
template<class F, class R, class Cond = noReferenceCond<F>>
auto MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type;
template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>>
auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type;
// /// \cond doxygen should ignore these methods
template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
auto MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type;
template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
auto MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type;
template<class F, class T, class Cond = noReferenceCond<F, T>>
T* MapReduce(F func, std::vector<T*> &args);
// /// \endcond
template<class T> T* Reduce(const std::vector<T*> &mergeObjs);
private:
inline subc & Derived()
{
return *static_cast<subc*>(this);
}
};
//////////////////////////////////////////////////////////////////////////
/// Execute func (with no arguments) nTimes in parallel.
/// A vector containg executions' results is returned.
/// Functions that take more than zero arguments can be executed (with
/// fixed arguments) by wrapping them in a lambda or with std::bind.
template<class subc> template<class F, class Cond>
auto TExecutor<subc>::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>
{
return Derived().Map(func, nTimes);
}
// //////////////////////////////////////////////////////////////////////////
// /// Execute func in parallel distributing the elements of the args collection between the workers.
// /// See class description for the valid types of collections and containers that can be used.
// /// A vector containing each execution's result is returned. The user is responsible of deleting
// /// objects that might be created upon the execution of func, returned objects included.
// /// **Note:** the collection of arguments is modified by Map and should be considered empty or otherwise
// /// invalidated after Map's execution (std::move might be applied to it).
// tell doxygen to ignore this (\endcond closes the statement)
/// \cond
template<class subc> template<class F, class INTEGER, class Cond>
auto TExecutor<subc>::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>
{
return Derived().Map(func, args);
}
template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>
{
std::vector<T> vargs(std::move(args));
const auto &reslist = Map(func, vargs);
return reslist;
}
// actual implementation of the Map method. all other calls with arguments eventually
// call this one
template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>
{
return Derived().Map(func, args);
}
// //////////////////////////////////////////////////////////////////////////
// /// This method behaves just like Map, but an additional redfunc function
// /// must be provided. redfunc is applied to the vector Map would return and
// /// must return the same type as func. In practice, redfunc can be used to
// /// "squash" the vector returned by Map into a single object by merging,
// /// adding, mixing the elements of the vector.
template<class subc> template<class F, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type
{
return Derived().Reduce(Map(func, nTimes), redfunc);
}
//////////////////////////////////////////////////////////////////////////
/// This method behaves just like Map, but an additional redfunc function
/// must be provided. redfunc is applied to the vector Map would return and
/// must return the same type as func. In practice, redfunc can be used to
/// "squash" the vector returned by Map into a single object by merging,
/// adding, mixing the elements of the vector.
/// \cond doxygen should ignore these methods
template<class subc> template<class F, class INTEGER, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type
{
return Derived().Reduce(Map(func, args), redfunc);
}
template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type
{
return Derived().Reduce(Map(func, args), redfunc);
}
template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type
{
return Derived().Reduce(Map(func, args), redfunc);
}
template<class subc> template<class F, class T, class Cond>
T* TExecutor<subc>::MapReduce(F func, std::vector<T*> &args)
{
return Derived().Reduce(Map(func, args));
}
/// \endcond
//Reduction for objects with the Merge() method
template<class subc> template<class T>
T* TExecutor<subc>::Reduce(const std::vector<T*> &mergeObjs)
{
TList l;
for(unsigned i =1; i<mergeObjs.size(); i++){
l.Add(mergeObjs[i]);
}
// use clone to return a new object
auto retHist = dynamic_cast<T*>((mergeObjs.front())->Clone());
if (retHist) retHist->Merge(&l);
return retHist;
}
} // end namespace ROOT
#endif
<commit_msg>Improve documentation of TExecutor :books:<commit_after>// @(#)root/thread:$Id$
// Author: Xavier Valls March 2016
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TExecutor
#define ROOT_TExecutor
#include "ROOT/TSeq.hxx"
#include "TList.h"
#include <vector>
//////////////////////////////////////////////////////////////////////////
///
/// \class ROOT::TExecutor
/// \brief This class defines an interface to execute the same task
/// multiple times in parallel, possibly with different arguments every
/// time. The classes implementing it mimic the behaviour of python's pool.Map method.
///
/// ###ROOT::TExecutor::Map
/// The two possible usages of the Map method are:\n
/// * Map(F func, unsigned nTimes): func is executed nTimes with no arguments
/// * Map(F func, T& args): func is executed on each element of the collection of arguments args
///
/// For either signature, func is executed as many times as needed by a pool of
/// nThreads threads; It defaults to the number of cores.\n
/// A collection containing the result of each execution is returned.\n
/// **Note:** the user is responsible for the deletion of any object that might
/// be created upon execution of func, returned objects included: ROOT::TExecutor never
/// deletes what it returns, it simply forgets it.\n
///
/// \param func
/// \parblock
/// a lambda expression, an std::function, a loaded macro, a
/// functor class or a function that takes zero arguments (for the first signature)
/// or one (for the second signature).
/// \endparblock
/// \param args
/// \parblock
/// a standard vector, a ROOT::TSeq of integer type or an initializer list for the second signature.
/// An integer only for the first.\n
/// \endparblock
///
/// **Note:** in cases where the function to be executed takes more than
/// zero/one argument but all are fixed except zero/one, the function can be wrapped
/// in a lambda or via std::bind to give it the right signature.\n
///
/// #### Return value:
/// An std::vector. The elements in the container
/// will be the objects returned by func.
namespace ROOT {
template<class subc>
class TExecutor {
public:
explicit TExecutor() = default;
explicit TExecutor(size_t /* nThreads */ ){};
template< class F, class... T>
using noReferenceCond = typename std::enable_if<"Function can't return a reference" && !(std::is_reference<typename std::result_of<F(T...)>::type>::value)>::type;
// // Map
// //these late return types allow for a compile-time check of compatibility between function signatures and args,
// //and a compile-time check that the argument list implements a front() method (all STL sequence containers have it)
template<class F, class Cond = noReferenceCond<F>>
auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>;
template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>>
auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>;
template<class F, class T, class Cond = noReferenceCond<F, T>>
auto Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>;
template<class F, class T, class Cond = noReferenceCond<F, T>>
auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>;
// // MapReduce
// // the late return types also check at compile-time whether redfunc is compatible with func,
// // other than checking that func is compatible with the type of arguments.
// // a static_assert check in TExecutor<subc>::Reduce is used to check that redfunc is compatible with the type returned by func
template<class F, class R, class Cond = noReferenceCond<F>>
auto MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type;
template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>>
auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type;
template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
auto MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type;
template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
auto MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type;
template<class F, class T, class Cond = noReferenceCond<F, T>>
T* MapReduce(F func, std::vector<T*> &args);
template<class T> T* Reduce(const std::vector<T*> &mergeObjs);
private:
inline subc & Derived()
{
return *static_cast<subc*>(this);
}
};
//////////////////////////////////////////////////////////////////////////
/// Execute func (with no arguments) nTimes in parallel.
/// A vector containg executions' results is returned.
/// Functions that take more than zero arguments can be executed (with
/// fixed arguments) by wrapping them in a lambda or with std::bind.
template<class subc> template<class F, class Cond>
auto TExecutor<subc>::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>
{
return Derived().Map(func, nTimes);
}
//////////////////////////////////////////////////////////////////////////
/// Execute func in parallel, taking an element of a
/// sequence as argument. Divides and groups the executions in nChunks with partial reduction;
/// A vector containg partial reductions' results is returned.
template<class subc> template<class F, class INTEGER, class Cond>
auto TExecutor<subc>::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>
{
return Derived().Map(func, args);
}
//////////////////////////////////////////////////////////////////////////
/// Execute func in parallel, taking an element of the std::initializer_list
/// as argument. Divides and groups the executions in nChunks with partial reduction;
/// A vector containg partial reductions' results is returned.
template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>
{
std::vector<T> vargs(std::move(args));
const auto &reslist = Map(func, vargs);
return reslist;
}
//////////////////////////////////////////////////////////////////////////
/// Execute func in parallel, taking an element of an
/// std::vector as argument.
/// A vector containg executions' results is returned.
// actual implementation of the Map method. all other calls with arguments eventually
// call this one
template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>
{
return Derived().Map(func, args);
}
//////////////////////////////////////////////////////////////////////////
/// This method behaves just like Map, but an additional redfunc function
/// must be provided. redfunc is applied to the vector Map would return and
/// must return the same type as func. In practice, redfunc can be used to
/// "squash" the vector returned by Map into a single object by merging,
/// adding, mixing the elements of the vector.
template<class subc> template<class F, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type
{
return Derived().Reduce(Map(func, nTimes), redfunc);
}
template<class subc> template<class F, class INTEGER, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type
{
return Derived().Reduce(Map(func, args), redfunc);
}
template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type
{
return Derived().Reduce(Map(func, args), redfunc);
}
template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type
{
return Derived().Reduce(Map(func, args), redfunc);
}
template<class subc> template<class F, class T, class Cond>
T* TExecutor<subc>::MapReduce(F func, std::vector<T*> &args)
{
return Derived().Reduce(Map(func, args));
}
//////////////////////////////////////////////////////////////////////////
/// "Reduce" an std::vector into a single object by using the object's Merge
//Reduction for objects with the Merge() method
template<class subc> template<class T>
T* TExecutor<subc>::Reduce(const std::vector<T*> &mergeObjs)
{
TList l;
for(unsigned i =1; i<mergeObjs.size(); i++){
l.Add(mergeObjs[i]);
}
// use clone to return a new object
auto retHist = dynamic_cast<T*>((mergeObjs.front())->Clone());
if (retHist) retHist->Merge(&l);
return retHist;
}
} // end namespace ROOT
#endif
<|endoftext|> |
<commit_before>/***************************************************************************
main.cpp - description
-------------------
begin : Sun Jan 6 11:50:14 EET 2002
copyright : (C) 2002 by Tuukka Pasanen
email : illuusio@mailcity.com
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <qdatetime.h>
#include <stdlib.h>
#include <iostream>
#include "konsolekalendar.h"
#include "konsolekalendarepoch.h"
using namespace KCal;
using namespace std;
static const char *description = I18N_NOOP("KonsoleKalendar");
static KCmdLineOptions options[] =
{
{ "help", I18N_NOOP("Prints this help"), 0 },
{ "verbose", I18N_NOOP("Output helpful (?) debug info"), 0 },
{ "file <calendar-file>", I18N_NOOP("Specify which calendar you want to use."), 0 },
{ "import <import-file>", I18N_NOOP("Import this calendar to main calendar"), 0 },
{ "next", I18N_NOOP("Next activity in calendar"), 0 },
{ "date <date>", I18N_NOOP("Show selected day's calendar"), 0 },
{ "time <time>", I18N_NOOP("Show selected time at calendar"), 0 },
{ "start-date <start-date>", I18N_NOOP("Start from this day"), 0 },
{ "start-time <start-time>", I18N_NOOP("Start from this time [mm:hh]"), 0 },
{ "end-date <end-date>", I18N_NOOP("End to this day"), 0 },
{ "end-time <end-time>", I18N_NOOP("End to this time [mm:hh]"), 0 },
{ "epoch-end <epoch-time>", I18N_NOOP("End time in epoch format"), 0 },
{ "epoch-start <epoch-time>", I18N_NOOP("Start time in epoch format"), 0 },
{ "description <description>", I18N_NOOP("Add description to event (works with add and change)"), 0 },
{ "summary <summary>", I18N_NOOP("Add description to event (works with add and change)"), 0 },
{ "all", I18N_NOOP("Show all entries"), 0 },
{ "create", I18N_NOOP("if calendar not available new caledar file"), 0 },
{ "add", I18N_NOOP("Add an event"), 0 },
{ "change", I18N_NOOP("Delete an event (currently not implemented)"), 0 },
{ "delete", I18N_NOOP("Delete an event (currently not implemented)"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "konsolekalendar", I18N_NOOP( "KonsoleKalendar" ),
"0.6", description, KAboutData::License_GPL,
"(c) 2002-2003, Tuukka Pasanen", 0, 0,
"illuusio@mailcity.com");
aboutData.addAuthor("Tuukka Pasanen",0, "illuusio@mailcity.com");
aboutData.addAuthor("Allen D. Winter", 0, "winterz@earthlink.net");
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
QString KalendarFile;
QDate startdate = QDate::currentDate();
QTime starttime(7,0);
QDate enddate = QDate::currentDate();
QTime endtime(17,0);
QDate date = QDate::currentDate();
QTime time = QTime::currentTime();
bool view = true;
bool add = false;
bool change = false;
bool del = false;
bool create = false;
bool calendarFile = false;
bool importFile = false;
QString option;
KApplication app( false, false );
KonsoleKalendarVariables variables;
if ( args->isSet("verbose") ) {
variables.setVerbose(true);
}
/*
* Switch on adding
*
*/
if ( args->isSet("add") ) {
view=false;
add=true;
if(variables.isVerbose()) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Add event" << endl;
}
}
/*
* Switch on Create
*
*/
if ( args->isSet("create") ) {
create=true;
if(variables.isVerbose()) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Create event" << endl;
}
}
/*
* Switch on Change
*
*/
if ( args->isSet("change") ) {
view=false;
add=false;
change=true;
if(variables.isVerbose()) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Change event" << endl;
}
}
/*
* Switch on deleting
*
*/
if ( args->isSet("delete") ) {
view=false;
add=false;
change=false;
del=true;
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Delete event" << endl;
}
}
/*
* If there is summary attached.
*
*/
if ( args->isSet("summary") ) {
option = args->getOption("summary");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Summary: (" << option << ")" << endl;
}
variables.setSummary(option);
//variables.setDate(date);
}
/*
* If there is description attached.
*
*/
if ( args->isSet("description") ) {
option = args->getOption("description");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Description: (" << option << ")" << endl;
}
variables.setDescription(option);
//variables.setDate(date);
}
/*
* Show next happening and exit
*
*/
if ( args->isSet("epoch-start") )
{
option = args->getOption("epoch-start");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Show next happening in calendar and exit" << endl;
}
// KonsoleKalendarEpoch::epoch2QDateTime( option );
//variables.setNext(true);
}
/*
* Show next happening and exit
*
*/
if ( args->isSet("next") )
{
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Show next happening in calendar and exit" << endl;
}
variables.setNext(true);
}
/*
* If we like to see some date
*
*/
if ( args->isSet("date") )
{
option = args->getOption("date");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Show date info and exit: (" << option << ")" << endl;
}
date = variables.parseDate(option);
//variables.setDate(date);
}
/*
* If we like to see some time
*
*/
if ( args->isSet("time") ) {
option = args->getOption("time");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Show date info and exit: (" << option << ")" << endl;
}
time = variables.parseTime(option);
//variables.setDate(date);
}
/*
* Set starting date for calendar
*
*/
if ( args->isSet("start-date") ) {
option = args->getOption("start-date");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Start date: (" << option << ")" << endl;
}
startdate = variables.parseDate(option);
//variables.setStartDate(date);
}
/*
* Set starting time
*
*/
if ( args->isSet("start-time") ) {
option = args->getOption("start-time");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Start time: (" << option << ")" << endl;
}
starttime = variables.parseTime(option);
//variables.setStartDate(date);
}
/*
* Set end date for calendar
*
*/
if ( args->isSet("end-date") ) {
QString option = args->getOption("end-date");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | End date: (" << option << ")" << endl;
}
enddate = variables.parseDate(option);
//variables.setEndDate(date);
}
/*
* Set ending time
*
*/
if ( args->isSet("end-time") ) {
option = args->getOption("start-time");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | End time: (" << option << ")" << endl;
}
endtime = variables.parseTime(option);
// variables.setStartDate(date);
}
if( args->isSet("all") ) {
variables.setAll( true );
} else {
variables.setAll( false );
} // else
if ( args->isSet("import") ) {
importFile = true;
option = args->getOption("import");
variables.setImportFile( option );
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | importing file from: (" << option << ")" << endl;
} // if verbose
} // if
if ( args->isSet("file") ) {
calendarFile = true;
option = args->getOption("file");
variables.setCalendarFile( option );
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | using calendar at: (" << variables.getCalendarFile() << ")" << endl;
} // if verbose
} else {
KConfig cfg( locate( "config", "korganizerrc" ) );
cfg.setGroup("General");
KURL url( cfg.readPathEntry("Active Calendar") );
if ( url.isLocalFile() )
{
KalendarFile = url.path();
variables.setCalendarFile(KalendarFile);
if( variables.isVerbose() ) {
cout << "main.cpp::int main(int argc, char *argv[]) | Calendar file currently is " << variables.getCalendarFile().local8Bit() << endl;
} // if verbose
} else {
cout << i18n("Remote files are not supported yet.").local8Bit() << endl;
} // else
} // else
args->clear(); // Free up some memory.
QDateTime startdatetime(startdate, starttime);
QDateTime enddatetime(enddate, endtime);
QDateTime datetime( date, time );
variables.setStartDate( startdatetime );
variables.setEndDate( enddatetime );
variables.setDate( datetime );
KonsoleKalendar *konsolekalendar = new KonsoleKalendar(variables);
if( calendarFile && create ) {
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | create file" << endl;
}
konsolekalendar->createCalendar();
} // if
/*
* Opens calendar file so we can use it;)
* Because at this point we don't know what well
* Do with it..
*
* Adds it to konsolekalendarvariables also..
*/
if( konsolekalendar->openCalendar() ) {
if( importFile ) {
konsolekalendar->importCalendar();
}
if( add ) {
konsolekalendar->addEvent();
}
if( view ) {
konsolekalendar->showInstance();
}
konsolekalendar->closeCalendar();
}
delete konsolekalendar;
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | exiting" << endl;
}
return 0;
}
<commit_msg>Added deleting and changing. also Alan's epoch patch is applied (Now one can search with epoch)<commit_after>/***************************************************************************
main.cpp - description
-------------------
begin : Sun Jan 6 11:50:14 EET 2002
copyright : (C) 2002 by Tuukka Pasanen
email : illuusio@mailcity.com
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <qdatetime.h>
#include <stdlib.h>
#include <iostream>
#include "konsolekalendar.h"
#include "konsolekalendarepoch.h"
using namespace KCal;
using namespace std;
static const char *description = I18N_NOOP("KonsoleKalendar");
static KCmdLineOptions options[] =
{
{ "help", I18N_NOOP("Prints this help"), 0 },
{ "verbose", I18N_NOOP("Output helpful (?) debug info"), 0 },
{ "file <calendar-file>", I18N_NOOP("Specify which calendar you want to use."), 0 },
{ "import <import-file>", I18N_NOOP("Import this calendar to main calendar"), 0 },
{ "export-type <export-type>", I18N_NOOP("Export as.. "), 0 },
{ "export-file <export-file>", I18N_NOOP("Export to file (Dedault: stdout)"), 0 },
{ "export-types", I18N_NOOP("What export types supported"), 0 },
{ "next", I18N_NOOP("Next activity in calendar"), 0 },
{ "date <date>", I18N_NOOP("Show selected day's calendar"), 0 },
{ "time <time>", I18N_NOOP("Show selected time at calendar"), 0 },
{ "start-date <start-date>", I18N_NOOP("Start from this day"), 0 },
{ "start-time <start-time>", I18N_NOOP("Start from this time [mm:hh]"), 0 },
{ "end-date <end-date>", I18N_NOOP("End to this day"), 0 },
{ "end-time <end-time>", I18N_NOOP("End to this time [mm:hh]"), 0 },
{ "epoch-start <epoch-time>", I18N_NOOP("Start from this time [epoch format]"), 0 },
{ "epoch-end <epoch-time>", I18N_NOOP("End to this time [epoch format]"), 0 },
{ "description <description>", I18N_NOOP("Add description to event (works with add and change)"), 0 },
{ "summary <summary>", I18N_NOOP("Add description to event (works with add and change)"), 0 },
{ "all", I18N_NOOP("Show all entries"), 0 },
{ "create", I18N_NOOP("if calendar not available new caledar file"), 0 },
{ "add", I18N_NOOP("Add an event"), 0 },
{ "change", I18N_NOOP("Change an event (currently not implemented)"), 0 },
{ "delete", I18N_NOOP("Delete an event (currently not implemented)"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "konsolekalendar", I18N_NOOP( "KonsoleKalendar" ),
"0.6", description, KAboutData::License_GPL,
"(c) 2002-2003, Tuukka Pasanen", 0, 0,
"illuusio@mailcity.com");
aboutData.addAuthor("Tuukka Pasanen",0, "illuusio@mailcity.com");
aboutData.addAuthor("Allen Winter", 0, "winterz@earthlink.net");
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
QString KalendarFile;
// Default values (Now!) for which date and time to show
QDate date = QDate::currentDate();
QTime time = QTime::currentTime();
// Default values for start (today at 0700) and end (today at 1700) timestamps
QDate startdate = QDate::currentDate();
QTime starttime(7,0);
QDate enddate = QDate::currentDate();
QTime endtime(17,0);
// Default values for switches
bool view = true;
bool add = false;
bool change = false;
bool del = false;
bool create = false;
bool calendarFile = false;
bool importFile = false;
QString option;
KApplication app( false, false );
KonsoleKalendarVariables variables;
KonsoleKalendarEpoch epochs;
if ( args->isSet("verbose") ) {
variables.setVerbose(true);
}
/*
* Switch on adding
*
*/
if ( args->isSet("add") ) {
view=false;
add=true;
if(variables.isVerbose()) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Add event" << endl;
}
}
/*
* Switch on Create
*
*/
if ( args->isSet("create") ) {
create=true;
if(variables.isVerbose()) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Create event" << endl;
}
}
/*
* Switch on Change
*
*/
if ( args->isSet("change") ) {
view=false;
add=false;
change=true;
if(variables.isVerbose()) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Change event" << endl;
}
}
/*
* Switch on Delete
*
*/
if ( args->isSet("delete") ) {
view=false;
add=false;
change=false;
del=true;
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Delete event" << endl;
}
}
/*
* If there is summary attached.
*
*/
if ( args->isSet("summary") ) {
option = args->getOption("summary");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Summary: (" << option << ")" << endl;
}
variables.setSummary(option);
//variables.setDate(date);
}
/*
* If there is description attached.
*
*/
if ( args->isSet("description") ) {
option = args->getOption("description");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Description: (" << option << ")" << endl;
}
variables.setDescription(option);
//variables.setDate(date);
}
/*
* Show next happening and exit
*
*/
if ( args->isSet("next") )
{
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Show next happening in calendar and exit" << endl;
}
variables.setNext(true);
}
/*
* If we like to see some date
*
*/
if ( args->isSet("date") )
{
option = args->getOption("date");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Show date info and exit: (" << option << ")" << endl;
}
date = variables.parseDate(option);
//variables.setDate(date);
}
/*
* If we like to see some time
*
*/
if ( args->isSet("time") ) {
option = args->getOption("time");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Show date info and exit: (" << option << ")" << endl;
}
time = variables.parseTime(option);
//variables.setDate(date);
}
/*
* Set starting date for calendar
*
*/
if ( args->isSet("start-date") ) {
option = args->getOption("start-date");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Start date: (" << option << ")" << endl;
}
startdate = variables.parseDate(option);
//variables.setStartDate(date);
}
/*
* Set starting time
*
*/
if ( args->isSet("start-time") ) {
option = args->getOption("start-time");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Start time: (" << option << ")" << endl;
}
starttime = variables.parseTime(option);
//variables.setStartDate(date);
}
/*
* Set end date for calendar
*
*/
if ( args->isSet("end-date") ) {
QString option = args->getOption("end-date");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | End date: (" << option << ")" << endl;
}
enddate = variables.parseDate(option);
//variables.setEndDate(date);
}
/*
* Set ending time
*
*/
if ( args->isSet("end-time") ) {
option = args->getOption("end-time");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | End time: (" << option << ")" << endl;
}
endtime = variables.parseTime(option);
// variables.setStartDate(date);
}
/*
* Set start date/time from epoch
*
*/
time_t epochstart=0;
if ( args->isSet("epoch-start") ) {
option = args->getOption("epoch-start");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Epoch start: (" << option << ")" << endl;
}
epochstart = (time_t) option.toULong(0,10);
}
/*
* Set end date/time from epoch
*
*/
time_t epochend=0;
if ( args->isSet("epoch-end") ) {
option = args->getOption("epoch-end");
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | Epoch end: (" << option << ")" << endl;
}
epochend = (time_t) option.toULong(0,10);
}
if( args->isSet("all") ) {
variables.setAll( true );
} else {
variables.setAll( false );
} // else
if ( args->isSet("import") ) {
importFile = true;
option = args->getOption("import");
variables.setImportFile( option );
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | importing file from: (" << option << ")" << endl;
} // if verbose
} // if
if ( args->isSet("file") ) {
calendarFile = true;
option = args->getOption("file");
variables.setCalendarFile( option );
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | using calendar at: (" << variables.getCalendarFile() << ")" << endl;
} // if verbose
} else {
KConfig cfg( locate( "config", "korganizerrc" ) );
cfg.setGroup("General");
KURL url( cfg.readPathEntry("Active Calendar") );
if ( url.isLocalFile() )
{
KalendarFile = url.path();
variables.setCalendarFile(KalendarFile);
if( variables.isVerbose() ) {
cout << "main.cpp::int main(int argc, char *argv[]) | Calendar file currently is " << variables.getCalendarFile().local8Bit() << endl;
} // if verbose
} else {
cout << i18n("Remote files are not supported yet.").local8Bit() << endl;
} // else
} // else
QDateTime startdatetime, enddatetime;
if ( args->isSet("epoch-start") ) {
startdatetime = epochs.epoch2QDateTime(epochstart);
} else {
startdatetime = QDateTime::QDateTime(startdate, starttime);
}
if ( args->isSet("epoch-end") ) {
enddatetime = epochs.epoch2QDateTime(epochend);
} else {
enddatetime = QDateTime::QDateTime(enddate, endtime);
}
QDateTime datetime( date, time );
variables.setStartDate( startdatetime );
variables.setEndDate( enddatetime );
variables.setDate( datetime );
if ( variables.isVerbose() ) {
// Tuukka, please fix so --verbose makes kdDebug print something.
kdDebug() << "DateTime=" << datetime.toString(Qt::TextDate) << endl;
kdDebug() << "StartDate=" << startdatetime.toString(Qt::TextDate) << endl;
kdDebug() << "EndDate=" << enddatetime.toString(Qt::TextDate) << endl;
} // if
args->clear(); // Free up some memory.
KonsoleKalendar *konsolekalendar = new KonsoleKalendar(variables);
if( calendarFile && create ) {
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | create file" << endl;
}
konsolekalendar->createCalendar();
} // if
/*
* Opens calendar file so we can use it;)
* Because at this point we don't know what we'll
* Do with it..
*
* Adds it to konsolekalendarvariables also..
*/
if( konsolekalendar->openCalendar() ) {
if( importFile ) {
konsolekalendar->importCalendar();
}
if( add ) {
konsolekalendar->addEvent();
}
if( change ) {
konsolekalendar->changeEvent();
}
if( del ) {
konsolekalendar->deleteEvent();
}
if( view ) {
konsolekalendar->showInstance();
}
konsolekalendar->closeCalendar();
}
delete konsolekalendar;
if( variables.isVerbose() ) {
kdDebug() << "main.cpp::int main(int argc, char *argv[]) | exiting" << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* listCat.cc KPilot
**
** Copyright (C) 2000-2001 by Adriaan de Groot
**
** This file defines a specialization of KListView that can
** be used to sort some fixed set of object into some fixed
** set of categories.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *listCat_id =
"$Id$";
#include "options.h"
#include <klocale.h>
#include "listCat.moc"
ListCategorizer::ListCategorizer(QWidget * parent,
const char *name) :
KListView(parent, name),
fStartOpen(false)
{
FUNCTIONSETUP;
setupWidget();
(void) listCat_id;
}
ListCategorizer::ListCategorizer(const QStringList & i,
bool startOpen,
QWidget * parent,
const char *name) :
KListView(parent, name),
fStartOpen(startOpen)
{
FUNCTIONSETUP;
addCategories(i);
}
void ListCategorizer::addCategories(const QStringList & l)
{
FUNCTIONSETUP;
QStringList::ConstIterator i;
for (i = l.begin(); i != l.end(); ++i)
{
(void) addCategory(*i);
}
}
QListViewItem *ListCategorizer::addCategory(const QString & name,
const QString & desc)
{
FUNCTIONSETUP;
QListViewItem *m = new QListViewItem(this, name, desc);
m->setSelectable(false);
m->setOpen(fStartOpen);
return m;
}
void ListCategorizer::setupWidget()
{
FUNCTIONSETUP;
addColumn(i18n("Category"));
addColumn(i18n("Description"));
setItemsMovable(false);
setDragEnabled(true);
setAcceptDrops(true);
setDropVisualizer(true);
setRootIsDecorated(true);
}
/* virtual */ bool ListCategorizer::acceptDrag(QDropEvent * event) const
{
FUNCTIONSETUP;
if (!(event->source()))
return false;
QListViewItem *p = itemAt(event->pos());
if (!p)
return false;
return true;
}
/* virtual */ void ListCategorizer::contentsDropEvent(QDropEvent * e)
{
FUNCTIONSETUP;
cleanDropVisualizer();
if (!acceptDrag(e))
return;
e->accept();
QListViewItem *p = itemAt(e->pos());
QListViewItem *selection = currentItem();
if (!p)
{
kdWarning() << "Drop without a category!" << endl;
return;
}
QListViewItem *category = p->parent();
if (!category)
{
category = p;
}
moveItem(selection, category, 0L);
}
/* virtual */ void ListCategorizer::startDrag()
{
FUNCTIONSETUP;
QListViewItem *p = currentItem();
if (!p || !p->parent())
return;
KListView::startDrag();
}
QStringList ListCategorizer::listSiblings(const QListViewItem * p, int column) const
{
FUNCTIONSETUP;
QStringList l;
while (p)
{
l.append(p->text(column));
p = p->nextSibling();
}
return l;
}
QListViewItem *ListCategorizer::findCategory(const QString & category) const
{
FUNCTIONSETUP;
QListViewItem *p = firstChild();
while (p)
{
if (p->text(0) == category)
return p;
p = p->nextSibling();
}
return 0L;
}
QListViewItem *ListCategorizer::addItem(const QString & category,
const QString & name, const QString & description)
{
FUNCTIONSETUP;
QListViewItem *p = findCategory(category);
if (!p)
return 0L;
return new QListViewItem(p, name, description);
}
#define RVPAD (4)
RichListViewItem::RichListViewItem(QListViewItem *p,
QString l,
int c) :
QListViewItem(p,l)
{
FUNCTIONSETUP;
fColumns=c;
fIsRich = new bool[c];
fRect = new QRect[c];
for (int i=0; i<c; i++)
{
fIsRich[i]=false;
}
}
RichListViewItem::~RichListViewItem()
{
FUNCTIONSETUP;
delete[] fIsRich;
delete[] fRect;
}
void RichListViewItem::computeHeight(int c)
{
FUNCTIONSETUP;
if (!fIsRich[c]) return;
QListView *v = listView();
fRect[c] = v->fontMetrics().boundingRect(v->itemMargin()+RVPAD,0+RVPAD,
v->columnWidth(c)-v->itemMargin()-RVPAD,300,
AlignLeft | AlignTop | WordBreak,
text(c));
}
/* virtual */ void RichListViewItem::setup()
{
FUNCTIONSETUP;
QListViewItem::setup();
QListView *v = listView();
int h = height();
for (int i=0; i<fColumns; i++)
{
computeHeight(i);
h = QMAX(h,fRect[i].height()+2*RVPAD);
}
setHeight(h);
}
/* virtual */ void RichListViewItem::paintCell(QPainter *p,
const QColorGroup &gc,
int column,
int width,
int alignment)
{
FUNCTIONSETUP;
if ((!column) || (!fIsRich[column]))
{
QListViewItem::paintCell(p,gc,column,width,alignment);
return;
}
QListView *v = listView();
p->eraseRect(0,0,width,height());
p->setBackgroundColor(gc.background());
p->eraseRect(RVPAD,RVPAD,width-RVPAD,height()-RVPAD);
p->setPen(gc.text());
p->drawText(v->itemMargin()+RVPAD,0+RVPAD,
width-v->itemMargin()-RVPAD,height()-RVPAD,
AlignTop | AlignLeft | WordBreak,
text(column),
-1,
&fRect[column]);
}
// $Log$
// Revision 1.6 2001/09/30 19:51:56 adridg
// Some last-minute layout, compile, and __FUNCTION__ (for Tru64) changes.
//
// Revision 1.5 2001/09/29 16:26:18 adridg
// The big layout change
//
// Revision 1.4 2001/03/09 09:46:15 adridg
// Large-scale #include cleanup
//
// Revision 1.3 2001/02/24 14:08:13 adridg
// Massive code cleanup, split KPilotLink
//
// Revision 1.2 2001/02/05 20:58:48 adridg
// Fixed copyright headers for source releases. No code changed
//
<commit_msg>compile with KDE3<commit_after>/* listCat.cc KPilot
**
** Copyright (C) 2000-2001 by Adriaan de Groot
**
** This file defines a specialization of KListView that can
** be used to sort some fixed set of object into some fixed
** set of categories.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *listCat_id =
"$Id$";
#include "options.h"
#include <qpainter.h>
#include <klocale.h>
#include "listCat.moc"
ListCategorizer::ListCategorizer(QWidget * parent,
const char *name) :
KListView(parent, name),
fStartOpen(false)
{
FUNCTIONSETUP;
setupWidget();
(void) listCat_id;
}
ListCategorizer::ListCategorizer(const QStringList & i,
bool startOpen,
QWidget * parent,
const char *name) :
KListView(parent, name),
fStartOpen(startOpen)
{
FUNCTIONSETUP;
addCategories(i);
}
void ListCategorizer::addCategories(const QStringList & l)
{
FUNCTIONSETUP;
QStringList::ConstIterator i;
for (i = l.begin(); i != l.end(); ++i)
{
(void) addCategory(*i);
}
}
QListViewItem *ListCategorizer::addCategory(const QString & name,
const QString & desc)
{
FUNCTIONSETUP;
QListViewItem *m = new QListViewItem(this, name, desc);
m->setSelectable(false);
m->setOpen(fStartOpen);
return m;
}
void ListCategorizer::setupWidget()
{
FUNCTIONSETUP;
addColumn(i18n("Category"));
addColumn(i18n("Description"));
setItemsMovable(false);
setDragEnabled(true);
setAcceptDrops(true);
setDropVisualizer(true);
setRootIsDecorated(true);
}
/* virtual */ bool ListCategorizer::acceptDrag(QDropEvent * event) const
{
FUNCTIONSETUP;
if (!(event->source()))
return false;
QListViewItem *p = itemAt(event->pos());
if (!p)
return false;
return true;
}
/* virtual */ void ListCategorizer::contentsDropEvent(QDropEvent * e)
{
FUNCTIONSETUP;
cleanDropVisualizer();
if (!acceptDrag(e))
return;
e->accept();
QListViewItem *p = itemAt(e->pos());
QListViewItem *selection = currentItem();
if (!p)
{
kdWarning() << "Drop without a category!" << endl;
return;
}
QListViewItem *category = p->parent();
if (!category)
{
category = p;
}
moveItem(selection, category, 0L);
}
/* virtual */ void ListCategorizer::startDrag()
{
FUNCTIONSETUP;
QListViewItem *p = currentItem();
if (!p || !p->parent())
return;
KListView::startDrag();
}
QStringList ListCategorizer::listSiblings(const QListViewItem * p, int column) const
{
FUNCTIONSETUP;
QStringList l;
while (p)
{
l.append(p->text(column));
p = p->nextSibling();
}
return l;
}
QListViewItem *ListCategorizer::findCategory(const QString & category) const
{
FUNCTIONSETUP;
QListViewItem *p = firstChild();
while (p)
{
if (p->text(0) == category)
return p;
p = p->nextSibling();
}
return 0L;
}
QListViewItem *ListCategorizer::addItem(const QString & category,
const QString & name, const QString & description)
{
FUNCTIONSETUP;
QListViewItem *p = findCategory(category);
if (!p)
return 0L;
return new QListViewItem(p, name, description);
}
#define RVPAD (4)
RichListViewItem::RichListViewItem(QListViewItem *p,
QString l,
int c) :
QListViewItem(p,l)
{
FUNCTIONSETUP;
fColumns=c;
fIsRich = new bool[c];
fRect = new QRect[c];
for (int i=0; i<c; i++)
{
fIsRich[i]=false;
}
}
RichListViewItem::~RichListViewItem()
{
FUNCTIONSETUP;
delete[] fIsRich;
delete[] fRect;
}
void RichListViewItem::computeHeight(int c)
{
FUNCTIONSETUP;
if (!fIsRich[c]) return;
QListView *v = listView();
fRect[c] = v->fontMetrics().boundingRect(v->itemMargin()+RVPAD,0+RVPAD,
v->columnWidth(c)-v->itemMargin()-RVPAD,300,
AlignLeft | AlignTop | WordBreak,
text(c));
}
/* virtual */ void RichListViewItem::setup()
{
FUNCTIONSETUP;
QListViewItem::setup();
QListView *v = listView();
int h = height();
for (int i=0; i<fColumns; i++)
{
computeHeight(i);
h = QMAX(h,fRect[i].height()+2*RVPAD);
}
setHeight(h);
}
/* virtual */ void RichListViewItem::paintCell(QPainter *p,
const QColorGroup &gc,
int column,
int width,
int alignment)
{
FUNCTIONSETUP;
if ((!column) || (!fIsRich[column]))
{
QListViewItem::paintCell(p,gc,column,width,alignment);
return;
}
QListView *v = listView();
p->eraseRect(0,0,width,height());
p->setBackgroundColor(gc.background());
p->eraseRect(RVPAD,RVPAD,width-RVPAD,height()-RVPAD);
p->setPen(gc.text());
p->drawText(v->itemMargin()+RVPAD,0+RVPAD,
width-v->itemMargin()-RVPAD,height()-RVPAD,
AlignTop | AlignLeft | WordBreak,
text(column),
-1,
&fRect[column]);
}
// $Log$
// Revision 1.7 2001/09/30 23:02:13 adridg
// Add support for multi-line comments in conduit configurator and add it to kpilotConfig
//
// Revision 1.6 2001/09/30 19:51:56 adridg
// Some last-minute layout, compile, and __FUNCTION__ (for Tru64) changes.
//
// Revision 1.5 2001/09/29 16:26:18 adridg
// The big layout change
//
// Revision 1.4 2001/03/09 09:46:15 adridg
// Large-scale #include cleanup
//
// Revision 1.3 2001/02/24 14:08:13 adridg
// Massive code cleanup, split KPilotLink
//
// Revision 1.2 2001/02/05 20:58:48 adridg
// Fixed copyright headers for source releases. No code changed
//
<|endoftext|> |
<commit_before>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str();
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.remove();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
if (proxyPath.exists())
{
Error error = proxyPath.remove();
if (error)
LOG_ERROR(error);
}
// write something to the file (to ensure it's created)
Error error = core::writeStringToFile(proxyPath, pidString());
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
return fileExistsError(ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
return error;
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<commit_msg>use 'removeIfExists()' to tolerate contention on file removal<commit_after>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str();
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
if (proxyPath.exists())
{
Error error = proxyPath.remove();
if (error)
LOG_ERROR(error);
}
// write something to the file (to ensure it's created)
Error error = core::writeStringToFile(proxyPath, pidString());
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
return fileExistsError(ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
return error;
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before>/*
Copyright 2012 David Robillard <http://drobilla.net>
Permission to use, copy, modify, and/or 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.
THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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.
*/
/**
@file pugl_win.cpp Windows/WGL Pugl Implementation.
*/
#include <windows.h>
#include <windowsx.h>
#include <GL/gl.h>
#include <stdio.h>
#include <stdlib.h>
#include "pugl_internal.h"
#ifndef WM_MOUSEWHEEL
# define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WM_MOUSEHWHEEL
# define WM_MOUSEHWHEEL 0x020E
#endif
#ifndef WHEEL_DELTA
# define WHEEL_DELTA 120
#endif
#define PUGL_LOCAL_CLOSE_MSG (WM_USER + 50)
struct PuglInternalsImpl {
HWND hwnd;
HDC hdc;
HGLRC hglrc;
WNDCLASS wc;
};
LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
PuglView*
puglInit()
{
PuglView* view = (PuglView*)calloc(1, sizeof(PuglView));
PuglInternals* impl = (PuglInternals*)calloc(1, sizeof(PuglInternals));
if (!view || !impl) {
return NULL;
}
view->impl = impl;
view->width = 640;
view->height = 480;
return view;
}
PuglView*
puglCreateInternals(PuglNativeWindow parent,
const char* title,
int width,
int height,
bool resizable,
bool visible)
{
PuglView* view = (PuglView*)calloc(1, sizeof(PuglView));
PuglInternals* impl = (PuglInternals*)calloc(1, sizeof(PuglInternals));
if (!view || !impl) {
return NULL;
}
view->impl = impl;
view->width = width;
view->height = height;
// FIXME: This is nasty, and pugl should not have static anything.
// Should class be a parameter? Does this make sense on other platforms?
static int wc_count = 0;
char classNameBuf[256];
_snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d\n", title, wc_count++);
impl->wc.style = CS_OWNDC;
impl->wc.lpfnWndProc = wndProc;
impl->wc.cbClsExtra = 0;
impl->wc.cbWndExtra = 0;
impl->wc.hInstance = 0;
impl->wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
impl->wc.hCursor = LoadCursor(NULL, IDC_ARROW);
impl->wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
impl->wc.lpszMenuName = NULL;
impl->wc.lpszClassName = classNameBuf;
RegisterClass(&impl->wc);
int winFlags = WS_POPUPWINDOW | WS_CAPTION;
if (resizable) {
winFlags |= WS_SIZEBOX;
}
// Adjust the overall window size to accomodate our requested client size
RECT wr = { 0, 0, width, height };
AdjustWindowRectEx(&wr, winFlags, FALSE, WS_EX_TOPMOST);
impl->hwnd = CreateWindowEx(
WS_EX_TOPMOST,
classNameBuf, title,
(visible ? WS_VISIBLE : 0) | (parent ? WS_CHILD : winFlags),
CW_USEDEFAULT, CW_USEDEFAULT, wr.right-wr.left, wr.bottom-wr.top,
(HWND)parent, NULL, NULL, NULL);
if (!impl->hwnd) {
free(impl);
free(view);
return NULL;
}
#ifdef _WIN64
SetWindowLongPtr(impl->hwnd, GWLP_USERDATA, (LONG_PTR)view);
#else
SetWindowLongPtr(impl->hwnd, GWL_USERDATA, (LONG)view);
#endif
impl->hdc = GetDC(impl->hwnd);
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
int format = ChoosePixelFormat(impl->hdc, &pfd);
SetPixelFormat(impl->hdc, format, &pfd);
impl->hglrc = wglCreateContext(impl->hdc);
wglMakeCurrent(impl->hdc, impl->hglrc);
view->width = width;
view->height = height;
return view;
}
void
puglDestroy(PuglView* view)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(view->impl->hglrc);
ReleaseDC(view->impl->hwnd, view->impl->hdc);
DestroyWindow(view->impl->hwnd);
UnregisterClass(view->impl->wc.lpszClassName, NULL);
free(view->impl);
free(view);
}
static void
puglReshape(PuglView* view, int width, int height)
{
wglMakeCurrent(view->impl->hdc, view->impl->hglrc);
if (view->reshapeFunc) {
view->reshapeFunc(view, width, height);
} else {
puglDefaultReshape(view, width, height);
}
view->width = width;
view->height = height;
}
static void
puglDisplay(PuglView* view)
{
wglMakeCurrent(view->impl->hdc, view->impl->hglrc);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
if (view->displayFunc) {
view->displayFunc(view);
}
glFlush();
SwapBuffers(view->impl->hdc);
view->redisplay = false;
}
static PuglKey
keySymToSpecial(int sym)
{
switch (sym) {
case VK_F1: return PUGL_KEY_F1;
case VK_F2: return PUGL_KEY_F2;
case VK_F3: return PUGL_KEY_F3;
case VK_F4: return PUGL_KEY_F4;
case VK_F5: return PUGL_KEY_F5;
case VK_F6: return PUGL_KEY_F6;
case VK_F7: return PUGL_KEY_F7;
case VK_F8: return PUGL_KEY_F8;
case VK_F9: return PUGL_KEY_F9;
case VK_F10: return PUGL_KEY_F10;
case VK_F11: return PUGL_KEY_F11;
case VK_F12: return PUGL_KEY_F12;
case VK_LEFT: return PUGL_KEY_LEFT;
case VK_UP: return PUGL_KEY_UP;
case VK_RIGHT: return PUGL_KEY_RIGHT;
case VK_DOWN: return PUGL_KEY_DOWN;
case VK_PRIOR: return PUGL_KEY_PAGE_UP;
case VK_NEXT: return PUGL_KEY_PAGE_DOWN;
case VK_HOME: return PUGL_KEY_HOME;
case VK_END: return PUGL_KEY_END;
case VK_INSERT: return PUGL_KEY_INSERT;
case VK_SHIFT: return PUGL_KEY_SHIFT;
case VK_CONTROL: return PUGL_KEY_CTRL;
case VK_MENU: return PUGL_KEY_ALT;
case VK_LWIN: return PUGL_KEY_SUPER;
case VK_RWIN: return PUGL_KEY_SUPER;
}
return (PuglKey)0;
}
static void
processMouseEvent(PuglView* view, int button, bool press, LPARAM lParam)
{
view->event_timestamp_ms = GetMessageTime();
if (press) {
SetCapture(view->impl->hwnd);
} else {
ReleaseCapture();
}
if (view->mouseFunc) {
view->mouseFunc(view, button, press,
GET_X_LPARAM(lParam),
GET_Y_LPARAM(lParam));
}
}
static void
setModifiers(PuglView* view)
{
view->mods = 0;
view->mods |= (GetKeyState(VK_SHIFT) < 0) ? PUGL_MOD_SHIFT : 0;
view->mods |= (GetKeyState(VK_CONTROL) < 0) ? PUGL_MOD_CTRL : 0;
view->mods |= (GetKeyState(VK_MENU) < 0) ? PUGL_MOD_ALT : 0;
view->mods |= (GetKeyState(VK_LWIN) < 0) ? PUGL_MOD_SUPER : 0;
view->mods |= (GetKeyState(VK_RWIN) < 0) ? PUGL_MOD_SUPER : 0;
}
static LRESULT
handleMessage(PuglView* view, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
PuglKey key;
setModifiers(view);
switch (message) {
case WM_CREATE:
case WM_SHOWWINDOW:
case WM_SIZE:
RECT rect;
GetClientRect(view->impl->hwnd, &rect);
puglReshape(view, rect.right, rect.bottom);
view->width = rect.right;
view->height = rect.bottom;
break;
case WM_PAINT:
BeginPaint(view->impl->hwnd, &ps);
puglDisplay(view);
EndPaint(view->impl->hwnd, &ps);
break;
case WM_MOUSEMOVE:
if (view->motionFunc) {
view->motionFunc(view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
break;
case WM_LBUTTONDOWN:
processMouseEvent(view, 1, true, lParam);
break;
case WM_MBUTTONDOWN:
processMouseEvent(view, 2, true, lParam);
break;
case WM_RBUTTONDOWN:
processMouseEvent(view, 3, true, lParam);
break;
case WM_LBUTTONUP:
processMouseEvent(view, 1, false, lParam);
break;
case WM_MBUTTONUP:
processMouseEvent(view, 2, false, lParam);
break;
case WM_RBUTTONUP:
processMouseEvent(view, 3, false, lParam);
break;
case WM_MOUSEWHEEL:
if (view->scrollFunc) {
view->event_timestamp_ms = GetMessageTime();
view->scrollFunc(
view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
0.0f, (int16_t)HIWORD(wParam) / (float)WHEEL_DELTA);
}
break;
case WM_MOUSEHWHEEL:
if (view->scrollFunc) {
view->event_timestamp_ms = GetMessageTime();
view->scrollFunc(
view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
(int16_t)HIWORD(wParam) / float(WHEEL_DELTA), 0.0f);
}
break;
case WM_KEYDOWN:
if (view->ignoreKeyRepeat && (lParam & (1 << 30))) {
break;
} // else nobreak
case WM_KEYUP:
view->event_timestamp_ms = GetMessageTime();
if ((key = keySymToSpecial(wParam))) {
if (view->specialFunc) {
view->specialFunc(view, message == WM_KEYDOWN, key);
}
} else if (view->keyboardFunc) {
view->keyboardFunc(view, message == WM_KEYDOWN, wParam);
}
break;
case WM_QUIT:
case PUGL_LOCAL_CLOSE_MSG:
if (view->closeFunc) {
view->closeFunc(view);
}
break;
default:
return DefWindowProc(
view->impl->hwnd, message, wParam, lParam);
}
return 0;
}
PuglStatus
puglProcessEvents(PuglView* view)
{
MSG msg;
while (PeekMessage(&msg, view->impl->hwnd, 0, 0, PM_REMOVE)) {
handleMessage(view, msg.message, msg.wParam, msg.lParam);
}
if (view->redisplay) {
InvalidateRect(view->impl->hwnd, NULL, FALSE);
}
return PUGL_SUCCESS;
}
LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
#ifdef _WIN64
PuglView* view = (PuglView*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
#else
PuglView* view = (PuglView*)GetWindowLongPtr(hwnd, GWL_USERDATA);
#endif
switch (message) {
case WM_CREATE:
PostMessage(hwnd, WM_SHOWWINDOW, TRUE, 0);
return 0;
case WM_CLOSE:
PostMessage(hwnd, PUGL_LOCAL_CLOSE_MSG, wParam, lParam);
return 0;
case WM_DESTROY:
return 0;
default:
if (view) {
return handleMessage(view, message, wParam, lParam);
} else {
return DefWindowProc(hwnd, message, wParam, lParam);
}
}
}
void
puglPostRedisplay(PuglView* view)
{
view->redisplay = true;
}
PuglNativeWindow
puglGetNativeWindow(PuglView* view)
{
return (PuglNativeWindow)view->impl->hwnd;
}
<commit_msg>Fix compilation on Windows. Maybe.<commit_after>/*
Copyright 2012 David Robillard <http://drobilla.net>
Permission to use, copy, modify, and/or 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.
THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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.
*/
/**
@file pugl_win.cpp Windows/WGL Pugl Implementation.
*/
#include <windows.h>
#include <windowsx.h>
#include <GL/gl.h>
#include <stdio.h>
#include <stdlib.h>
#include "pugl_internal.h"
#ifndef WM_MOUSEWHEEL
# define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WM_MOUSEHWHEEL
# define WM_MOUSEHWHEEL 0x020E
#endif
#ifndef WHEEL_DELTA
# define WHEEL_DELTA 120
#endif
#define PUGL_LOCAL_CLOSE_MSG (WM_USER + 50)
struct PuglInternalsImpl {
HWND hwnd;
HDC hdc;
HGLRC hglrc;
WNDCLASS wc;
};
LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
PuglView*
puglInit()
{
PuglView* view = (PuglView*)calloc(1, sizeof(PuglView));
PuglInternals* impl = (PuglInternals*)calloc(1, sizeof(PuglInternals));
if (!view || !impl) {
return NULL;
}
view->impl = impl;
view->width = 640;
view->height = 480;
return view;
}
PuglInternals*
puglInitInternals()
{
return (PuglInternals*)calloc(1, sizeof(PuglInternals));
}
int
puglCreateWindow(PuglView* view, const char* title)
{
PuglInternals* impl = view->impl;
if (!title) {
title = "Window";
}
// FIXME: This is nasty, and pugl should not have static anything.
// Should class be a parameter? Does this make sense on other platforms?
static int wc_count = 0;
char classNameBuf[256];
_snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d\n", title, wc_count++);
impl->wc.style = CS_OWNDC;
impl->wc.lpfnWndProc = wndProc;
impl->wc.cbClsExtra = 0;
impl->wc.cbWndExtra = 0;
impl->wc.hInstance = 0;
impl->wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
impl->wc.hCursor = LoadCursor(NULL, IDC_ARROW);
impl->wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
impl->wc.lpszMenuName = NULL;
impl->wc.lpszClassName = classNameBuf;
RegisterClass(&impl->wc);
int winFlags = WS_POPUPWINDOW | WS_CAPTION;
if (view->resizable) {
winFlags |= WS_SIZEBOX;
}
// Adjust the overall window size to accomodate our requested client size
RECT wr = { 0, 0, view->width, view->height };
AdjustWindowRectEx(&wr, winFlags, FALSE, WS_EX_TOPMOST);
impl->hwnd = CreateWindowEx(
WS_EX_TOPMOST,
classNameBuf, title,
(view->parent ? WS_CHILD : winFlags),
CW_USEDEFAULT, CW_USEDEFAULT, wr.right-wr.left, wr.bottom-wr.top,
(HWND)view->parent, NULL, NULL, NULL);
if (!impl->hwnd) {
free(impl);
free(view);
return 1;
}
#ifdef _WIN64
SetWindowLongPtr(impl->hwnd, GWLP_USERDATA, (LONG_PTR)view);
#else
SetWindowLongPtr(impl->hwnd, GWL_USERDATA, (LONG)view);
#endif
impl->hdc = GetDC(impl->hwnd);
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
int format = ChoosePixelFormat(impl->hdc, &pfd);
SetPixelFormat(impl->hdc, format, &pfd);
impl->hglrc = wglCreateContext(impl->hdc);
wglMakeCurrent(impl->hdc, impl->hglrc);
return 0;
}
void
puglShowWindow(PuglView* view)
{
PuglInternals* impl = view->impl;
ShowWindow(impl->hwnd, SW_SHOWNORMAL);
}
void
puglHideWindow(PuglView* view)
{
PuglInternals* impl = view->impl;
ShowWindow(impl->hwnd, SW_HIDE);
}
void
puglDestroy(PuglView* view)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(view->impl->hglrc);
ReleaseDC(view->impl->hwnd, view->impl->hdc);
DestroyWindow(view->impl->hwnd);
UnregisterClass(view->impl->wc.lpszClassName, NULL);
free(view->impl);
free(view);
}
static void
puglReshape(PuglView* view, int width, int height)
{
wglMakeCurrent(view->impl->hdc, view->impl->hglrc);
if (view->reshapeFunc) {
view->reshapeFunc(view, width, height);
} else {
puglDefaultReshape(view, width, height);
}
view->width = width;
view->height = height;
}
static void
puglDisplay(PuglView* view)
{
wglMakeCurrent(view->impl->hdc, view->impl->hglrc);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
if (view->displayFunc) {
view->displayFunc(view);
}
glFlush();
SwapBuffers(view->impl->hdc);
view->redisplay = false;
}
static PuglKey
keySymToSpecial(int sym)
{
switch (sym) {
case VK_F1: return PUGL_KEY_F1;
case VK_F2: return PUGL_KEY_F2;
case VK_F3: return PUGL_KEY_F3;
case VK_F4: return PUGL_KEY_F4;
case VK_F5: return PUGL_KEY_F5;
case VK_F6: return PUGL_KEY_F6;
case VK_F7: return PUGL_KEY_F7;
case VK_F8: return PUGL_KEY_F8;
case VK_F9: return PUGL_KEY_F9;
case VK_F10: return PUGL_KEY_F10;
case VK_F11: return PUGL_KEY_F11;
case VK_F12: return PUGL_KEY_F12;
case VK_LEFT: return PUGL_KEY_LEFT;
case VK_UP: return PUGL_KEY_UP;
case VK_RIGHT: return PUGL_KEY_RIGHT;
case VK_DOWN: return PUGL_KEY_DOWN;
case VK_PRIOR: return PUGL_KEY_PAGE_UP;
case VK_NEXT: return PUGL_KEY_PAGE_DOWN;
case VK_HOME: return PUGL_KEY_HOME;
case VK_END: return PUGL_KEY_END;
case VK_INSERT: return PUGL_KEY_INSERT;
case VK_SHIFT: return PUGL_KEY_SHIFT;
case VK_CONTROL: return PUGL_KEY_CTRL;
case VK_MENU: return PUGL_KEY_ALT;
case VK_LWIN: return PUGL_KEY_SUPER;
case VK_RWIN: return PUGL_KEY_SUPER;
}
return (PuglKey)0;
}
static void
processMouseEvent(PuglView* view, int button, bool press, LPARAM lParam)
{
view->event_timestamp_ms = GetMessageTime();
if (press) {
SetCapture(view->impl->hwnd);
} else {
ReleaseCapture();
}
if (view->mouseFunc) {
view->mouseFunc(view, button, press,
GET_X_LPARAM(lParam),
GET_Y_LPARAM(lParam));
}
}
static void
setModifiers(PuglView* view)
{
view->mods = 0;
view->mods |= (GetKeyState(VK_SHIFT) < 0) ? PUGL_MOD_SHIFT : 0;
view->mods |= (GetKeyState(VK_CONTROL) < 0) ? PUGL_MOD_CTRL : 0;
view->mods |= (GetKeyState(VK_MENU) < 0) ? PUGL_MOD_ALT : 0;
view->mods |= (GetKeyState(VK_LWIN) < 0) ? PUGL_MOD_SUPER : 0;
view->mods |= (GetKeyState(VK_RWIN) < 0) ? PUGL_MOD_SUPER : 0;
}
static LRESULT
handleMessage(PuglView* view, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
PuglKey key;
setModifiers(view);
switch (message) {
case WM_CREATE:
case WM_SHOWWINDOW:
case WM_SIZE:
RECT rect;
GetClientRect(view->impl->hwnd, &rect);
puglReshape(view, rect.right, rect.bottom);
view->width = rect.right;
view->height = rect.bottom;
break;
case WM_PAINT:
BeginPaint(view->impl->hwnd, &ps);
puglDisplay(view);
EndPaint(view->impl->hwnd, &ps);
break;
case WM_MOUSEMOVE:
if (view->motionFunc) {
view->motionFunc(view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
break;
case WM_LBUTTONDOWN:
processMouseEvent(view, 1, true, lParam);
break;
case WM_MBUTTONDOWN:
processMouseEvent(view, 2, true, lParam);
break;
case WM_RBUTTONDOWN:
processMouseEvent(view, 3, true, lParam);
break;
case WM_LBUTTONUP:
processMouseEvent(view, 1, false, lParam);
break;
case WM_MBUTTONUP:
processMouseEvent(view, 2, false, lParam);
break;
case WM_RBUTTONUP:
processMouseEvent(view, 3, false, lParam);
break;
case WM_MOUSEWHEEL:
if (view->scrollFunc) {
view->event_timestamp_ms = GetMessageTime();
view->scrollFunc(
view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
0.0f, (int16_t)HIWORD(wParam) / (float)WHEEL_DELTA);
}
break;
case WM_MOUSEHWHEEL:
if (view->scrollFunc) {
view->event_timestamp_ms = GetMessageTime();
view->scrollFunc(
view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
(int16_t)HIWORD(wParam) / float(WHEEL_DELTA), 0.0f);
}
break;
case WM_KEYDOWN:
if (view->ignoreKeyRepeat && (lParam & (1 << 30))) {
break;
} // else nobreak
case WM_KEYUP:
view->event_timestamp_ms = GetMessageTime();
if ((key = keySymToSpecial(wParam))) {
if (view->specialFunc) {
view->specialFunc(view, message == WM_KEYDOWN, key);
}
} else if (view->keyboardFunc) {
view->keyboardFunc(view, message == WM_KEYDOWN, wParam);
}
break;
case WM_QUIT:
case PUGL_LOCAL_CLOSE_MSG:
if (view->closeFunc) {
view->closeFunc(view);
}
break;
default:
return DefWindowProc(
view->impl->hwnd, message, wParam, lParam);
}
return 0;
}
PuglStatus
puglProcessEvents(PuglView* view)
{
MSG msg;
while (PeekMessage(&msg, view->impl->hwnd, 0, 0, PM_REMOVE)) {
handleMessage(view, msg.message, msg.wParam, msg.lParam);
}
if (view->redisplay) {
InvalidateRect(view->impl->hwnd, NULL, FALSE);
}
return PUGL_SUCCESS;
}
LRESULT CALLBACK
wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
#ifdef _WIN64
PuglView* view = (PuglView*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
#else
PuglView* view = (PuglView*)GetWindowLongPtr(hwnd, GWL_USERDATA);
#endif
switch (message) {
case WM_CREATE:
PostMessage(hwnd, WM_SHOWWINDOW, TRUE, 0);
return 0;
case WM_CLOSE:
PostMessage(hwnd, PUGL_LOCAL_CLOSE_MSG, wParam, lParam);
return 0;
case WM_DESTROY:
return 0;
default:
if (view) {
return handleMessage(view, message, wParam, lParam);
} else {
return DefWindowProc(hwnd, message, wParam, lParam);
}
}
}
void
puglPostRedisplay(PuglView* view)
{
view->redisplay = true;
}
PuglNativeWindow
puglGetNativeWindow(PuglView* view)
{
return (PuglNativeWindow)view->impl->hwnd;
}
<|endoftext|> |
<commit_before>AliAnalysisTaskCheckDeadcone* AddTaskCheckDeadcone(const char * njetsBase,
const char * njetsUS,
const char * njetsTrue,
const char * njetsPartLevel,
const Double_t R,
const char * nrhoBase,
const char * ntracks,
const char * ntracksUS,
const char *ntracksPartLevel,
const char * nclusters,
const char * ntracksTrue,
const char *type,
const char *CentEst,
Int_t pSel,
TString trigClass = "",
TString kEmcalTriggers = "",
TString tag = "",
AliAnalysisTaskCheckDeadcone::JetShapeType jetShapeType = AliAnalysisTaskCheckDeadcone::kMCTrue,
AliAnalysisTaskCheckDeadcone::JetShapeSub jetShapeSub = AliAnalysisTaskCheckDeadcone::kNoSub,
AliAnalysisTaskCheckDeadcone::JetSelectionType jetSelection = AliAnalysisTaskCheckDeadcone::kInclusive,
Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskCheckDeadcone::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskCheckDeadcone::kSecondOrder ) {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
Error("AddTaskCheckDeadcone","No analysis manager found.");
return 0;
}
Bool_t ismc=kFALSE;
ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskCheckDeadcone", "This task requires an input event handler");
return NULL;
}
TString wagonName1 = Form("JetSubstructure_%s_TC%s%s",njetsBase,trigClass.Data(),tag.Data());
TString wagonName2 = Form("JetSubstructure_%s_TC%s%sTree",njetsBase,trigClass.Data(),tag.Data());
//Configure jet tagger task
AliAnalysisTaskCheckDeadcone *task = new AliAnalysisTaskCheckDeadcone(wagonName1.Data());
//task->SetNCentBins(4);
task->SetJetShapeType(jetShapeType);
task->SetJetShapeSub(jetShapeSub);
task->SetJetSelection(jetSelection);
task->SetDerivativeSubtractionOrder(derivSubtrOrder);
TString thename(njetsBase);
//if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE);
//task->SetVzRange(-10.,10.);
AliParticleContainer *trackCont;// = task->AddTrackContainer(ntracks);
if ((jetShapeSub==AliAnalysisTaskCheckDeadcone::kConstSub || jetShapeSub==AliAnalysisTaskCheckDeadcone::kEventSub ) && ((jetShapeType==AliAnalysisTaskCheckDeadcone::kData) || (jetShapeType==AliAnalysisTaskCheckDeadcone::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskCheckDeadcone::kPythiaDef))){
trackCont = task->AddParticleContainer(ntracks);}
else trackCont = task->AddTrackContainer(ntracks);
//Printf("tracks() = %s, trackCont =%p", ntracks, trackCont);
AliParticleContainer *trackContUS = task->AddTrackContainer(ntracksUS);
//Printf("tracksUS() = %s", ntracksUS);
AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);
//Printf("ntracksTrue() = %s, trackContTrue=%p ", ntracksTrue, trackContTrue);
if (jetShapeType==AliAnalysisTaskCheckDeadcone::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true);
AliParticleContainer *trackContPartLevel=0;
if ((jetShapeSub==AliAnalysisTaskCheckDeadcone::kConstSub) && ((jetShapeType==AliAnalysisTaskCheckDeadcone::kMCTrue) || (jetShapeType==AliAnalysisTaskCheckDeadcone::kPythiaDef))){
trackContPartLevel = task->AddParticleContainer(ntracksPartLevel);
}
else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel);
if (jetShapeType==AliAnalysisTaskCheckDeadcone::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true);
//Printf("ntracksPartLevel() = %s, trackContPartLevel=%p ", ntracksPartLevel, trackContPartLevel);
AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);
AliJetContainer *jetContBase=0x0;
AliJetContainer *jetContUS=0x0;
AliJetContainer *jetContTrue=0x0;
AliJetContainer *jetContPart=0x0;
TString strType(type);
if ((jetShapeType==AliAnalysisTaskCheckDeadcone::kMCTrue || (jetShapeType==AliAnalysisTaskCheckDeadcone::kGenOnTheFly))) {
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->SetRhoName(nrhoBase);
jetContBase->ConnectParticleContainer(trackContPartLevel);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
}
}
if (jetShapeType==AliAnalysisTaskCheckDeadcone::kData){
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->SetRhoName(nrhoBase);
jetContBase->ConnectParticleContainer(trackCont);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
if(jetShapeSub==AliAnalysisTaskCheckDeadcone::kConstSub) jetContBase->SetAreaEmcCut(-2);
}
}
if (jetShapeType==AliAnalysisTaskCheckDeadcone::kDetEmbPartPythia){
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->SetRhoName(nrhoBase);
jetContBase->ConnectParticleContainer(trackCont);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
if(jetShapeSub==AliAnalysisTaskCheckDeadcone::kConstSub) jetContBase->SetAreaEmcCut(-2);
}
jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
if(jetContTrue) {
jetContTrue->SetRhoName(nrhoBase);
jetContTrue->ConnectParticleContainer(trackContTrue);
jetContTrue->SetPercAreaCut(acut);
}
if(jetShapeSub==AliAnalysisTaskCheckDeadcone::kConstSub || jetShapeSub==AliAnalysisTaskCheckDeadcone::kEventSub){
jetContUS=task->AddJetContainer(njetsUS,strType,R);
if(jetContUS) {
jetContUS->SetRhoName(nrhoBase);
jetContUS->ConnectParticleContainer(trackContUS);
jetContUS->SetPercAreaCut(acut);
}
}
jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
if(jetContPart) {
jetContPart->SetRhoName(nrhoBase);
jetContPart->ConnectParticleContainer(trackContPartLevel);
jetContPart->SetPercAreaCut(acut);
}
}
if (jetShapeType==AliAnalysisTaskCheckDeadcone::kPythiaDef){
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->ConnectParticleContainer(trackCont);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
}
jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
if(jetContTrue) {
jetContTrue->SetRhoName(nrhoBase);
jetContTrue->ConnectParticleContainer(trackContTrue);
jetContTrue->SetPercAreaCut(acut);
}
if(jetShapeSub==AliAnalysisTaskCheckDeadcone::kConstSub){
jetContUS=task->AddJetContainer(njetsUS,strType,R);
if(jetContUS) {
jetContUS->SetRhoName(nrhoBase);
jetContUS->ConnectParticleContainer(trackContUS);
jetContUS->SetPercAreaCut(acut);
}
}
jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
if(jetContPart) {
jetContPart->SetRhoName(nrhoBase);
jetContPart->ConnectParticleContainer(trackContPartLevel);
jetContPart->SetPercAreaCut(acut);
}
}
task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
task->SetCentralityEstimator(CentEst);
task->SelectCollisionCandidates(pSel);
task->SetUseAliAnaUtils(kFALSE);
mgr->AddTask(task);
//Connnect input
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );
//Connect output
TString contName1(wagonName1);
TString contName2(wagonName2);
if (jetShapeType == AliAnalysisTaskCheckDeadcone::kMCTrue) contName1 += "_MCTrue";
if (jetShapeType == AliAnalysisTaskCheckDeadcone::kData) contName1 += "_Data";
if (jetShapeType == AliAnalysisTaskCheckDeadcone::kPythiaDef) contName1 +="_PythiaDef";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kNoSub) contName1 += "_NoSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kConstSub) contName1 += "_ConstSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kEventSub) contName1 += "_EventSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kDerivSub) contName1 += "_DerivSub";
if (jetSelection == AliAnalysisTaskCheckDeadcone::kInclusive) contName1 += "_Incl";
if (jetShapeType == AliAnalysisTaskCheckDeadcone::kMCTrue) contName2 += "_MCTrue";
if (jetShapeType == AliAnalysisTaskCheckDeadcone::kData) contName2 += "_Data";
if (jetShapeType == AliAnalysisTaskCheckDeadcone::kPythiaDef) contName2 +="_PythiaDef";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kNoSub) contName2 += "_NoSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kConstSub) contName2 += "_ConstSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kEventSub) contName2 += "_EventSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadcone::kDerivSub) contName2 += "_DerivSub";
if (jetSelection == AliAnalysisTaskCheckDeadcone::kInclusive) contName2 += "_Incl";
TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
mgr->ConnectOutput(task,1,coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);
mgr->ConnectOutput(task,2,coutput2);
return task;
}
<commit_msg>bug check<commit_after>AliAnalysisTaskCheckDeadCone* AddTaskCheckDeadCone(const char * njetsBase,
const char * njetsUS,
const char * njetsTrue,
const char * njetsPartLevel,
const Double_t R,
const char * nrhoBase,
const char * ntracks,
const char * ntracksUS,
const char *ntracksPartLevel,
const char * nclusters,
const char * ntracksTrue,
const char *type,
const char *CentEst,
Int_t pSel,
TString trigClass = "",
TString kEmcalTriggers = "",
TString tag = "",
AliAnalysisTaskCheckDeadCone::JetShapeType jetShapeType = AliAnalysisTaskCheckDeadCone::kMCTrue,
AliAnalysisTaskCheckDeadCone::JetShapeSub jetShapeSub = AliAnalysisTaskCheckDeadCone::kNoSub,
AliAnalysisTaskCheckDeadCone::JetSelectionType jetSelection = AliAnalysisTaskCheckDeadCone::kInclusive,
Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskCheckDeadCone::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskCheckDeadCone::kSecondOrder ) {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
Error("AddTaskCheckDeadCone","No analysis manager found.");
return 0;
}
Bool_t ismc=kFALSE;
ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskCheckDeadCone", "This task requires an input event handler");
return NULL;
}
TString wagonName1 = Form("JetSubstructure_%s_TC%s%s",njetsBase,trigClass.Data(),tag.Data());
TString wagonName2 = Form("JetSubstructure_%s_TC%s%sTree",njetsBase,trigClass.Data(),tag.Data());
//Configure jet tagger task
AliAnalysisTaskCheckDeadCone *task = new AliAnalysisTaskCheckDeadCone(wagonName1.Data());
//task->SetNCentBins(4);
task->SetJetShapeType(jetShapeType);
task->SetJetShapeSub(jetShapeSub);
task->SetJetSelection(jetSelection);
task->SetDerivativeSubtractionOrder(derivSubtrOrder);
TString thename(njetsBase);
//if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE);
//task->SetVzRange(-10.,10.);
AliParticleContainer *trackCont;// = task->AddTrackContainer(ntracks);
if ((jetShapeSub==AliAnalysisTaskCheckDeadCone::kConstSub || jetShapeSub==AliAnalysisTaskCheckDeadCone::kEventSub ) && ((jetShapeType==AliAnalysisTaskCheckDeadCone::kData) || (jetShapeType==AliAnalysisTaskCheckDeadCone::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskCheckDeadCone::kPythiaDef))){
trackCont = task->AddParticleContainer(ntracks);}
else trackCont = task->AddTrackContainer(ntracks);
//Printf("tracks() = %s, trackCont =%p", ntracks, trackCont);
AliParticleContainer *trackContUS = task->AddTrackContainer(ntracksUS);
//Printf("tracksUS() = %s", ntracksUS);
AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);
//Printf("ntracksTrue() = %s, trackContTrue=%p ", ntracksTrue, trackContTrue);
if (jetShapeType==AliAnalysisTaskCheckDeadCone::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true);
AliParticleContainer *trackContPartLevel=0;
if ((jetShapeSub==AliAnalysisTaskCheckDeadCone::kConstSub) && ((jetShapeType==AliAnalysisTaskCheckDeadCone::kMCTrue) || (jetShapeType==AliAnalysisTaskCheckDeadCone::kPythiaDef))){
trackContPartLevel = task->AddParticleContainer(ntracksPartLevel);
}
else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel);
if (jetShapeType==AliAnalysisTaskCheckDeadCone::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true);
//Printf("ntracksPartLevel() = %s, trackContPartLevel=%p ", ntracksPartLevel, trackContPartLevel);
AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);
AliJetContainer *jetContBase=0x0;
AliJetContainer *jetContUS=0x0;
AliJetContainer *jetContTrue=0x0;
AliJetContainer *jetContPart=0x0;
TString strType(type);
if ((jetShapeType==AliAnalysisTaskCheckDeadCone::kMCTrue || (jetShapeType==AliAnalysisTaskCheckDeadCone::kGenOnTheFly))) {
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->SetRhoName(nrhoBase);
jetContBase->ConnectParticleContainer(trackContPartLevel);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
}
}
if (jetShapeType==AliAnalysisTaskCheckDeadCone::kData){
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->SetRhoName(nrhoBase);
jetContBase->ConnectParticleContainer(trackCont);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
if(jetShapeSub==AliAnalysisTaskCheckDeadCone::kConstSub) jetContBase->SetAreaEmcCut(-2);
}
}
if (jetShapeType==AliAnalysisTaskCheckDeadCone::kDetEmbPartPythia){
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->SetRhoName(nrhoBase);
jetContBase->ConnectParticleContainer(trackCont);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
if(jetShapeSub==AliAnalysisTaskCheckDeadCone::kConstSub) jetContBase->SetAreaEmcCut(-2);
}
jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
if(jetContTrue) {
jetContTrue->SetRhoName(nrhoBase);
jetContTrue->ConnectParticleContainer(trackContTrue);
jetContTrue->SetPercAreaCut(acut);
}
if(jetShapeSub==AliAnalysisTaskCheckDeadCone::kConstSub || jetShapeSub==AliAnalysisTaskCheckDeadCone::kEventSub){
jetContUS=task->AddJetContainer(njetsUS,strType,R);
if(jetContUS) {
jetContUS->SetRhoName(nrhoBase);
jetContUS->ConnectParticleContainer(trackContUS);
jetContUS->SetPercAreaCut(acut);
}
}
jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
if(jetContPart) {
jetContPart->SetRhoName(nrhoBase);
jetContPart->ConnectParticleContainer(trackContPartLevel);
jetContPart->SetPercAreaCut(acut);
}
}
if (jetShapeType==AliAnalysisTaskCheckDeadCone::kPythiaDef){
jetContBase = task->AddJetContainer(njetsBase,strType,R);
if(jetContBase) {
jetContBase->ConnectParticleContainer(trackCont);
jetContBase->ConnectClusterContainer(clusterCont);
jetContBase->SetPercAreaCut(acut);
}
jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
if(jetContTrue) {
jetContTrue->SetRhoName(nrhoBase);
jetContTrue->ConnectParticleContainer(trackContTrue);
jetContTrue->SetPercAreaCut(acut);
}
if(jetShapeSub==AliAnalysisTaskCheckDeadCone::kConstSub){
jetContUS=task->AddJetContainer(njetsUS,strType,R);
if(jetContUS) {
jetContUS->SetRhoName(nrhoBase);
jetContUS->ConnectParticleContainer(trackContUS);
jetContUS->SetPercAreaCut(acut);
}
}
jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
if(jetContPart) {
jetContPart->SetRhoName(nrhoBase);
jetContPart->ConnectParticleContainer(trackContPartLevel);
jetContPart->SetPercAreaCut(acut);
}
}
task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
task->SetCentralityEstimator(CentEst);
task->SelectCollisionCandidates(pSel);
task->SetUseAliAnaUtils(kFALSE);
mgr->AddTask(task);
//Connnect input
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );
//Connect output
TString contName1(wagonName1);
TString contName2(wagonName2);
if (jetShapeType == AliAnalysisTaskCheckDeadCone::kMCTrue) contName1 += "_MCTrue";
if (jetShapeType == AliAnalysisTaskCheckDeadCone::kData) contName1 += "_Data";
if (jetShapeType == AliAnalysisTaskCheckDeadCone::kPythiaDef) contName1 +="_PythiaDef";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kNoSub) contName1 += "_NoSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kConstSub) contName1 += "_ConstSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kEventSub) contName1 += "_EventSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kDerivSub) contName1 += "_DerivSub";
if (jetSelection == AliAnalysisTaskCheckDeadCone::kInclusive) contName1 += "_Incl";
if (jetShapeType == AliAnalysisTaskCheckDeadCone::kMCTrue) contName2 += "_MCTrue";
if (jetShapeType == AliAnalysisTaskCheckDeadCone::kData) contName2 += "_Data";
if (jetShapeType == AliAnalysisTaskCheckDeadCone::kPythiaDef) contName2 +="_PythiaDef";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kNoSub) contName2 += "_NoSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kConstSub) contName2 += "_ConstSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kEventSub) contName2 += "_EventSub";
if (jetShapeSub == AliAnalysisTaskCheckDeadCone::kDerivSub) contName2 += "_DerivSub";
if (jetSelection == AliAnalysisTaskCheckDeadCone::kInclusive) contName2 += "_Incl";
TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
mgr->ConnectOutput(task,1,coutput1);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);
mgr->ConnectOutput(task,2,coutput2);
return task;
}
<|endoftext|> |
<commit_before>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
#define DEBUG(__X__) \
do \
{ \
if (::rstudio::core::FileLock::isLoggingEnabled()) \
{ \
std::stringstream ss; \
ss << "(PID " << ::getpid() << "): " << __X__; \
LOG_DEBUG_MESSAGE(ss.str()); \
} \
} while (0)
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string hostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str();
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
DEBUG("Bumping write time: " << lockFilePath.absolutePath());
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
DEBUG("Clearing lock: " << lockFilePath.absolutePath());
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
Error error = proxyPath.removeIfExists();
if (error)
LOG_ERROR(error);
// ensure the proxy file is created, and remove it when we're done
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
error = proxyPath.ensureFile();
if (error)
{
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignore lock_not_available errors
LOG_ERROR(error);
return error;
}
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
int status = ::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
// Log errors (remove this if it is too noisy on NFS)
if (status == -1)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
{
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignoring lock_not_available errors
Error error = systemError(errno, ERROR_LOCATION);
LOG_ERROR(error);
return error;
}
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
DEBUG("Removing stale lockfile: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
DEBUG("No lock available: " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
{
DEBUG("Failed to acquire lock (lost race?): " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
error,
ERROR_LOCATION);
}
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
DEBUG("Acquired lock: " << lockFilePath.absolutePath());
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
DEBUG("Released lock: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
DEBUG("Refreshing locks...");
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
DEBUG("Cleaning up lock registry...");
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<commit_msg>don't log here (as these methods always called)<commit_after>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
#define DEBUG(__X__) \
do \
{ \
if (::rstudio::core::FileLock::isLoggingEnabled()) \
{ \
std::stringstream ss; \
ss << "(PID " << ::getpid() << "): " << __X__; \
LOG_DEBUG_MESSAGE(ss.str()); \
} \
} while (0)
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string hostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str();
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
DEBUG("Bumping write time: " << lockFilePath.absolutePath());
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
DEBUG("Clearing lock: " << lockFilePath.absolutePath());
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
Error error = proxyPath.removeIfExists();
if (error)
LOG_ERROR(error);
// ensure the proxy file is created, and remove it when we're done
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
error = proxyPath.ensureFile();
if (error)
{
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignore lock_not_available errors
LOG_ERROR(error);
return error;
}
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
int status = ::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
// Log errors (remove this if it is too noisy on NFS)
if (status == -1)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
{
// log the error since it isn't expected and could get swallowed
// upstream by a caller ignoring lock_not_available errors
Error error = systemError(errno, ERROR_LOCATION);
LOG_ERROR(error);
return error;
}
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
DEBUG("Removing stale lockfile: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
DEBUG("No lock available: " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
{
DEBUG("Failed to acquire lock (lost race?): " << lockFilePath.absolutePath());
return systemError(boost::system::errc::no_lock_available,
error,
ERROR_LOCATION);
}
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
DEBUG("Acquired lock: " << lockFilePath.absolutePath());
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
DEBUG("Released lock: " << lockFilePath.absolutePath());
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before>/*************************************************************************/
/* gdscript_highlighter.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 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 "gdscript_highlighter.h"
#include "../gdscript_tokenizer.h"
#include "editor/editor_settings.h"
#include "scene/gui/text_edit.h"
inline bool _is_symbol(CharType c) {
return is_symbol(c);
}
static bool _is_text_char(CharType c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
static bool _is_char(CharType c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
static bool _is_number(CharType c) {
return (c >= '0' && c <= '9');
}
static bool _is_hex_symbol(CharType c) {
return ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}
static bool _is_bin_symbol(CharType c) {
return (c == '0' || c == '1');
}
Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) {
Map<int, TextEdit::HighlighterInfo> color_map;
Type next_type = NONE;
Type current_type = NONE;
Type previous_type = NONE;
String previous_text = "";
int previous_column = 0;
bool prev_is_char = false;
bool prev_is_number = false;
bool in_keyword = false;
bool in_word = false;
bool in_function_name = false;
bool in_variable_declaration = false;
bool in_function_args = false;
bool in_member_variable = false;
bool in_node_path = false;
bool is_hex_notation = false;
bool is_bin_notation = false;
bool expect_type = false;
Color keyword_color;
Color color;
int in_region = text_editor->_is_line_in_region(p_line);
int deregion = 0;
const Map<int, TextEdit::Text::ColorRegionInfo> cri_map = text_editor->_get_line_color_region_info(p_line);
const String &str = text_editor->get_line(p_line);
Color prev_color;
for (int j = 0; j < str.length(); j++) {
TextEdit::HighlighterInfo highlighter_info;
if (deregion > 0) {
deregion--;
if (deregion == 0) {
in_region = -1;
}
}
if (deregion != 0) {
if (color != prev_color) {
prev_color = color;
highlighter_info.color = color;
color_map[j] = highlighter_info;
}
continue;
}
color = font_color;
bool is_char = _is_text_char(str[j]);
bool is_symbol = _is_symbol(str[j]);
bool is_number = _is_number(str[j]);
// allow ABCDEF in hex notation
if (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) {
is_number = true;
} else {
is_hex_notation = false;
}
// disallow anything not a 0 or 1
if (is_bin_notation && (_is_bin_symbol(str[j]))) {
is_number = true;
} else if (is_bin_notation) {
is_bin_notation = false;
is_number = false;
} else {
is_bin_notation = false;
}
// check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation
if ((str[j] == '.' || str[j] == 'x' || str[j] == 'b' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {
is_number = true;
is_symbol = false;
is_char = false;
if (str[j] == 'x' && str[j - 1] == '0') {
is_hex_notation = true;
} else if (str[j] == 'b' && str[j - 1] == '0') {
is_bin_notation = true;
}
}
if (!in_word && _is_char(str[j]) && !is_number) {
in_word = true;
}
if ((in_keyword || in_word) && !is_hex_notation) {
is_number = false;
}
if (is_symbol && str[j] != '.' && in_word) {
in_word = false;
}
if (is_symbol && cri_map.has(j)) {
const TextEdit::Text::ColorRegionInfo &cri = cri_map[j];
if (in_region == -1) {
if (!cri.end) {
in_region = cri.region;
}
} else {
TextEdit::ColorRegion cr = text_editor->_get_color_region(cri.region);
if (in_region == cri.region && !cr.line_only) { //ignore otherwise
if (cri.end || cr.eq) {
deregion = cr.eq ? cr.begin_key.length() : cr.end_key.length();
}
}
}
}
if (!is_char) {
in_keyword = false;
}
if (in_region == -1 && !in_keyword && is_char && !prev_is_char) {
int to = j;
while (to < str.length() && _is_text_char(str[to]))
to++;
String word = str.substr(j, to - j);
Color col = Color();
if (text_editor->has_keyword_color(word)) {
col = text_editor->get_keyword_color(word);
} else if (text_editor->has_member_color(word)) {
col = text_editor->get_member_color(word);
for (int k = j - 1; k >= 0; k--) {
if (str[k] == '.') {
col = Color(); //member indexing not allowed
break;
} else if (str[k] > 32) {
break;
}
}
}
if (col != Color()) {
in_keyword = true;
keyword_color = col;
}
}
if (!in_function_name && in_word && !in_keyword) {
int k = j;
while (k < str.length() && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
k++;
}
// check for space between name and bracket
while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) {
k++;
}
if (str[k] == '(') {
in_function_name = true;
} else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_VAR)) {
in_variable_declaration = true;
}
}
if (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) {
int k = j;
while (k > 0 && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
k--;
}
if (str[k] == '.') {
in_member_variable = true;
}
}
if (is_symbol) {
if (in_function_name) {
in_function_args = true;
}
if (in_function_args && str[j] == ')') {
in_function_args = false;
}
if (expect_type && (prev_is_char || str[j] == '=')) {
expect_type = false;
}
if (j > 0 && str[j] == '>' && str[j - 1] == '-') {
expect_type = true;
}
if (in_variable_declaration || in_function_args) {
int k = j;
// Skip space
while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) {
k++;
}
if (str[k] == ':') {
// has type hint
expect_type = true;
}
}
in_variable_declaration = false;
in_function_name = false;
in_member_variable = false;
}
if (!in_node_path && in_region == -1 && str[j] == '$') {
in_node_path = true;
} else if (in_region != -1 || (is_symbol && str[j] != '/')) {
in_node_path = false;
}
if (in_region >= 0) {
next_type = REGION;
color = text_editor->_get_color_region(in_region).color;
} else if (in_node_path) {
next_type = NODE_PATH;
color = node_path_color;
} else if (in_keyword) {
next_type = KEYWORD;
color = keyword_color;
} else if (in_member_variable) {
next_type = MEMBER;
color = member_color;
} else if (in_function_name) {
next_type = FUNCTION;
if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_FUNCTION)) {
color = function_definition_color;
} else {
color = function_color;
}
} else if (is_symbol) {
next_type = SYMBOL;
color = symbol_color;
} else if (is_number) {
next_type = NUMBER;
color = number_color;
} else if (expect_type) {
next_type = TYPE;
color = type_color;
} else {
next_type = IDENTIFIER;
}
if (next_type != current_type) {
if (current_type == NONE) {
current_type = next_type;
} else {
previous_type = current_type;
current_type = next_type;
// no need to store regions...
if (previous_type == REGION) {
previous_text = "";
previous_column = j;
} else {
String text = str.substr(previous_column, j - previous_column).strip_edges();
previous_column = j;
// ignore if just whitespace
if (text != "") {
previous_text = text;
}
}
}
}
prev_is_char = is_char;
prev_is_number = is_number;
if (color != prev_color) {
prev_color = color;
highlighter_info.color = color;
color_map[j] = highlighter_info;
}
}
return color_map;
}
String GDScriptSyntaxHighlighter::get_name() const {
return "GDScript";
}
List<String> GDScriptSyntaxHighlighter::get_supported_languages() {
List<String> languages;
languages.push_back("GDScript");
return languages;
}
void GDScriptSyntaxHighlighter::_update_cache() {
font_color = text_editor->get_color("font_color");
symbol_color = text_editor->get_color("symbol_color");
function_color = text_editor->get_color("function_color");
number_color = text_editor->get_color("number_color");
member_color = text_editor->get_color("member_variable_color");
EditorSettings *settings = EditorSettings::get_singleton();
String text_editor_color_theme = settings->get("text_editor/theme/color_theme");
bool default_theme = text_editor_color_theme == "Default";
bool dark_theme = settings->is_dark_theme();
function_definition_color = default_theme ? Color(0.0, 0.88, 1.0) : dark_theme ? Color(0.0, 0.88, 1.0) : Color(0.0, 0.65, 0.73);
node_path_color = default_theme ? Color(0.39, 0.76, 0.35) : dark_theme ? Color(0.39, 0.76, 0.35) : Color(0.32, 0.55, 0.29);
EDITOR_DEF("text_editor/highlighting/gdscript/function_definition_color", function_definition_color);
EDITOR_DEF("text_editor/highlighting/gdscript/node_path_color", node_path_color);
if (text_editor_color_theme == "Adaptive" || default_theme) {
settings->set_initial_value("text_editor/highlighting/gdscript/function_definition_color", function_definition_color, true);
settings->set_initial_value("text_editor/highlighting/gdscript/node_path_color", node_path_color, true);
}
function_definition_color = EDITOR_GET("text_editor/highlighting/gdscript/function_definition_color");
node_path_color = EDITOR_GET("text_editor/highlighting/gdscript/node_path_color");
type_color = EDITOR_GET("text_editor/highlighting/base_type_color");
}
SyntaxHighlighter *GDScriptSyntaxHighlighter::create() {
return memnew(GDScriptSyntaxHighlighter);
}
<commit_msg>Tweak the default function definition color when using a dark theme<commit_after>/*************************************************************************/
/* gdscript_highlighter.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 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 "gdscript_highlighter.h"
#include "../gdscript_tokenizer.h"
#include "editor/editor_settings.h"
#include "scene/gui/text_edit.h"
inline bool _is_symbol(CharType c) {
return is_symbol(c);
}
static bool _is_text_char(CharType c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
static bool _is_char(CharType c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
static bool _is_number(CharType c) {
return (c >= '0' && c <= '9');
}
static bool _is_hex_symbol(CharType c) {
return ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}
static bool _is_bin_symbol(CharType c) {
return (c == '0' || c == '1');
}
Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) {
Map<int, TextEdit::HighlighterInfo> color_map;
Type next_type = NONE;
Type current_type = NONE;
Type previous_type = NONE;
String previous_text = "";
int previous_column = 0;
bool prev_is_char = false;
bool prev_is_number = false;
bool in_keyword = false;
bool in_word = false;
bool in_function_name = false;
bool in_variable_declaration = false;
bool in_function_args = false;
bool in_member_variable = false;
bool in_node_path = false;
bool is_hex_notation = false;
bool is_bin_notation = false;
bool expect_type = false;
Color keyword_color;
Color color;
int in_region = text_editor->_is_line_in_region(p_line);
int deregion = 0;
const Map<int, TextEdit::Text::ColorRegionInfo> cri_map = text_editor->_get_line_color_region_info(p_line);
const String &str = text_editor->get_line(p_line);
Color prev_color;
for (int j = 0; j < str.length(); j++) {
TextEdit::HighlighterInfo highlighter_info;
if (deregion > 0) {
deregion--;
if (deregion == 0) {
in_region = -1;
}
}
if (deregion != 0) {
if (color != prev_color) {
prev_color = color;
highlighter_info.color = color;
color_map[j] = highlighter_info;
}
continue;
}
color = font_color;
bool is_char = _is_text_char(str[j]);
bool is_symbol = _is_symbol(str[j]);
bool is_number = _is_number(str[j]);
// allow ABCDEF in hex notation
if (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) {
is_number = true;
} else {
is_hex_notation = false;
}
// disallow anything not a 0 or 1
if (is_bin_notation && (_is_bin_symbol(str[j]))) {
is_number = true;
} else if (is_bin_notation) {
is_bin_notation = false;
is_number = false;
} else {
is_bin_notation = false;
}
// check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation
if ((str[j] == '.' || str[j] == 'x' || str[j] == 'b' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {
is_number = true;
is_symbol = false;
is_char = false;
if (str[j] == 'x' && str[j - 1] == '0') {
is_hex_notation = true;
} else if (str[j] == 'b' && str[j - 1] == '0') {
is_bin_notation = true;
}
}
if (!in_word && _is_char(str[j]) && !is_number) {
in_word = true;
}
if ((in_keyword || in_word) && !is_hex_notation) {
is_number = false;
}
if (is_symbol && str[j] != '.' && in_word) {
in_word = false;
}
if (is_symbol && cri_map.has(j)) {
const TextEdit::Text::ColorRegionInfo &cri = cri_map[j];
if (in_region == -1) {
if (!cri.end) {
in_region = cri.region;
}
} else {
TextEdit::ColorRegion cr = text_editor->_get_color_region(cri.region);
if (in_region == cri.region && !cr.line_only) { //ignore otherwise
if (cri.end || cr.eq) {
deregion = cr.eq ? cr.begin_key.length() : cr.end_key.length();
}
}
}
}
if (!is_char) {
in_keyword = false;
}
if (in_region == -1 && !in_keyword && is_char && !prev_is_char) {
int to = j;
while (to < str.length() && _is_text_char(str[to]))
to++;
String word = str.substr(j, to - j);
Color col = Color();
if (text_editor->has_keyword_color(word)) {
col = text_editor->get_keyword_color(word);
} else if (text_editor->has_member_color(word)) {
col = text_editor->get_member_color(word);
for (int k = j - 1; k >= 0; k--) {
if (str[k] == '.') {
col = Color(); //member indexing not allowed
break;
} else if (str[k] > 32) {
break;
}
}
}
if (col != Color()) {
in_keyword = true;
keyword_color = col;
}
}
if (!in_function_name && in_word && !in_keyword) {
int k = j;
while (k < str.length() && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
k++;
}
// check for space between name and bracket
while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) {
k++;
}
if (str[k] == '(') {
in_function_name = true;
} else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_VAR)) {
in_variable_declaration = true;
}
}
if (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) {
int k = j;
while (k > 0 && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
k--;
}
if (str[k] == '.') {
in_member_variable = true;
}
}
if (is_symbol) {
if (in_function_name) {
in_function_args = true;
}
if (in_function_args && str[j] == ')') {
in_function_args = false;
}
if (expect_type && (prev_is_char || str[j] == '=')) {
expect_type = false;
}
if (j > 0 && str[j] == '>' && str[j - 1] == '-') {
expect_type = true;
}
if (in_variable_declaration || in_function_args) {
int k = j;
// Skip space
while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) {
k++;
}
if (str[k] == ':') {
// has type hint
expect_type = true;
}
}
in_variable_declaration = false;
in_function_name = false;
in_member_variable = false;
}
if (!in_node_path && in_region == -1 && str[j] == '$') {
in_node_path = true;
} else if (in_region != -1 || (is_symbol && str[j] != '/')) {
in_node_path = false;
}
if (in_region >= 0) {
next_type = REGION;
color = text_editor->_get_color_region(in_region).color;
} else if (in_node_path) {
next_type = NODE_PATH;
color = node_path_color;
} else if (in_keyword) {
next_type = KEYWORD;
color = keyword_color;
} else if (in_member_variable) {
next_type = MEMBER;
color = member_color;
} else if (in_function_name) {
next_type = FUNCTION;
if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_FUNCTION)) {
color = function_definition_color;
} else {
color = function_color;
}
} else if (is_symbol) {
next_type = SYMBOL;
color = symbol_color;
} else if (is_number) {
next_type = NUMBER;
color = number_color;
} else if (expect_type) {
next_type = TYPE;
color = type_color;
} else {
next_type = IDENTIFIER;
}
if (next_type != current_type) {
if (current_type == NONE) {
current_type = next_type;
} else {
previous_type = current_type;
current_type = next_type;
// no need to store regions...
if (previous_type == REGION) {
previous_text = "";
previous_column = j;
} else {
String text = str.substr(previous_column, j - previous_column).strip_edges();
previous_column = j;
// ignore if just whitespace
if (text != "") {
previous_text = text;
}
}
}
}
prev_is_char = is_char;
prev_is_number = is_number;
if (color != prev_color) {
prev_color = color;
highlighter_info.color = color;
color_map[j] = highlighter_info;
}
}
return color_map;
}
String GDScriptSyntaxHighlighter::get_name() const {
return "GDScript";
}
List<String> GDScriptSyntaxHighlighter::get_supported_languages() {
List<String> languages;
languages.push_back("GDScript");
return languages;
}
void GDScriptSyntaxHighlighter::_update_cache() {
font_color = text_editor->get_color("font_color");
symbol_color = text_editor->get_color("symbol_color");
function_color = text_editor->get_color("function_color");
number_color = text_editor->get_color("number_color");
member_color = text_editor->get_color("member_variable_color");
const String text_editor_color_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme");
const bool default_theme = text_editor_color_theme == "Default";
if (default_theme || EditorSettings::get_singleton()->is_dark_theme()) {
function_definition_color = Color(0.4, 0.9, 1.0);
node_path_color = Color(0.39, 0.76, 0.35);
} else {
function_definition_color = Color(0.0, 0.65, 0.73);
node_path_color = Color(0.32, 0.55, 0.29);
}
EDITOR_DEF("text_editor/highlighting/gdscript/function_definition_color", function_definition_color);
EDITOR_DEF("text_editor/highlighting/gdscript/node_path_color", node_path_color);
if (text_editor_color_theme == "Adaptive" || default_theme) {
EditorSettings::get_singleton()->set_initial_value(
"text_editor/highlighting/gdscript/function_definition_color",
function_definition_color,
true);
EditorSettings::get_singleton()->set_initial_value(
"text_editor/highlighting/gdscript/node_path_color",
node_path_color,
true);
}
function_definition_color = EDITOR_GET("text_editor/highlighting/gdscript/function_definition_color");
node_path_color = EDITOR_GET("text_editor/highlighting/gdscript/node_path_color");
type_color = EDITOR_GET("text_editor/highlighting/base_type_color");
}
SyntaxHighlighter *GDScriptSyntaxHighlighter::create() {
return memnew(GDScriptSyntaxHighlighter);
}
<|endoftext|> |
<commit_before>/**********************************************************************
--- Dlgedit generated file ---
File: adddata.cpp
Last generated: Fri Jun 20 07:42:44 1997
DO NOT EDIT!!! This file will be automatically
regenerated by dlgedit. All changes will be lost.
*********************************************************************/
#include "adddata.h"
#define Inherited QDialog
#include <qframe.h>
#include <qlabel.h>
#include <kapp.h>
#include <klocale.h>
KAddDlgData::KAddDlgData
(
QWidget* parent,
const char* name
)
:
Inherited( parent, name )
{
QFrame* tmpQFrame;
tmpQFrame = new QFrame( this, "Frame_1" );
tmpQFrame->setGeometry( 10, 10, 280, 90 );
tmpQFrame->setFrameStyle( 34 );
QLabel* tmpQLabel;
tmpQLabel = new QLabel( this, "Label_1" );
tmpQLabel->setGeometry( 20, 20, 100, 30 );
tmpQLabel->setText( klocale->translate( "Task Name" ) );
tmpQLabel->setAlignment( 265 );
tmpQLabel->setMargin( -1 );
tmpQLabel = new QLabel( this, "Label_2" );
tmpQLabel->setGeometry( 20, 60, 100, 30 );
tmpQLabel->setText( klocale->translate( "Accumutated time (in minutes)" ) );
tmpQLabel->setAlignment( 1289 );
tmpQLabel->setMargin( -1 );
_taskName = new QLineEdit( this, "LineEdit_1" );
_taskName->setGeometry( 130, 20, 150, 30 );
_taskName->setText( "" );
_taskName->setMaxLength( 32767 );
_taskName->setEchoMode( QLineEdit::Normal );
_taskName->setFrame( TRUE );
_taskTime = new QLineEdit( this, "LineEdit_2" );
_taskTime->setGeometry( 130, 60, 150, 30 );
_taskTime->setText( "" );
_taskTime->setMaxLength( 32767 );
_taskTime->setEchoMode( QLineEdit::Normal );
_taskTime->setFrame( TRUE );
_okButton = new QPushButton( this, "PushButton_1" );
_okButton->setGeometry( 40, 110, 100, 30 );
connect( _okButton, SIGNAL(clicked()), SLOT(okClicked()) );
_okButton->setText( "&OK" );
_okButton->setAutoRepeat( FALSE );
_okButton->setAutoResize( FALSE );
_cancelButton = new QPushButton( this, "PushButton_2" );
_cancelButton->setGeometry( 160, 110, 100, 30 );
connect( _cancelButton, SIGNAL(clicked()), SLOT(cancelClicked()) );
_cancelButton->setText( klocale->translate( "&Cancel" ) );
_cancelButton->setAutoRepeat( FALSE );
_cancelButton->setAutoResize( FALSE );
resize( 300, 150 );
}
KAddDlgData::~KAddDlgData()
{
}
void KAddDlgData::okClicked()
{
}
void KAddDlgData::cancelClicked()
{
}
<commit_msg>OK button is default (finally!)<commit_after>/**********************************************************************
--- Dlgedit generated file ---
File: adddata.cpp
Last generated: Fri Jun 20 07:42:44 1997
DO NOT EDIT!!! This file will be automatically
regenerated by dlgedit. All changes will be lost.
*********************************************************************/
#include "adddata.h"
#define Inherited QDialog
#include <qframe.h>
#include <qlabel.h>
#include <kapp.h>
#include <klocale.h>
KAddDlgData::KAddDlgData
(
QWidget* parent,
const char* name
)
:
Inherited( parent, name )
{
QFrame* tmpQFrame;
tmpQFrame = new QFrame( this, "Frame_1" );
tmpQFrame->setGeometry( 10, 10, 280, 90 );
tmpQFrame->setFrameStyle( 34 );
QLabel* tmpQLabel;
tmpQLabel = new QLabel( this, "Label_1" );
tmpQLabel->setGeometry( 20, 20, 100, 30 );
tmpQLabel->setText( klocale->translate( "Task Name" ) );
tmpQLabel->setAlignment( 265 );
tmpQLabel->setMargin( -1 );
tmpQLabel = new QLabel( this, "Label_2" );
tmpQLabel->setGeometry( 20, 60, 100, 30 );
tmpQLabel->setText( klocale->translate( "Accumutated time (in minutes)" ) );
tmpQLabel->setAlignment( 1289 );
tmpQLabel->setMargin( -1 );
_taskName = new QLineEdit( this, "LineEdit_1" );
_taskName->setGeometry( 130, 20, 150, 30 );
_taskName->setText( "" );
_taskName->setMaxLength( 32767 );
_taskName->setEchoMode( QLineEdit::Normal );
_taskName->setFrame( TRUE );
_taskTime = new QLineEdit( this, "LineEdit_2" );
_taskTime->setGeometry( 130, 60, 150, 30 );
_taskTime->setText( "" );
_taskTime->setMaxLength( 32767 );
_taskTime->setEchoMode( QLineEdit::Normal );
_taskTime->setFrame( TRUE );
_okButton = new QPushButton( this, "PushButton_1" );
_okButton->setGeometry( 40, 110, 100, 30 );
connect( _okButton, SIGNAL(clicked()), SLOT(okClicked()) );
_okButton->setText( "&OK" );
_okButton->setDefault( TRUE );
_okButton->setAutoRepeat( FALSE );
_okButton->setAutoResize( FALSE );
_cancelButton = new QPushButton( this, "PushButton_2" );
_cancelButton->setGeometry( 160, 110, 100, 30 );
connect( _cancelButton, SIGNAL(clicked()), SLOT(cancelClicked()) );
_cancelButton->setText( klocale->translate( "&Cancel" ) );
_cancelButton->setAutoRepeat( FALSE );
_cancelButton->setAutoResize( FALSE );
resize( 300, 150 );
}
KAddDlgData::~KAddDlgData()
{
}
void KAddDlgData::okClicked()
{
}
void KAddDlgData::cancelClicked()
{
}
<|endoftext|> |
<commit_before>/// HEADER
#include <csapex/param/path_parameter.h>
/// PROJECT
#include <csapex/serialization/parameter_serializer.h>
#include <csapex/serialization/io/std_io.h>
/// SYSTEM
#include <yaml-cpp/yaml.h>
#include <boost/any.hpp>
CSAPEX_REGISTER_PARAMETER_SERIALIZER(PathParameter)
using namespace csapex;
using namespace param;
PathParameter::PathParameter()
: ParameterImplementation("noname", ParameterDescription())
{
}
PathParameter::PathParameter(const std::string &name, const ParameterDescription& description, const std::string &filter, bool is_file, bool input, bool output)
: ParameterImplementation(name, description), filter_(filter), is_file_(is_file), input_(input), output_(output)
{
}
PathParameter::~PathParameter()
{
}
const std::type_info& PathParameter::type() const
{
return typeid(std::string);
}
std::string PathParameter::toStringImpl() const
{
return std::string("[path: ") + value_ + "]";
}
void PathParameter::get_unsafe(boost::any& out) const
{
out = value_;
}
bool PathParameter::set_unsafe(const boost::any &v)
{
auto val = boost::any_cast<std::string>(v);
if(value_ != val) {
value_ = val;
return true;
}
return false;
}
void PathParameter::cloneDataFrom(const Clonable &other)
{
if(const PathParameter* path = dynamic_cast<const PathParameter*>(&other)) {
if(value_ != path->value_) {
*this = *path;
triggerChange();
}
} else {
throw std::runtime_error("bad setFrom, invalid types");
}
}
void PathParameter::doSerialize(YAML::Node& n) const
{
n["value"] = value_;
}
void PathParameter::doDeserialize(const YAML::Node& n)
{
value_ = n["value"].as<std::string>();
}
std::string PathParameter::def() const
{
return def_;
}
std::string PathParameter::filter() const
{
return filter_;
}
bool PathParameter::isFile() const
{
return is_file_;
}
bool PathParameter::isInput() const
{
return input_;
}
bool PathParameter::isOutput() const
{
return output_;
}
void PathParameter::serialize(SerializationBuffer &data) const
{
Parameter::serialize(data);
data << value_;
data << def_;
data << filter_;
data << is_file_;
data << input_;
data << output_;
}
void PathParameter::deserialize(const SerializationBuffer& data)
{
Parameter::deserialize(data);
data >> value_;
data >> def_;
data >> filter_;
data >> is_file_;
data >> input_;
data >> output_;
}
<commit_msg>Fix path parameter serialization bot being complete<commit_after>/// HEADER
#include <csapex/param/path_parameter.h>
/// PROJECT
#include <csapex/serialization/parameter_serializer.h>
#include <csapex/serialization/io/std_io.h>
/// SYSTEM
#include <yaml-cpp/yaml.h>
#include <boost/any.hpp>
CSAPEX_REGISTER_PARAMETER_SERIALIZER(PathParameter)
using namespace csapex;
using namespace param;
PathParameter::PathParameter()
: ParameterImplementation("noname", ParameterDescription())
{
}
PathParameter::PathParameter(const std::string &name, const ParameterDescription& description, const std::string &filter, bool is_file, bool input, bool output)
: ParameterImplementation(name, description), filter_(filter), is_file_(is_file), input_(input), output_(output)
{
}
PathParameter::~PathParameter()
{
}
const std::type_info& PathParameter::type() const
{
return typeid(std::string);
}
std::string PathParameter::toStringImpl() const
{
return std::string("[path: ") + value_ + "]";
}
void PathParameter::get_unsafe(boost::any& out) const
{
out = value_;
}
bool PathParameter::set_unsafe(const boost::any &v)
{
auto val = boost::any_cast<std::string>(v);
if(value_ != val) {
value_ = val;
return true;
}
return false;
}
void PathParameter::cloneDataFrom(const Clonable &other)
{
if(const PathParameter* path = dynamic_cast<const PathParameter*>(&other)) {
if(value_ != path->value_) {
*this = *path;
triggerChange();
}
} else {
throw std::runtime_error("bad setFrom, invalid types");
}
}
void PathParameter::doSerialize(YAML::Node& n) const
{
n["version"] = 2;
n["value"] = value_;
n["def"] = def_;
n["filter"] = filter_;
n["is_file"] = is_file_;
n["is_input"] = input_;
n["is_output"] = output_;
}
void PathParameter::doDeserialize(const YAML::Node& n)
{
int version = n["version"].IsDefined() ? n["version"].as<int>() : 1;
value_ = n["value"].as<std::string>();
if(version > 1) {
def_= n["def"].as<std::string>();
filter_= n["filter"].as<std::string>();
is_file_= n["is_file"].as<bool>();
input_= n["is_input"].as<bool>();
output_= n["is_output"].as<bool>();
}
}
std::string PathParameter::def() const
{
return def_;
}
std::string PathParameter::filter() const
{
return filter_;
}
bool PathParameter::isFile() const
{
return is_file_;
}
bool PathParameter::isInput() const
{
return input_;
}
bool PathParameter::isOutput() const
{
return output_;
}
void PathParameter::serialize(SerializationBuffer &data) const
{
Parameter::serialize(data);
data << value_;
data << def_;
data << filter_;
data << is_file_;
data << input_;
data << output_;
}
void PathParameter::deserialize(const SerializationBuffer& data)
{
Parameter::deserialize(data);
data >> value_;
data >> def_;
data >> filter_;
data >> is_file_;
data >> input_;
data >> output_;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2010 NorthScale, Inc.
*
* 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 "config.h"
#include "dispatcher.hh"
#include "objectregistry.hh"
extern "C" {
static void* launch_dispatcher_thread(void* arg);
}
static void* launch_dispatcher_thread(void *arg) {
Dispatcher *dispatcher = (Dispatcher*) arg;
try {
dispatcher->run();
} catch (std::exception& e) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Caught an exception: %s\n",
dispatcher->getName().c_str(), e.what());
} catch(...) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Caught a fatal exception\n",
dispatcher->getName().c_str());
}
return NULL;
}
void Dispatcher::start() {
assert(state == dispatcher_running);
if(pthread_create(&thread, NULL, launch_dispatcher_thread, this) != 0) {
std::stringstream ss;
ss << getName().c_str() << ": Initialization error!!!";
throw std::runtime_error(ss.str().c_str());
}
}
TaskId Dispatcher::nextTask() {
assert (!empty());
return readyQueue.empty() ? futureQueue.top() : readyQueue.top();
}
void Dispatcher::popNext() {
assert (!empty());
readyQueue.empty() ? futureQueue.pop() : readyQueue.pop();
}
void Dispatcher::moveReadyTasks(const struct timeval &tv) {
while (!futureQueue.empty()) {
TaskId tid = futureQueue.top();
if (less_tv(tid->waketime, tv)) {
readyQueue.push(tid);
futureQueue.pop();
} else {
// We found all the ready stuff.
return;
}
}
}
void Dispatcher::run() {
ObjectRegistry::onSwitchThread(&engine);
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Starting\n", getName().c_str());
for (;;) {
LockHolder lh(mutex);
// Having acquired the lock, verify our state and break out if
// it's changed.
if (state != dispatcher_running) {
break;
}
if (empty()) {
// Wait forever as long as the state didn't change while
// we grabbed the lock.
if (state == dispatcher_running) {
noTask();
mutex.wait();
}
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
// Get any ready tasks out of the due queue.
moveReadyTasks(tv);
TaskId task = nextTask();
assert(task);
LockHolder tlh(task->mutex);
if (task->state == task_dead) {
popNext();
continue;
}
if (less_tv(tv, task->waketime)) {
idleTask->setWaketime(task->waketime);
idleTask->setDispatcherNotifications(notifications.get());
task = idleTask;
taskDesc = task->getName();
} else {
// Otherwise, do the normal thing.
popNext();
taskDesc = task->getName();
}
tlh.unlock();
taskStart = gethrtime();
lh.unlock();
rel_time_t startReltime = ep_current_time();
try {
running_task = true;
if(task->run(*this, TaskId(task))) {
reschedule(task);
}
} catch (std::exception& e) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Exception caught in task \"%s\": %s\n",
getName().c_str(), task->getName().c_str(), e.what());
} catch(...) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Fatal exception caught in task \"%s\"\n",
getName().c_str(), task->getName().c_str());
}
running_task = false;
hrtime_t runtime((gethrtime() - taskStart) / 1000);
JobLogEntry jle(taskDesc, runtime, startReltime);
joblog.add(jle);
if (runtime > task->maxExpectedDuration()) {
slowjobs.add(jle);
}
}
}
completeNonDaemonTasks();
state = dispatcher_stopped;
notify();
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Exited\n", getName().c_str());
}
void Dispatcher::stop(bool force) {
LockHolder lh(mutex);
if (state == dispatcher_stopped || state == dispatcher_stopping) {
return;
}
forceTermination = force;
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Stopping\n", getName().c_str());
state = dispatcher_stopping;
notify();
lh.unlock();
pthread_join(thread, NULL);
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Stopped\n", getName().c_str());
}
void Dispatcher::schedule(shared_ptr<DispatcherCallback> callback,
TaskId *outtid,
const Priority &priority,
double sleeptime,
bool isDaemon,
bool mustComplete) {
LockHolder lh(mutex);
TaskId task(new Task(callback, priority.getPriorityValue(), sleeptime,
isDaemon, mustComplete));
if (outtid) {
*outtid = TaskId(task);
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Schedule a task \"%s\"",
getName().c_str(), task->getName().c_str());
futureQueue.push(task);
notify();
}
void Dispatcher::wake(TaskId task, TaskId *outtid) {
cancel(task);
LockHolder lh(mutex);
TaskId oldTask(task);
TaskId newTask(new Task(*oldTask));
if (outtid) {
*outtid = TaskId(task);
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Wake a task \"%s\"",
getName().c_str(), task->getName().c_str());
futureQueue.push(newTask);
notify();
}
void Dispatcher::snooze(TaskId t, double sleeptime) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Snooze a task \"%s\"",
getName().c_str(), t->getName().c_str());
t->snooze(sleeptime);
}
void Dispatcher::cancel(TaskId t) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Cancel a task \"%s\"",
getName().c_str(), t->getName().c_str());
t->cancel();
}
void Dispatcher::reschedule(TaskId task) {
// If the task is already in the queue it'll get run twice
LockHolder lh(mutex);
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Reschedule a task \"%s\"",
getName().c_str(), task->getName().c_str());
futureQueue.push(task);
notify();
}
void Dispatcher::completeNonDaemonTasks() {
LockHolder lh(mutex);
while (!empty()) {
TaskId task = nextTask();
popNext();
assert(task);
// Skip a daemon task
if (task->isDaemonTask) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s: Skipping daemon task \"%s\" during shutdown\n",
getName().c_str(), task->getName().c_str());
continue;
}
if (task->blockShutdown || !forceTermination) {
LockHolder tlh(task->mutex);
if (task->state == task_running) {
tlh.unlock();
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Running task \"%s\" during shutdown",
getName().c_str(), task->getName().c_str());
try {
while (task->run(*this, TaskId(task))) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Keep on running task \"%s\" during shutdown",
getName().c_str(), task->getName().c_str());
}
} catch (std::exception& e) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Exception caught in task \"%s\" "
"during shutdown: \"%s\"",
getName().c_str(), task->getName().c_str(), e.what());
} catch (...) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Fatal exception caught in task \"%s\" "
"during shutdown",
getName().c_str(), task->getName().c_str());
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Task \"%s\" completed during shutdown",
getName().c_str(), task->getName().c_str());
}
} else {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s: Skipping task \"%s\" during shutdown",
getName().c_str(), task->getName().c_str());
}
}
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s: Completed all the non-daemon tasks as part of shutdown\n",
getName().c_str());
}
bool IdleTask::run(Dispatcher &d, TaskId) {
LockHolder lh(d.mutex);
if (d.notifications.get() == dnotifications) {
d.mutex.wait(waketime);
}
return false;
}
<commit_msg>MB-4930 Dispatcher may deadlock itself during shutdown<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2010 NorthScale, Inc.
*
* 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 "config.h"
#include "dispatcher.hh"
#include "objectregistry.hh"
extern "C" {
static void* launch_dispatcher_thread(void* arg);
}
static void* launch_dispatcher_thread(void *arg) {
Dispatcher *dispatcher = (Dispatcher*) arg;
try {
dispatcher->run();
} catch (std::exception& e) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Caught an exception: %s\n",
dispatcher->getName().c_str(), e.what());
} catch(...) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Caught a fatal exception\n",
dispatcher->getName().c_str());
}
return NULL;
}
void Dispatcher::start() {
assert(state == dispatcher_running);
if(pthread_create(&thread, NULL, launch_dispatcher_thread, this) != 0) {
std::stringstream ss;
ss << getName().c_str() << ": Initialization error!!!";
throw std::runtime_error(ss.str().c_str());
}
}
TaskId Dispatcher::nextTask() {
assert (!empty());
return readyQueue.empty() ? futureQueue.top() : readyQueue.top();
}
void Dispatcher::popNext() {
assert (!empty());
readyQueue.empty() ? futureQueue.pop() : readyQueue.pop();
}
void Dispatcher::moveReadyTasks(const struct timeval &tv) {
while (!futureQueue.empty()) {
TaskId tid = futureQueue.top();
if (less_tv(tid->waketime, tv)) {
readyQueue.push(tid);
futureQueue.pop();
} else {
// We found all the ready stuff.
return;
}
}
}
void Dispatcher::run() {
ObjectRegistry::onSwitchThread(&engine);
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Starting\n", getName().c_str());
for (;;) {
LockHolder lh(mutex);
// Having acquired the lock, verify our state and break out if
// it's changed.
if (state != dispatcher_running) {
break;
}
if (empty()) {
// Wait forever as long as the state didn't change while
// we grabbed the lock.
if (state == dispatcher_running) {
noTask();
mutex.wait();
}
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
// Get any ready tasks out of the due queue.
moveReadyTasks(tv);
TaskId task = nextTask();
assert(task);
LockHolder tlh(task->mutex);
if (task->state == task_dead) {
popNext();
continue;
}
if (less_tv(tv, task->waketime)) {
idleTask->setWaketime(task->waketime);
idleTask->setDispatcherNotifications(notifications.get());
task = idleTask;
taskDesc = task->getName();
} else {
// Otherwise, do the normal thing.
popNext();
taskDesc = task->getName();
}
tlh.unlock();
taskStart = gethrtime();
lh.unlock();
rel_time_t startReltime = ep_current_time();
try {
running_task = true;
if(task->run(*this, TaskId(task))) {
reschedule(task);
}
} catch (std::exception& e) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Exception caught in task \"%s\": %s\n",
getName().c_str(), task->getName().c_str(), e.what());
} catch(...) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Fatal exception caught in task \"%s\"\n",
getName().c_str(), task->getName().c_str());
}
running_task = false;
hrtime_t runtime((gethrtime() - taskStart) / 1000);
JobLogEntry jle(taskDesc, runtime, startReltime);
joblog.add(jle);
if (runtime > task->maxExpectedDuration()) {
slowjobs.add(jle);
}
}
}
completeNonDaemonTasks();
state = dispatcher_stopped;
notify();
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Exited\n", getName().c_str());
}
void Dispatcher::stop(bool force) {
LockHolder lh(mutex);
if (state == dispatcher_stopped || state == dispatcher_stopping) {
return;
}
forceTermination = force;
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Stopping\n", getName().c_str());
state = dispatcher_stopping;
notify();
lh.unlock();
pthread_join(thread, NULL);
getLogger()->log(EXTENSION_LOG_INFO, NULL, "%s: Stopped\n", getName().c_str());
}
void Dispatcher::schedule(shared_ptr<DispatcherCallback> callback,
TaskId *outtid,
const Priority &priority,
double sleeptime,
bool isDaemon,
bool mustComplete)
{
// MB-4930 We might end up with a deadlock if some of the tasks try
// to reschedule new tasks during shutdown (while we're
// running completeNonDaemonTasks
if (state == dispatcher_stopping || state == dispatcher_stopped) {
return ;
}
LockHolder lh(mutex);
TaskId task(new Task(callback, priority.getPriorityValue(), sleeptime,
isDaemon, mustComplete));
if (outtid) {
*outtid = TaskId(task);
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Schedule a task \"%s\"",
getName().c_str(), task->getName().c_str());
futureQueue.push(task);
notify();
}
void Dispatcher::wake(TaskId task, TaskId *outtid) {
cancel(task);
LockHolder lh(mutex);
TaskId oldTask(task);
TaskId newTask(new Task(*oldTask));
if (outtid) {
*outtid = TaskId(task);
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Wake a task \"%s\"",
getName().c_str(), task->getName().c_str());
futureQueue.push(newTask);
notify();
}
void Dispatcher::snooze(TaskId t, double sleeptime) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Snooze a task \"%s\"",
getName().c_str(), t->getName().c_str());
t->snooze(sleeptime);
}
void Dispatcher::cancel(TaskId t) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Cancel a task \"%s\"",
getName().c_str(), t->getName().c_str());
t->cancel();
}
void Dispatcher::reschedule(TaskId task) {
// If the task is already in the queue it'll get run twice
LockHolder lh(mutex);
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Reschedule a task \"%s\"",
getName().c_str(), task->getName().c_str());
futureQueue.push(task);
notify();
}
void Dispatcher::completeNonDaemonTasks() {
LockHolder lh(mutex);
while (!empty()) {
TaskId task = nextTask();
popNext();
assert(task);
// Skip a daemon task
if (task->isDaemonTask) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s: Skipping daemon task \"%s\" during shutdown\n",
getName().c_str(), task->getName().c_str());
continue;
}
if (task->blockShutdown || !forceTermination) {
LockHolder tlh(task->mutex);
if (task->state == task_running) {
tlh.unlock();
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Running task \"%s\" during shutdown",
getName().c_str(), task->getName().c_str());
try {
while (task->run(*this, TaskId(task))) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Keep on running task \"%s\" during shutdown",
getName().c_str(), task->getName().c_str());
}
} catch (std::exception& e) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Exception caught in task \"%s\" "
"during shutdown: \"%s\"",
getName().c_str(), task->getName().c_str(), e.what());
} catch (...) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s: Fatal exception caught in task \"%s\" "
"during shutdown",
getName().c_str(), task->getName().c_str());
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s: Task \"%s\" completed during shutdown",
getName().c_str(), task->getName().c_str());
}
} else {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s: Skipping task \"%s\" during shutdown",
getName().c_str(), task->getName().c_str());
}
}
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s: Completed all the non-daemon tasks as part of shutdown\n",
getName().c_str());
}
bool IdleTask::run(Dispatcher &d, TaskId) {
LockHolder lh(d.mutex);
if (d.notifications.get() == dnotifications) {
d.mutex.wait(waketime);
}
return false;
}
<|endoftext|> |
<commit_before>//#define DEBUG_AGENT
#include "agent.hpp"
#include <atomic>
#include <cassert>
#include <cstdlib>
#include <chrono>
#include <functional>
#include <thread>
#include <QtCore/QCoreApplication>
#include <QtCore/QThread>
#include "agent_qtmonkey_communication.hpp"
#include "common.hpp"
#include "script.hpp"
#include "script_api.hpp"
#include "script_runner.hpp"
#include "user_events_analyzer.hpp"
using qt_monkey_agent::Agent;
using qt_monkey_agent::Private::PacketTypeForMonkey;
using qt_monkey_agent::Private::CommunicationAgentPart;
using qt_monkey_agent::Private::ScriptRunner;
Agent *Agent::gAgent_ = nullptr;
#define GET_THREAD(__name__) \
auto __name__ = static_cast<AgentThread *>(thread_); \
if (__name__->isFinished()) { \
return; \
}
#ifdef DEBUG_AGENT
#define DBGPRINT(fmt, ...) qDebug(fmt, __VA_ARGS__)
#else
#define DBGPRINT(fmt, ...) \
do { \
} while (false)
#endif
namespace
{
class FuncEvent final : public QEvent
{
public:
FuncEvent(QEvent::Type type, std::function<void()> func)
: QEvent(type), func_(std::move(func))
{
}
void exec() { func_(); }
private:
std::function<void()> func_;
};
class EventsReciever final : public QObject
{
public:
EventsReciever()
{
eventType_ = static_cast<QEvent::Type>(QEvent::registerEventType());
}
void customEvent(QEvent *event) override
{
if (event->type() != eventType_)
return;
static_cast<FuncEvent *>(event)->exec();
}
QEvent::Type eventType() const { return eventType_; }
private:
std::atomic<QEvent::Type> eventType_;
};
class AgentThread final : public QThread
{
public:
AgentThread(QObject *parent) : QThread(parent) {}
bool isNotReady() { return !ready_.exchange(false); }
void run() override
{
CommunicationAgentPart client;
if (!client.connectToMonkey()) {
qWarning(
"%s",
qPrintable(
T_("%1: can not connect to qt monkey").arg(Q_FUNC_INFO)));
return;
}
connect(&client, SIGNAL(error(const QString &)), parent(),
SLOT(onCommunicationError(const QString &)),
Qt::DirectConnection);
connect(&client,
SIGNAL(runScript(const qt_monkey_agent::Private::Script &)),
parent(), SLOT(onRunScriptCommand(
const qt_monkey_agent::Private::Script &)),
Qt::DirectConnection);
EventsReciever eventReciever;
objInThread_ = &eventReciever;
channelWithMonkey_ = &client;
ready_ = true;
exec();
}
CommunicationAgentPart *channelWithMonkey() { return channelWithMonkey_; }
void runInThread(std::function<void()> func)
{
assert(objInThread_ != nullptr);
QCoreApplication::postEvent(
objInThread_,
new FuncEvent(objInThread_->eventType(), std::move(func)));
}
private:
std::atomic<bool> ready_{false};
EventsReciever *objInThread_{nullptr};
CommunicationAgentPart *channelWithMonkey_{nullptr};
};
}
Agent::Agent(const QKeySequence &showObjectShortcut,
std::list<CustomEventAnalyzer> customEventAnalyzers,
PopulateScriptContext psc)
: eventAnalyzer_(new UserEventsAnalyzer(*this,
showObjectShortcut, std::move(customEventAnalyzers), this)),
populateScriptContextCallback_(std::move(psc))
{
// make sure that type is referenced, fix bug with qt4 and static lib
qMetaTypeId<qt_monkey_agent::Private::Script>();
eventType_ = static_cast<QEvent::Type>(QEvent::registerEventType());
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(onAppAboutToQuit()));
connect(eventAnalyzer_, SIGNAL(userEventInScriptForm(const QString &)),
this, SLOT(onUserEventInScriptForm(const QString &)));
connect(eventAnalyzer_, SIGNAL(scriptLog(const QString &)), this,
SLOT(onScriptLog(const QString &)));
QCoreApplication::instance()->installEventFilter(eventAnalyzer_);
thread_ = new AgentThread(this);
thread_->start();
while (!thread_->isFinished()
&& static_cast<AgentThread *>(thread_)->isNotReady())
;
assert(gAgent_ == nullptr);
gAgent_ = this;
}
void Agent::onCommunicationError(const QString &err)
{
qFatal("%s: communication error %s", Q_FUNC_INFO, qPrintable(err));
std::abort();
}
Agent::~Agent()
{
GET_THREAD(thread)
thread->runInThread(
[this, thread] { thread->channelWithMonkey()->flushSendData(); });
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000 /*ms*/);
thread->quit();
thread->wait();
}
void Agent::onUserEventInScriptForm(const QString &script)
{
if (script.isEmpty())
return;
GET_THREAD(thread)
thread->channelWithMonkey()->sendCommand(
PacketTypeForMonkey::NewUserAppEvent, script);
}
void Agent::onRunScriptCommand(const Private::Script &script)
{
GET_THREAD(thread)
assert(QThread::currentThread() == thread_);
DBGPRINT("%s: run script", Q_FUNC_INFO);
ScriptAPI api{*this};
ScriptRunner sr{api, populateScriptContextCallback_};
QString errMsg;
{
CurrentScriptContext context(&sr, curScriptRunner_);
sr.runScript(script, errMsg);
}
if (!errMsg.isEmpty()) {
qWarning("AGENT: %s: script return error", Q_FUNC_INFO);
thread->channelWithMonkey()->sendCommand(
PacketTypeForMonkey::ScriptError, errMsg);
} else {
DBGPRINT("%s: sync with gui", Q_FUNC_INFO);
// if all ok, sync with gui, so user recieve all events
// before script exit
runCodeInGuiThreadSync([] {
qt_monkey_common::processEventsFor(300 /*ms*/);
DBGPRINT("%s: wait done", Q_FUNC_INFO);
return QString();
});
}
DBGPRINT("%s: report about script end", Q_FUNC_INFO);
thread->channelWithMonkey()->sendCommand(PacketTypeForMonkey::ScriptEnd,
QString());
}
void Agent::sendToLog(QString msg)
{
DBGPRINT("%s: msg %s", Q_FUNC_INFO, qPrintable(msg));
GET_THREAD(thread)
thread->channelWithMonkey()->sendCommand(PacketTypeForMonkey::ScriptLog,
std::move(msg));
}
void Agent::scriptCheckPoint()
{
assert(QThread::currentThread() == thread_);
assert(curScriptRunner_ != nullptr);
const int lineno = curScriptRunner_->currentLineNum();
DBGPRINT("%s: lineno %d", Q_FUNC_INFO, lineno);
}
QString Agent::runCodeInGuiThreadSync(std::function<QString()> func)
{
assert(QThread::currentThread() == thread_);
QString res;
QCoreApplication::postEvent(this,
new FuncEvent(eventType_, [func, this, &res] {
res = func();
guiRunSem_.release();
}));
guiRunSem_.acquire();
return res;
}
void Agent::customEvent(QEvent *event)
{
assert(QThread::currentThread() != thread_);
if (event->type() != eventType_)
return;
static_cast<FuncEvent *>(event)->exec();
}
void Agent::throwScriptError(QString msg)
{
assert(QThread::currentThread() == thread_);
assert(curScriptRunner_ != nullptr);
curScriptRunner_->throwError(std::move(msg));
}
QString Agent::runCodeInGuiThreadSyncWithTimeout(std::function<QString()> func,
int timeoutSecs)
{
assert(QThread::currentThread() == thread_);
std::shared_ptr<QSemaphore> waitSem{new QSemaphore};
std::shared_ptr<QString> res{new QString};
QCoreApplication::postEvent(this,
new FuncEvent(eventType_, [func, waitSem, res] {
*res = func();
waitSem->release();
}));
const int timeoutMsec = timeoutSecs * 1000;
const int waitIntervalMsec = 100;
const int N = timeoutMsec / waitIntervalMsec + 1;
for (int attempt = 0; attempt < N; ++attempt) {
if (waitSem->tryAcquire(1, waitIntervalMsec))
return *res;
}
DBGPRINT("%s: timeout occuire", Q_FUNC_INFO);
return QString();
}
void Agent::onAppAboutToQuit()
{
qDebug("%s: begin", Q_FUNC_INFO);
qt_monkey_common::processEventsFor(300 /*ms*/);
}
void Agent::onScriptLog(const QString &msg)
{
assert(QThread::currentThread() != thread_);
GET_THREAD(thread)
thread->channelWithMonkey()->sendCommand(PacketTypeForMonkey::ScriptLog,
msg);
}
<commit_msg>change way how we handling events that may cause new event loop<commit_after>//#define DEBUG_AGENT
#include "agent.hpp"
#include <atomic>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <functional>
#include <thread>
#include <QApplication>
#include <QtCore/QAbstractEventDispatcher>
#include <QtCore/QThread>
#include "agent_qtmonkey_communication.hpp"
#include "common.hpp"
#include "script.hpp"
#include "script_api.hpp"
#include "script_runner.hpp"
#include "user_events_analyzer.hpp"
using qt_monkey_agent::Agent;
using qt_monkey_agent::Private::PacketTypeForMonkey;
using qt_monkey_agent::Private::CommunicationAgentPart;
using qt_monkey_agent::Private::ScriptRunner;
Agent *Agent::gAgent_ = nullptr;
#define GET_THREAD(__name__) \
auto __name__ = static_cast<AgentThread *>(thread_); \
if (__name__->isFinished()) { \
return; \
}
#ifdef DEBUG_AGENT
#define DBGPRINT(fmt, ...) qDebug(fmt, __VA_ARGS__)
#else
#define DBGPRINT(fmt, ...) \
do { \
} while (false)
#endif
namespace
{
class FuncEvent final : public QEvent
{
public:
FuncEvent(QEvent::Type type, std::function<void()> func)
: QEvent(type), func_(std::move(func))
{
}
void exec() { func_(); }
private:
std::function<void()> func_;
};
class EventsReciever final : public QObject
{
public:
EventsReciever()
{
eventType_ = static_cast<QEvent::Type>(QEvent::registerEventType());
}
void customEvent(QEvent *event) override
{
if (event->type() != eventType_)
return;
static_cast<FuncEvent *>(event)->exec();
}
QEvent::Type eventType() const { return eventType_; }
private:
std::atomic<QEvent::Type> eventType_;
};
class AgentThread final : public QThread
{
public:
AgentThread(QObject *parent) : QThread(parent) {}
bool isNotReady() { return !ready_.exchange(false); }
void run() override
{
CommunicationAgentPart client;
if (!client.connectToMonkey()) {
qWarning(
"%s",
qPrintable(
T_("%1: can not connect to qt monkey").arg(Q_FUNC_INFO)));
return;
}
connect(&client, SIGNAL(error(const QString &)), parent(),
SLOT(onCommunicationError(const QString &)),
Qt::DirectConnection);
connect(&client,
SIGNAL(runScript(const qt_monkey_agent::Private::Script &)),
parent(), SLOT(onRunScriptCommand(
const qt_monkey_agent::Private::Script &)),
Qt::DirectConnection);
EventsReciever eventReciever;
objInThread_ = &eventReciever;
channelWithMonkey_ = &client;
ready_ = true;
exec();
}
CommunicationAgentPart *channelWithMonkey() { return channelWithMonkey_; }
void runInThread(std::function<void()> func)
{
assert(objInThread_ != nullptr);
QCoreApplication::postEvent(
objInThread_,
new FuncEvent(objInThread_->eventType(), std::move(func)));
}
private:
std::atomic<bool> ready_{false};
EventsReciever *objInThread_{nullptr};
CommunicationAgentPart *channelWithMonkey_{nullptr};
};
}
Agent::Agent(const QKeySequence &showObjectShortcut,
std::list<CustomEventAnalyzer> customEventAnalyzers,
PopulateScriptContext psc)
: eventAnalyzer_(new UserEventsAnalyzer(
*this, showObjectShortcut, std::move(customEventAnalyzers), this)),
populateScriptContextCallback_(std::move(psc))
{
// make sure that type is referenced, fix bug with qt4 and static lib
qMetaTypeId<qt_monkey_agent::Private::Script>();
eventType_ = static_cast<QEvent::Type>(QEvent::registerEventType());
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(onAppAboutToQuit()));
connect(eventAnalyzer_, SIGNAL(userEventInScriptForm(const QString &)),
this, SLOT(onUserEventInScriptForm(const QString &)));
connect(eventAnalyzer_, SIGNAL(scriptLog(const QString &)), this,
SLOT(onScriptLog(const QString &)));
QCoreApplication::instance()->installEventFilter(eventAnalyzer_);
thread_ = new AgentThread(this);
thread_->start();
while (!thread_->isFinished()
&& static_cast<AgentThread *>(thread_)->isNotReady())
;
assert(gAgent_ == nullptr);
gAgent_ = this;
}
void Agent::onCommunicationError(const QString &err)
{
qFatal("%s: communication error %s", Q_FUNC_INFO, qPrintable(err));
std::abort();
}
Agent::~Agent()
{
GET_THREAD(thread)
thread->runInThread(
[this, thread] { thread->channelWithMonkey()->flushSendData(); });
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000 /*ms*/);
thread->quit();
thread->wait();
}
void Agent::onUserEventInScriptForm(const QString &script)
{
if (script.isEmpty())
return;
GET_THREAD(thread)
thread->channelWithMonkey()->sendCommand(
PacketTypeForMonkey::NewUserAppEvent, script);
}
void Agent::onRunScriptCommand(const Private::Script &script)
{
GET_THREAD(thread)
assert(QThread::currentThread() == thread_);
DBGPRINT("%s: run script", Q_FUNC_INFO);
ScriptAPI api{*this};
ScriptRunner sr{api, populateScriptContextCallback_};
QString errMsg;
{
CurrentScriptContext context(&sr, curScriptRunner_);
sr.runScript(script, errMsg);
}
if (!errMsg.isEmpty()) {
qWarning("AGENT: %s: script return error", Q_FUNC_INFO);
thread->channelWithMonkey()->sendCommand(
PacketTypeForMonkey::ScriptError, errMsg);
} else {
DBGPRINT("%s: sync with gui", Q_FUNC_INFO);
// if all ok, sync with gui, so user recieve all events
// before script exit
runCodeInGuiThreadSync([] {
qt_monkey_common::processEventsFor(300 /*ms*/);
DBGPRINT("%s: wait done", Q_FUNC_INFO);
return QString();
});
}
DBGPRINT("%s: report about script end", Q_FUNC_INFO);
thread->channelWithMonkey()->sendCommand(PacketTypeForMonkey::ScriptEnd,
QString());
}
void Agent::sendToLog(QString msg)
{
DBGPRINT("%s: msg %s", Q_FUNC_INFO, qPrintable(msg));
GET_THREAD(thread)
thread->channelWithMonkey()->sendCommand(PacketTypeForMonkey::ScriptLog,
std::move(msg));
}
void Agent::scriptCheckPoint()
{
assert(QThread::currentThread() == thread_);
assert(curScriptRunner_ != nullptr);
const int lineno = curScriptRunner_->currentLineNum();
DBGPRINT("%s: lineno %d", Q_FUNC_INFO, lineno);
}
QString Agent::runCodeInGuiThreadSync(std::function<QString()> func)
{
assert(QThread::currentThread() == thread_);
QString res;
QCoreApplication::postEvent(this,
new FuncEvent(eventType_, [func, this, &res] {
res = func();
guiRunSem_.release();
}));
guiRunSem_.acquire();
return res;
}
void Agent::customEvent(QEvent *event)
{
assert(QThread::currentThread() != thread_);
if (event->type() != eventType_)
return;
static_cast<FuncEvent *>(event)->exec();
}
void Agent::throwScriptError(QString msg)
{
assert(QThread::currentThread() == thread_);
assert(curScriptRunner_ != nullptr);
curScriptRunner_->throwError(std::move(msg));
}
QString Agent::runCodeInGuiThreadSyncWithTimeout(std::function<QString()> func,
int timeoutSecs)
{
assert(QThread::currentThread() == thread_);
QWidget *wasDialog = nullptr;
runCodeInGuiThreadSync([&wasDialog] {
wasDialog = qApp->activeModalWidget();
return QString();
});
std::shared_ptr<QSemaphore> waitSem{new QSemaphore};
std::shared_ptr<QString> res{new QString};
QCoreApplication::postEvent(this,
new FuncEvent(eventType_, [func, waitSem, res] {
*res = func();
waitSem->release();
}));
QWidget *nowDialog = nullptr;
runCodeInGuiThreadSync(
[&nowDialog] { /*this code send event internally, so
if new QEventLoop was created, it will
be executed after handling of event posted above
*/
auto dispatcher = QAbstractEventDispatcher::instance(
QThread::currentThread());
if (dispatcher == nullptr)
return QStringLiteral("no event dispatcher");
// if @func cause dialog close, then process all events,
// to prevent post of next event to QDialog's QEventLoop
dispatcher->processEvents(
QEventLoop::ExcludeUserInputEvents);
nowDialog = qApp->activeModalWidget();
return QString();
});
if (nowDialog != wasDialog) {
DBGPRINT("%s: dialog has changed\n", Q_FUNC_INFO);
// it may not return, if @func cause new QEventLoop creation, so
const int timeoutMsec = timeoutSecs * 1000;
const int waitIntervalMsec = 100;
const int N = timeoutMsec / waitIntervalMsec + 1;
for (int attempt = 0; attempt < N; ++attempt) {
if (waitSem->tryAcquire(1, waitIntervalMsec))
return *res;
}
DBGPRINT("%s: timeout occuire", Q_FUNC_INFO);
} else {
DBGPRINT("%s: wait of finished event handling", Q_FUNC_INFO);
waitSem->acquire();
DBGPRINT("%s: wait of finished event handling DONE", Q_FUNC_INFO);
}
return QString();
}
void Agent::onAppAboutToQuit()
{
qDebug("%s: begin", Q_FUNC_INFO);
qt_monkey_common::processEventsFor(300 /*ms*/);
}
void Agent::onScriptLog(const QString &msg)
{
assert(QThread::currentThread() != thread_);
GET_THREAD(thread)
thread->channelWithMonkey()->sendCommand(PacketTypeForMonkey::ScriptLog,
msg);
}
<|endoftext|> |
<commit_before>#ifndef STAN__AGRAD__FWD__FUNCTIONS__OWENS_T_HPP
#define STAN__AGRAD__FWD__FUNCTIONS__OWENS_T_HPP
#include <math.h>
#include <stan/agrad/fwd/fvar.hpp>
#include <stan/meta/traits.hpp>
#include <stan/math/constants.hpp>
#include <stan/math/functions/owens_t.hpp>
namespace stan {
namespace agrad {
template <typename T>
inline
fvar<T>
owens_t(const fvar<T>& x1, const fvar<T>& x2) {
using stan::math::owens_t;
using stan::math::pi;
using std::exp;
using ::erf;
T neg_x1_sq_div_2 = -x1.val_ * x1.val_ / 2.0;
T one_p_x2_sq = 1.0 + x2.val_ * x2.val_;
return fvar<T>(owens_t(x1.val_, x2.val_),
- x1.d_
* (erf(x2.val_ * x1.val_ / std::sqrt(2.0))
* exp(neg_x1_sq_div_2) / std::sqrt(8.0 * pi()))
+ x2.d_ * exp(neg_x1_sq_div_2 * one_p_x2_sq)
/ (one_p_x2_sq * 2.0 * pi()));
}
template <typename T>
inline
fvar<T>
owens_t(const double x1, const fvar<T>& x2) {
using stan::math::owens_t;
using stan::math::pi;
using std::exp;
T neg_x1_sq_div_2 = -x1 * x1 / 2.0;
T one_p_x2_sq = 1.0 + x2.val_ * x2.val_;
return fvar<T>(owens_t(x1, x2.val_),
x2.d_ * exp(neg_x1_sq_div_2 * one_p_x2_sq)
/ (one_p_x2_sq * 2.0 * pi()));
}
template <typename T>
inline
fvar<T>
owens_t(const fvar<T>& x1, const double x2) {
using stan::math::owens_t;
using stan::math::pi;
using std::exp;
using ::erf;
T neg_x1_sq_div_2 = -x1.val_ * x1.val_ / 2.0;
return fvar<T>(owens_t(x1.val_, x2),
-x1.d_ * (erf(x2 * x1.val_ / std::sqrt(2.0))
* exp(neg_x1_sq_div_2)
/ std::sqrt(8.0 * pi())));
}
}
}
#endif
<commit_msg>updating arithmetic in owens_t<commit_after>#ifndef STAN__AGRAD__FWD__FUNCTIONS__OWENS_T_HPP
#define STAN__AGRAD__FWD__FUNCTIONS__OWENS_T_HPP
#include <math.h>
#include <stan/agrad/fwd/fvar.hpp>
#include <stan/meta/traits.hpp>
#include <stan/math/constants.hpp>
#include <stan/math/functions/owens_t.hpp>
namespace stan {
namespace agrad {
template <typename T>
inline
fvar<T>
owens_t(const fvar<T>& x1, const fvar<T>& x2) {
using stan::math::owens_t;
using stan::math::pi;
using stan::math::INV_SQRT_2;
using stan::math::INV_SQRT_TWO_PI;
using stan::math::square;
using std::exp;
using ::erf;
T neg_x1_sq_div_2 = -square(x1.val_) * 0.5;
T one_p_x2_sq = 1.0 + square(x2.val_);
return fvar<T>(owens_t(x1.val_, x2.val_),
- x1.d_
* (erf(x2.val_ * x1.val_ * INV_SQRT_2)
* exp(neg_x1_sq_div_2) * INV_SQRT_TWO_PI * 0.5)
+ x2.d_ * exp(neg_x1_sq_div_2 * one_p_x2_sq)
/ (one_p_x2_sq * 2.0 * pi()));
}
template <typename T>
inline
fvar<T>
owens_t(const double x1, const fvar<T>& x2) {
using stan::math::owens_t;
using stan::math::pi;
using stan::math::square;
using std::exp;
T neg_x1_sq_div_2 = -square(x1) * 0.5;
T one_p_x2_sq = 1.0 + square(x2.val_);
return fvar<T>(owens_t(x1, x2.val_),
x2.d_ * exp(neg_x1_sq_div_2 * one_p_x2_sq)
/ (one_p_x2_sq * 2.0 * pi()));
}
template <typename T>
inline
fvar<T>
owens_t(const fvar<T>& x1, const double x2) {
using stan::math::owens_t;
using stan::math::pi;
using stan::math::square;
using stan::math::INV_SQRT_2;
using stan::math::INV_SQRT_TWO_PI;
using std::exp;
using ::erf;
T neg_x1_sq_div_2 = -square(x1.val_) * 0.5;
return fvar<T>(owens_t(x1.val_, x2),
-x1.d_ * (erf(x2 * x1.val_ * INV_SQRT_2)
* exp(neg_x1_sq_div_2)
* INV_SQRT_TWO_PI * 0.5));
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "sdlwrap.hpp"
#include <iostream>
namespace rs {
std::string SDLError::s_errString;
const char* SDLError::ErrorDesc() {
const char* err = SDL_GetError();
if(*err != '\0') {
s_errString = err;
SDL_ClearError();
return s_errString.c_str();
}
return nullptr;
}
const char* SDLError::GetAPIName() {
return "SDL";
}
namespace sdlw {
SDL_threadID thread_local tls_threadID(~0);
}
}
<commit_msg>tls_threadIDのnamespaceを修正<commit_after>#include "sdlwrap.hpp"
#include <iostream>
namespace rs {
std::string SDLError::s_errString;
const char* SDLError::ErrorDesc() {
const char* err = SDL_GetError();
if(*err != '\0') {
s_errString = err;
SDL_ClearError();
return s_errString.c_str();
}
return nullptr;
}
const char* SDLError::GetAPIName() {
return "SDL";
}
SDL_threadID thread_local tls_threadID(~0);
}
<|endoftext|> |
<commit_before>// @(#)root/core/meta:$Id$
// Author: Paul Russo 30/07/2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TClingTypeInfo //
// //
// Emulation of the CINT TypeInfo class. //
// //
// The CINT C++ interpreter provides an interface to metadata about //
// a type through the TypeInfo class. This class provides the same //
// functionality, using an interface as close as possible to TypeInfo //
// but the type metadata comes from the Clang C++ compiler, not CINT. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClingTypeInfo.h"
#include "TDictionary.h"
#include "Rtypes.h" // for gDebug
#include "TClassEdit.h"
#include "TMetaUtils.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Type.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/Frontend/CompilerInstance.h"
#include <cstdio>
#include <string>
using namespace std;
//______________________________________________________________________________
TClingTypeInfo::TClingTypeInfo(cling::Interpreter *interp, const char *name)
: fInterp(interp)
{
Init(name);
}
//______________________________________________________________________________
void TClingTypeInfo::Init(const char *name)
{
fQualType = clang::QualType();
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): looking up clang type: %s", name);
}
const cling::LookupHelper& lh = fInterp->getLookupHelper();
clang::QualType QT = lh.findType(name);
if (QT.isNull()) {
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): clang type not found: %s", name);
}
std::string buf = TClassEdit::InsertStd(name);
QT = lh.findType(buf);
if (QT.isNull()) {
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): "
"clang type not found name: %s\n", buf.c_str());
}
}
else {
fQualType = QT;
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): found clang type name: %s\n",
buf.c_str());
}
}
}
else {
fQualType = QT;
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): clang type found: %s\n", name);
}
}
}
//______________________________________________________________________________
const char *TClingTypeInfo::Name() const
{
if (!IsValid()) {
return 0;
}
// Note: This *must* be static because we are returning a pointer inside it!
static std::string buf;
buf.clear();
ROOT::TMetaUtils::GetFullyQualifiedTypeName(buf,fQualType,*fInterp);
return buf.c_str();
}
//______________________________________________________________________________
long TClingTypeInfo::Property() const
{
if (!IsValid()) {
return 0L;
}
long property = 0L;
if (llvm::isa<clang::TypedefType>(*fQualType)) {
property |= kIsTypedef;
}
clang::QualType QT = fQualType.getCanonicalType();
if (QT.isConstQualified()) {
property |= kIsConstant;
}
while (1) {
if (QT->isArrayType()) {
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
property |= kIsReference;
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
property |= kIsPointer;
if (QT.isConstQualified()) {
property |= kIsConstPointer;
}
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
if (QT->isBuiltinType()) {
property |= kIsFundamental;
}
if (QT.isConstQualified()) {
property |= kIsConstant;
}
const clang::TagType *tagQT = llvm::dyn_cast<clang::TagType>(QT.getTypePtr());
if (tagQT) {
// Note: Now we have class, enum, struct, union only.
const clang::TagDecl *TD = llvm::dyn_cast<clang::TagDecl>(tagQT->getDecl());
if (TD->isEnum()) {
property |= kIsEnum;
} else {
// Note: Now we have class, struct, union only.
const clang::CXXRecordDecl *CRD =
llvm::dyn_cast<clang::CXXRecordDecl>(TD);
if (CRD->isClass()) {
property |= kIsClass;
}
else if (CRD->isStruct()) {
property |= kIsStruct;
}
else if (CRD->isUnion()) {
property |= kIsUnion;
}
if (CRD->isThisDeclarationADefinition() && CRD->isAbstract()) {
property |= kIsAbstract;
}
}
}
return property;
}
//______________________________________________________________________________
int TClingTypeInfo::RefType() const
{
if (!IsValid()) {
return 0;
}
int cnt = 0;
bool is_ref = false;
clang::QualType QT = fQualType.getCanonicalType();
while (1) {
if (QT->isArrayType()) {
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
is_ref = true;
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
++cnt;
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
int val = 0;
if (cnt > 1) {
val = cnt;
}
if (is_ref) {
if (cnt < 2) {
val = kParaReference;
}
else {
val |= kParaRef;
}
}
return val;
}
//______________________________________________________________________________
int TClingTypeInfo::Size() const
{
if (!IsValid()) {
return 1;
}
if (fQualType->isDependentType()) {
// Dependent on a template parameter, we do not know what it is yet.
return 0;
}
if (const clang::RecordType *RT = fQualType->getAs<clang::RecordType>()) {
if (!RT->getDecl()->getDefinition()) {
// This is a forward-declared class.
return 0;
}
}
clang::ASTContext &Context = fInterp->getCI()->getASTContext();
// Note: This is an int64_t.
clang::CharUnits::QuantityType Quantity =
Context.getTypeSizeInChars(fQualType).getQuantity();
return static_cast<int>(Quantity);
}
//______________________________________________________________________________
const char *TClingTypeInfo::StemName() const
{
if (!IsValid()) {
return 0;
}
clang::QualType QT = fQualType.getCanonicalType();
while (1) {
if (QT->isArrayType()) {
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
// Note: This *must* be static because we are returning a pointer inside it.
static std::string buf;
buf.clear();
clang::PrintingPolicy Policy(fInterp->getCI()->getASTContext().
getPrintingPolicy());
QT.getAsStringInternal(buf, Policy);
return buf.c_str();
}
//______________________________________________________________________________
const char *TClingTypeInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
{
// Return the normalized name of the type (i.e. fully qualified and without
// the non-opaque typedefs.
if (!IsValid()) {
return 0;
}
// Note: This *must* be static because we are returning a pointer inside it.
static std::string buf;
buf.clear();
ROOT::TMetaUtils::GetNormalizedName(buf,fQualType, *fInterp, normCtxt);
return buf.c_str();
}
//______________________________________________________________________________
std::string TClingTypeInfo::NormalizedName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
{
// Return the normalized name of the type (i.e. fully qualified and without
// the non-opaque typedefs.
if (!IsValid()) {
return 0;
}
std::string buf;
ROOT::TMetaUtils::GetNormalizedName(buf,fQualType, *fInterp, normCtxt);
// in C++11 this will be efficient thanks to the move constructor.
return buf;
}
<commit_msg>Fix null pointer use in constructing string<commit_after>// @(#)root/core/meta:$Id$
// Author: Paul Russo 30/07/2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TClingTypeInfo //
// //
// Emulation of the CINT TypeInfo class. //
// //
// The CINT C++ interpreter provides an interface to metadata about //
// a type through the TypeInfo class. This class provides the same //
// functionality, using an interface as close as possible to TypeInfo //
// but the type metadata comes from the Clang C++ compiler, not CINT. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClingTypeInfo.h"
#include "TDictionary.h"
#include "Rtypes.h" // for gDebug
#include "TClassEdit.h"
#include "TMetaUtils.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Type.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/Frontend/CompilerInstance.h"
#include <cstdio>
#include <string>
using namespace std;
//______________________________________________________________________________
TClingTypeInfo::TClingTypeInfo(cling::Interpreter *interp, const char *name)
: fInterp(interp)
{
Init(name);
}
//______________________________________________________________________________
void TClingTypeInfo::Init(const char *name)
{
fQualType = clang::QualType();
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): looking up clang type: %s", name);
}
const cling::LookupHelper& lh = fInterp->getLookupHelper();
clang::QualType QT = lh.findType(name);
if (QT.isNull()) {
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): clang type not found: %s", name);
}
std::string buf = TClassEdit::InsertStd(name);
QT = lh.findType(buf);
if (QT.isNull()) {
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): "
"clang type not found name: %s\n", buf.c_str());
}
}
else {
fQualType = QT;
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): found clang type name: %s\n",
buf.c_str());
}
}
}
else {
fQualType = QT;
if (gDebug > 0) {
fprintf(stderr,
"TClingTypeInfo::Init(name): clang type found: %s\n", name);
}
}
}
//______________________________________________________________________________
const char *TClingTypeInfo::Name() const
{
if (!IsValid()) {
return 0;
}
// Note: This *must* be static because we are returning a pointer inside it!
static std::string buf;
buf.clear();
ROOT::TMetaUtils::GetFullyQualifiedTypeName(buf,fQualType,*fInterp);
return buf.c_str();
}
//______________________________________________________________________________
long TClingTypeInfo::Property() const
{
if (!IsValid()) {
return 0L;
}
long property = 0L;
if (llvm::isa<clang::TypedefType>(*fQualType)) {
property |= kIsTypedef;
}
clang::QualType QT = fQualType.getCanonicalType();
if (QT.isConstQualified()) {
property |= kIsConstant;
}
while (1) {
if (QT->isArrayType()) {
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
property |= kIsReference;
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
property |= kIsPointer;
if (QT.isConstQualified()) {
property |= kIsConstPointer;
}
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
if (QT->isBuiltinType()) {
property |= kIsFundamental;
}
if (QT.isConstQualified()) {
property |= kIsConstant;
}
const clang::TagType *tagQT = llvm::dyn_cast<clang::TagType>(QT.getTypePtr());
if (tagQT) {
// Note: Now we have class, enum, struct, union only.
const clang::TagDecl *TD = llvm::dyn_cast<clang::TagDecl>(tagQT->getDecl());
if (TD->isEnum()) {
property |= kIsEnum;
} else {
// Note: Now we have class, struct, union only.
const clang::CXXRecordDecl *CRD =
llvm::dyn_cast<clang::CXXRecordDecl>(TD);
if (CRD->isClass()) {
property |= kIsClass;
}
else if (CRD->isStruct()) {
property |= kIsStruct;
}
else if (CRD->isUnion()) {
property |= kIsUnion;
}
if (CRD->isThisDeclarationADefinition() && CRD->isAbstract()) {
property |= kIsAbstract;
}
}
}
return property;
}
//______________________________________________________________________________
int TClingTypeInfo::RefType() const
{
if (!IsValid()) {
return 0;
}
int cnt = 0;
bool is_ref = false;
clang::QualType QT = fQualType.getCanonicalType();
while (1) {
if (QT->isArrayType()) {
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
is_ref = true;
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
++cnt;
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
int val = 0;
if (cnt > 1) {
val = cnt;
}
if (is_ref) {
if (cnt < 2) {
val = kParaReference;
}
else {
val |= kParaRef;
}
}
return val;
}
//______________________________________________________________________________
int TClingTypeInfo::Size() const
{
if (!IsValid()) {
return 1;
}
if (fQualType->isDependentType()) {
// Dependent on a template parameter, we do not know what it is yet.
return 0;
}
if (const clang::RecordType *RT = fQualType->getAs<clang::RecordType>()) {
if (!RT->getDecl()->getDefinition()) {
// This is a forward-declared class.
return 0;
}
}
clang::ASTContext &Context = fInterp->getCI()->getASTContext();
// Note: This is an int64_t.
clang::CharUnits::QuantityType Quantity =
Context.getTypeSizeInChars(fQualType).getQuantity();
return static_cast<int>(Quantity);
}
//______________________________________________________________________________
const char *TClingTypeInfo::StemName() const
{
if (!IsValid()) {
return 0;
}
clang::QualType QT = fQualType.getCanonicalType();
while (1) {
if (QT->isArrayType()) {
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
// Note: This *must* be static because we are returning a pointer inside it.
static std::string buf;
buf.clear();
clang::PrintingPolicy Policy(fInterp->getCI()->getASTContext().
getPrintingPolicy());
QT.getAsStringInternal(buf, Policy);
return buf.c_str();
}
//______________________________________________________________________________
const char *TClingTypeInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
{
// Return the normalized name of the type (i.e. fully qualified and without
// the non-opaque typedefs.
if (!IsValid()) {
return 0;
}
// Note: This *must* be static because we are returning a pointer inside it.
static std::string buf;
buf.clear();
ROOT::TMetaUtils::GetNormalizedName(buf,fQualType, *fInterp, normCtxt);
return buf.c_str();
}
//______________________________________________________________________________
std::string TClingTypeInfo::NormalizedName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
{
// Return the normalized name of the type (i.e. fully qualified and without
// the non-opaque typedefs.
if (!IsValid()) {
return "";
}
std::string buf;
ROOT::TMetaUtils::GetNormalizedName(buf,fQualType, *fInterp, normCtxt);
// in C++11 this will be efficient thanks to the move constructor.
return buf;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT 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 <cstdarg>
#include <iostream>
#include <Common/Colorful.hh>
#include <Core/Chunk.hh>
#include <GC/GC.hh>
#include <Object/NativeObject.hh>
#include <Core/CallFrame.hh>
#include <Compiler/Compiler.hh>
#include <Builtin/Builtins.hh>
#include <Core/TadpoleVM.hh>
namespace Tadpole::Core {
TadpoleVM::TadpoleVM() noexcept {
gcompiler_ = new Compiler::GlobalCompiler();
stack_.reserve(kDefaultCap);
Builtin::register_builtins(*this);
GC::GC::get_instance().append_roots("TadpoleVM", this);
}
TadpoleVM::~TadpoleVM() {
delete gcompiler_;
globals_.clear();
}
void TadpoleVM::define_native(const str_t& name, Value::TadpoleCFun&& fn) {
globals_[name] = Object::NativeObject::create(std::move(fn));
}
InterpretRet TadpoleVM::interpret(const str_t& source_bytes) {
Object::FunctionObject* fn = gcompiler_->compile(*this, source_bytes);
if (fn == nullptr)
return InterpretRet::ECOMPILE;
// TODO:
return InterpretRet::OK;
}
void TadpoleVM::iter_objects(Object::ObjectVisitor&& visitor) {
// iterate Tadpole objects roots
gcompiler_->iter_objects(std::move(visitor));
for (auto& v : stack_)
visitor(v.as_object(safe_t()));
for (auto& f : frames_)
visitor(f.closure());
for (auto& g : globals_)
visitor(g.second.as_object(safe_t()));
for (auto* u = open_upvalues_; u != nullptr; u = u->next())
visitor(u);
}
void TadpoleVM::reset() {
stack_.clear();
frames_.clear();
open_upvalues_ = nullptr;
}
void TadpoleVM::runtime_error(const char* format, ...) {
std::cerr << Common::Colorful::fg::red << "Traceback (most recent call last):" << std::endl;
for (auto it = frames_.rbegin(); it != frames_.rend(); ++it) {
auto& frame = *it;
sz_t i = frame.frame_chunk()->offset_with(frame.ip()) - 1;
std::cerr
<< " [LINE: " << frame.frame_chunk()->get_line(i) << "] in "
<< "`" << frame.frame_fn()->name_asstr() << "()`"
<< std::endl;
}
va_list ap;
va_start(ap, format);
std::vfprintf(stderr, format, ap);
va_end(ap);
std::cerr << Common::Colorful::reset << std::endl;
reset();
}
void TadpoleVM::push(const Value::Value& value) noexcept {
stack_.push_back(value);
}
Value::Value TadpoleVM::pop() noexcept {
Value::Value value = stack_.back();
stack_.pop_back();
return value;
}
const Value::Value& TadpoleVM::peek(sz_t distance) const noexcept {
return stack_[stack_.size() - 1 - distance];
}
bool TadpoleVM::call(Object::ClosureObject* closure, sz_t nargs) {
Object::FunctionObject* fn = closure->fn();
if (fn->arity() != nargs) {
runtime_error("%s() takes exactly %u arguments (%u given)",
fn->name_asstr(), fn->arity(), nargs);
return false;
}
frames_.push_back({closure, fn->chunk()->codes(), stack_.size() - nargs - 1});
return true;
}
bool TadpoleVM::call(const Value::Value& callee, sz_t nargs) {
if (callee.is_object()) {
switch (callee.objtype()) {
case Object::ObjType::NATIVE:
{
Value::Value* args{};
if (nargs > 0 && stack_.size() > nargs)
args = &stack_[stack_.size() - nargs];
Value::Value result = callee.as_native()->call(nargs, args);
stack_.resize(stack_.size() - nargs - 1);
push(result);
return true;
}
case Object::ObjType::CLOSURE: return call(callee.as_closure(), nargs);
}
}
runtime_error("can only call function");
return false;
}
Object::UpvalueObject* TadpoleVM::capture_upvalue(Value::Value* local) {
if (open_upvalues_ == nullptr) {
open_upvalues_ = Object::UpvalueObject::create(local);
return open_upvalues_;
}
Object::UpvalueObject* upvalue = open_upvalues_;
Object::UpvalueObject* prev_upvalue = nullptr;
while (upvalue != nullptr && upvalue->value() > local) {
prev_upvalue = upvalue;
upvalue = upvalue->next();
}
if (upvalue != nullptr && upvalue->value() == local)
return upvalue;
Object::UpvalueObject* new_upvate = Object::UpvalueObject::create(local, upvalue);
if (prev_upvalue == nullptr)
open_upvalues_ = new_upvate;
else
prev_upvalue->set_next(new_upvate);
return new_upvate;
}
void TadpoleVM::close_upvalues(Value::Value* last) {
while (open_upvalues_ != nullptr && open_upvalues_->value() >= last) {
Object::UpvalueObject* upvalue = open_upvalues_;
upvalue->set_closed(upvalue->value_asref());
upvalue->set_value(upvalue->closed_asptr());
open_upvalues_ = upvalue->next();
}
}
InterpretRet TadpoleVM::run() {
CallFrame* frame = &frames_.back();
#define _RDBYTE() frame->inc_ip()
#define _RDCONST() frame->frame_chunk()->get_constant(_RDBYTE())
#define _RDSTR() _RDCONST().as_string()
#define _RDCSTR() _RDCONST().as_cstring()
#define _BINOP(op) do {\
if (!peek(0).is_numeric() || !peek(1).is_numeric()) {\
runtime_error("operands must be two numerics");\
return InterpretRet::ERUNTIME;\
}\
double b = pop().as_numeric();\
double a = pop().as_numeric();\
push(a op b);\
} while (false)
for (;;) {
#if defined(_TADPOLE_DEBUG_VM)
auto* frame_chunk = frame->frame_chunk();
std::cout << " ";
for (auto& v : stack_)
std::cout << "[" << Common::Colorful::fg::magenta << v << Common::Colorful::reset << "]";
std::cout << std::endl;
frame_chunk->dis_code(frame_chunk->offset_with(frame->ip()));
#endif
switch (Code c = Common::as_type<Code>(_RDBYTE())) {
case Code::CONSTANT: push(_RDCONST()); break;
default: break;
}
}
#undef _BINOP
#undef _RDCSTR
#undef _RDSTR
#undef _RDCONST
#undef _RDBYTE
return InterpretRet::OK;
}
}
<commit_msg>:construction: chore(vm): add implementation of vm<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT 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 <cstdarg>
#include <iostream>
#include <Common/Colorful.hh>
#include <Core/Chunk.hh>
#include <GC/GC.hh>
#include <Object/NativeObject.hh>
#include <Core/CallFrame.hh>
#include <Compiler/Compiler.hh>
#include <Builtin/Builtins.hh>
#include <Core/TadpoleVM.hh>
namespace Tadpole::Core {
TadpoleVM::TadpoleVM() noexcept {
gcompiler_ = new Compiler::GlobalCompiler();
stack_.reserve(kDefaultCap);
Builtin::register_builtins(*this);
GC::GC::get_instance().append_roots("TadpoleVM", this);
}
TadpoleVM::~TadpoleVM() {
delete gcompiler_;
globals_.clear();
}
void TadpoleVM::define_native(const str_t& name, Value::TadpoleCFun&& fn) {
globals_[name] = Object::NativeObject::create(std::move(fn));
}
InterpretRet TadpoleVM::interpret(const str_t& source_bytes) {
Object::FunctionObject* fn = gcompiler_->compile(*this, source_bytes);
if (fn == nullptr)
return InterpretRet::ECOMPILE;
// TODO:
return InterpretRet::OK;
}
void TadpoleVM::iter_objects(Object::ObjectVisitor&& visitor) {
// iterate Tadpole objects roots
gcompiler_->iter_objects(std::move(visitor));
for (auto& v : stack_)
visitor(v.as_object(safe_t()));
for (auto& f : frames_)
visitor(f.closure());
for (auto& g : globals_)
visitor(g.second.as_object(safe_t()));
for (auto* u = open_upvalues_; u != nullptr; u = u->next())
visitor(u);
}
void TadpoleVM::reset() {
stack_.clear();
frames_.clear();
open_upvalues_ = nullptr;
}
void TadpoleVM::runtime_error(const char* format, ...) {
std::cerr << Common::Colorful::fg::red << "Traceback (most recent call last):" << std::endl;
for (auto it = frames_.rbegin(); it != frames_.rend(); ++it) {
auto& frame = *it;
sz_t i = frame.frame_chunk()->offset_with(frame.ip()) - 1;
std::cerr
<< " [LINE: " << frame.frame_chunk()->get_line(i) << "] in "
<< "`" << frame.frame_fn()->name_asstr() << "()`"
<< std::endl;
}
va_list ap;
va_start(ap, format);
std::vfprintf(stderr, format, ap);
va_end(ap);
std::cerr << Common::Colorful::reset << std::endl;
reset();
}
void TadpoleVM::push(const Value::Value& value) noexcept {
stack_.push_back(value);
}
Value::Value TadpoleVM::pop() noexcept {
Value::Value value = stack_.back();
stack_.pop_back();
return value;
}
const Value::Value& TadpoleVM::peek(sz_t distance) const noexcept {
return stack_[stack_.size() - 1 - distance];
}
bool TadpoleVM::call(Object::ClosureObject* closure, sz_t nargs) {
Object::FunctionObject* fn = closure->fn();
if (fn->arity() != nargs) {
runtime_error("%s() takes exactly %u arguments (%u given)",
fn->name_asstr(), fn->arity(), nargs);
return false;
}
frames_.push_back({closure, fn->chunk()->codes(), stack_.size() - nargs - 1});
return true;
}
bool TadpoleVM::call(const Value::Value& callee, sz_t nargs) {
if (callee.is_object()) {
switch (callee.objtype()) {
case Object::ObjType::NATIVE:
{
Value::Value* args{};
if (nargs > 0 && stack_.size() > nargs)
args = &stack_[stack_.size() - nargs];
Value::Value result = callee.as_native()->call(nargs, args);
stack_.resize(stack_.size() - nargs - 1);
push(result);
return true;
}
case Object::ObjType::CLOSURE: return call(callee.as_closure(), nargs);
}
}
runtime_error("can only call function");
return false;
}
Object::UpvalueObject* TadpoleVM::capture_upvalue(Value::Value* local) {
if (open_upvalues_ == nullptr) {
open_upvalues_ = Object::UpvalueObject::create(local);
return open_upvalues_;
}
Object::UpvalueObject* upvalue = open_upvalues_;
Object::UpvalueObject* prev_upvalue = nullptr;
while (upvalue != nullptr && upvalue->value() > local) {
prev_upvalue = upvalue;
upvalue = upvalue->next();
}
if (upvalue != nullptr && upvalue->value() == local)
return upvalue;
Object::UpvalueObject* new_upvate = Object::UpvalueObject::create(local, upvalue);
if (prev_upvalue == nullptr)
open_upvalues_ = new_upvate;
else
prev_upvalue->set_next(new_upvate);
return new_upvate;
}
void TadpoleVM::close_upvalues(Value::Value* last) {
while (open_upvalues_ != nullptr && open_upvalues_->value() >= last) {
Object::UpvalueObject* upvalue = open_upvalues_;
upvalue->set_closed(upvalue->value_asref());
upvalue->set_value(upvalue->closed_asptr());
open_upvalues_ = upvalue->next();
}
}
InterpretRet TadpoleVM::run() {
CallFrame* frame = &frames_.back();
#define _RDBYTE() frame->inc_ip()
#define _RDCONST() frame->frame_chunk()->get_constant(_RDBYTE())
#define _RDSTR() _RDCONST().as_string()
#define _RDCSTR() _RDCONST().as_cstring()
#define _BINOP(op) do {\
if (!peek(0).is_numeric() || !peek(1).is_numeric()) {\
runtime_error("operands must be two numerics");\
return InterpretRet::ERUNTIME;\
}\
double b = pop().as_numeric();\
double a = pop().as_numeric();\
push(a op b);\
} while (false)
for (;;) {
#if defined(_TADPOLE_DEBUG_VM)
auto* frame_chunk = frame->frame_chunk();
std::cout << " ";
for (auto& v : stack_)
std::cout << "[" << Common::Colorful::fg::magenta << v << Common::Colorful::reset << "]";
std::cout << std::endl;
frame_chunk->dis_code(frame_chunk->offset_with(frame->ip()));
#endif
switch (Code c = Common::as_type<Code>(_RDBYTE())) {
case Code::CONSTANT: push(_RDCONST()); break;
case Code::NIL: push(nullptr); break;
case Code::FALSE: push(false); break;
case Code::TRUE: push(true); break;
case Code::POP: pop(); break;
default: break;
}
}
#undef _BINOP
#undef _RDCSTR
#undef _RDSTR
#undef _RDCONST
#undef _RDBYTE
return InterpretRet::OK;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT 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 <Common/Harness.hh>
#include <Lex/Lexer.hh>
TADPOLE_TEST(TadpoleLexer) {
using TK = Tadpole::Lex::TokenKind;
#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)
#define DUMPLEX() do {\
for (;;) {\
auto t = lex.next_token();\
std::fprintf(stdout, "%-24s | %-32s | %d\n",\
Tadpole::Lex::get_kind_name(t.kind()),\
t.as_cstring(),\
t.lineno());\
if (t.kind() == TK::TK_EOF)\
break;\
}\
} while (false)
#undef DUMPLEX
#undef TESTEQ
}
<commit_msg>:white_check_mark: test(lexer): updated the test for lexer<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT 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 <Common/Harness.hh>
#include <Lex/Lexer.hh>
TADPOLE_TEST(TadpoleLexer) {
using TK = Tadpole::Lex::TokenKind;
#define TESTEQ(k) TADPOLE_CHECK_EQ(lex.next_token().kind(), k)
#define DUMPLEX() do {\
for (;;) {\
auto t = lex.next_token();\
std::fprintf(stdout, "%-24s | %-32s | %d\n",\
Tadpole::Lex::get_kind_name(t.kind()),\
t.as_cstring(),\
t.lineno());\
if (t.kind() == TK::TK_EOF)\
break;\
}\
} while (false)
{
std::string s =
"print(\"Hello, world !\")";
Tadpole::Lex::Lexer lex(s);
DUMPLEX();
}
#undef DUMPLEX
#undef TESTEQ
}
<|endoftext|> |
<commit_before>/* slave_banker.cc
Jeremy Barnes, 8 November 2012
Copyright (c) 2012 Datacratic Inc. All rights reserved.
Slave banker implementation.
*/
#include "slave_banker.h"
#include "jml/utils/vector_utils.h"
using namespace std;
static constexpr int MaximumFailSyncSeconds = 3;
namespace RTBKIT {
/*****************************************************************************/
/* SLAVE BUDGET CONTROLLER */
/*****************************************************************************/
SlaveBudgetController::
SlaveBudgetController()
{
}
void
SlaveBudgetController::
addAccount(const AccountKey & account,
const OnBudgetResult & onResult)
{
applicationLayer->addAccount(account, onResult);
}
void
SlaveBudgetController::
topupTransfer(const AccountKey & account,
CurrencyPool amount,
const OnBudgetResult & onResult)
{
applicationLayer->topupTransfer(account, AT_BUDGET, amount, onResult);
}
void
SlaveBudgetController::
setBudget(const std::string & topLevelAccount,
CurrencyPool amount,
const OnBudgetResult & onResult)
{
applicationLayer->setBudget(topLevelAccount, amount, onResult);
}
void
SlaveBudgetController::
addBudget(const std::string & topLevelAccount,
CurrencyPool amount,
const OnBudgetResult & onResult)
{
throw ML::Exception("addBudget no good any more");
}
void
SlaveBudgetController::
getAccountList(const AccountKey & account,
int depth,
std::function<void (std::exception_ptr,
std::vector<AccountKey> &&)>)
{
throw ML::Exception("getAccountList not needed anymore");
}
void
SlaveBudgetController::
getAccountSummary(const AccountKey & account,
int depth,
std::function<void (std::exception_ptr,
AccountSummary &&)> onResult)
{
applicationLayer->getAccountSummary(account, depth, onResult);
}
void
SlaveBudgetController::
getAccount(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
Account &&)> onResult)
{
applicationLayer->getAccount(accountKey, onResult);
}
/*****************************************************************************/
/* SLAVE BANKER */
/*****************************************************************************/
SlaveBanker::
SlaveBanker(const std::string & accountSuffix, CurrencyPool spendRate)
: createdAccounts(128), reauthorizing(false), numReauthorized(0)
{
init(accountSuffix, spendRate);
}
void
SlaveBanker::
init(const std::string & accountSuffix, CurrencyPool spendRate)
{
if (accountSuffix.empty()) {
throw ML::Exception("'accountSuffix' cannot be empty");
}
if (spendRate.isZero()) {
throw ML::Exception("'spendRate' can not be zero");
}
// When our account manager creates an account, it will call this
// function. We can't do anything from it (because the lock could
// be held), but we *can* push a message asynchronously to be
// handled later...
accounts.onNewAccount = [=] (const AccountKey & accountKey)
{
//cerr << "((((1)))) new account " << accountKey << endl;
createdAccounts.push(accountKey);
};
// ... here. Now we know that no lock is held and so we can
// perform the work we need to synchronize the account with
// the server.
createdAccounts.onEvent = [=] (const AccountKey & accountKey)
{
//cerr << "((((2)))) new account " << accountKey << endl;
auto onDone = [=] (std::exception_ptr exc,
ShadowAccount && account)
{
#if 0
cerr << "((((3)))) new account " << accountKey << endl;
cerr << "got back shadow account " << account
<< " for " << accountKey << endl;
cerr << "current status is " << accounts.getAccount(accountKey)
<< endl;
#endif
};
addSpendAccount(accountKey, USD(0), onDone);
};
addSource("SlaveBanker::createdAccounts", createdAccounts);
this->accountSuffix = accountSuffix;
this->spendRate = spendRate;
lastSync = lastReauthorize = Date::now();
addPeriodic("SlaveBanker::reportSpend", 1.0,
std::bind(&SlaveBanker::reportSpend,
this,
std::placeholders::_1),
true /* single threaded */);
addPeriodic("SlaveBanker::reauthorizeBudget", 1.0,
std::bind(&SlaveBanker::reauthorizeBudget,
this,
std::placeholders::_1),
true /* single threaded */);
}
ShadowAccount
SlaveBanker::
syncAccountSync(const AccountKey & account)
{
BankerSyncResult<ShadowAccount> result;
syncAccount(account, result);
return result.get();
}
void
SlaveBanker::
onSyncResult(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
ShadowAccount &&)> onDone,
std::exception_ptr exc,
Account&& masterAccount)
{
ShadowAccount result;
try {
if (exc) {
onDone(exc, std::move(result));
return;
}
//cerr << "got result from master for " << accountKey
// << " which is "
// << masterAccount << endl;
result = accounts.syncFromMaster(accountKey, masterAccount);
} catch (...) {
onDone(std::current_exception(), std::move(result));
}
try {
onDone(nullptr, std::move(result));
} catch (...) {
cerr << "warning: onDone handler threw" << endl;
}
}
void
SlaveBanker::
onInitializeResult(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
ShadowAccount &&)> onDone,
std::exception_ptr exc,
Account&& masterAccount)
{
ShadowAccount result;
try {
if (exc) {
onDone(exc, std::move(result));
return;
}
result = accounts.initializeAndMergeState(accountKey, masterAccount);
} catch (...) {
onDone(std::current_exception(), std::move(result));
}
try {
onDone(nullptr, std::move(result));
} catch (...) {
cerr << "warning: onDone handler threw" << endl;
}
}
void
SlaveBanker::
syncAccount(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
ShadowAccount &&)> onDone)
{
auto onDone2
= std::bind(&SlaveBanker::onSyncResult,
this,
accountKey,
onDone,
std::placeholders::_1,
std::placeholders::_2);
//cerr << "syncing account " << accountKey << ": "
// << accounts.getAccount(accountKey) << endl;
applicationLayer->syncAccount(
accounts.getAccount(accountKey),
getShadowAccountStr(accountKey),
onDone2);
}
void
SlaveBanker::
syncAllSync()
{
BankerSyncResult<void> result;
syncAll(result);
result.get();
}
void
SlaveBanker::
syncAll(std::function<void (std::exception_ptr)> onDone)
{
auto allKeys = accounts.getAccountKeys();
vector<AccountKey> filteredKeys;
for (auto k: allKeys)
if (accounts.isInitialized(k))
filteredKeys.push_back(k);
allKeys.swap(filteredKeys);
if (allKeys.empty()) {
// We need some kind of synchronization here because the lastSync
// member variable will also be read in the context of an other
// MessageLoop (the MonitorProviderClient). Thus, if we want to avoid
// data-race here, we grab a lock.
std::lock_guard<Lock> guard(syncLock);
lastSync = Date::now();
if (onDone)
onDone(nullptr);
return;
}
struct Aggregator {
Aggregator(SlaveBanker *self, int numTotal,
std::function<void (std::exception_ptr)> onDone)
: itl(new Itl())
{
itl->self = self;
itl->numTotal = numTotal;
itl->numFinished = 0;
itl->exc = nullptr;
itl->onDone = onDone;
}
struct Itl {
SlaveBanker *self;
int numTotal;
int numFinished;
std::exception_ptr exc;
std::function<void (std::exception_ptr)> onDone;
};
std::shared_ptr<Itl> itl;
void operator () (std::exception_ptr exc, ShadowAccount && account)
{
if (exc)
itl->exc = exc;
int nowDone = __sync_add_and_fetch(&itl->numFinished, 1);
if (nowDone == itl->numTotal) {
if (!itl->exc) {
std::lock_guard<Lock> guard(itl->self->syncLock);
itl->self->lastSync = Date::now();
}
if (itl->onDone)
itl->onDone(itl->exc);
else {
if (itl->exc)
cerr << "warning: async callback aggregator ate "
<< "exception" << endl;
}
}
}
};
Aggregator aggregator(const_cast<SlaveBanker *>(this), allKeys.size(), onDone);
//cerr << "syncing " << allKeys.size() << " keys" << endl;
for (auto & key: allKeys) {
// We take its parent since syncAccount assumes nothing was added
if (accounts.isInitialized(key))
syncAccount(key, aggregator);
}
}
void
SlaveBanker::
addSpendAccount(const AccountKey & accountKey,
CurrencyPool accountFloat,
std::function<void (std::exception_ptr, ShadowAccount&&)> onDone)
{
bool first = accounts.createAccountAtomic(accountKey);
if(!first) {
// already done
if (onDone) {
auto account = accounts.getAccount(accountKey);
onDone(nullptr, std::move(account));
}
}
else {
// TODO: record float
//accountFloats[accountKey] = accountFloat;
// Now kick off the initial synchronization step
auto onDone2 = std::bind(&SlaveBanker::onInitializeResult,
this,
accountKey,
onDone,
std::placeholders::_1,
std::placeholders::_2);
cerr << "********* calling addSpendAccount for " << accountKey
<< " for SlaveBanker " << accountSuffix << endl;
applicationLayer->addSpendAccount(getShadowAccountStr(accountKey), onDone2);
}
}
void
SlaveBanker::
reportSpend(uint64_t numTimeoutsExpired)
{
if (numTimeoutsExpired > 1) {
cerr << "warning: slave banker missed " << numTimeoutsExpired
<< " timeouts" << endl;
}
if (reportSpendSent != Date())
cerr << "warning: report spend still in progress" << endl;
//cerr << "started report spend" << endl;
auto onDone = [=] (std::exception_ptr exc)
{
//cerr << "finished report spend" << endl;
reportSpendSent = Date();
if (exc)
cerr << "reportSpend got exception" << endl;
};
syncAll(onDone);
}
void
SlaveBanker::
reauthorizeBudget(uint64_t numTimeoutsExpired)
{
if (numTimeoutsExpired > 1) {
cerr << "warning: slave banker missed " << numTimeoutsExpired
<< " timeouts" << endl;
}
//std::unique_lock<Lock> guard(lock);
if (reauthorizing) {
cerr << "warning: reauthorize budget still in progress" << endl;
return;
}
accountsLeft = 0;
// For each of our accounts, we report back what has been spent
// and re-up to our desired float
auto onAccount = [&] (const AccountKey & key,
const ShadowAccount & account)
{
Json::Value payload = spendRate.toJson();
auto onDone = std::bind(&SlaveBanker::onReauthorizeBudgetMessage, this,
key,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3);
accountsLeft++;
// Finally, send it out
applicationLayer->request(
"POST", "/v1/accounts/" + getShadowAccountStr(key) + "/balance",
{ { "accountType", "spend" } },
payload.toString(),
onDone);
};
accounts.forEachInitializedAccount(onAccount);
if (accountsLeft > 0) {
reauthorizing = true;
reauthorizeDate = Date::now();
}
}
void
SlaveBanker::
onReauthorizeBudgetMessage(const AccountKey & accountKey,
std::exception_ptr exc,
int responseCode,
const std::string & payload)
{
if (exc) {
cerr << "reauthorize budget got exception" << payload << endl;
cerr << "accountKey = " << accountKey << endl;
return;
}
else if (responseCode == 200) {
Account masterAccount = Account::fromJson(Json::parse(payload));
accounts.syncFromMaster(accountKey, masterAccount);
}
reauthorizeBudgetSent = Date();
accountsLeft--;
if (accountsLeft == 0) {
lastReauthorizeDelay = Date::now() - reauthorizeDate;
numReauthorized++;
reauthorizing = false;
std::lock_guard<Lock> guard(syncLock);
lastReauthorize = Date::now();
}
}
void
SlaveBanker::
waitReauthorized()
const
{
while (reauthorizing) {
ML::sleep(0.2);
}
}
MonitorIndicator
SlaveBanker::
getProviderIndicators() const
{
Date now = Date::now();
// See syncAll for the reason of this lock
std::lock_guard<Lock> guard(syncLock);
bool syncOk = now < lastSync.plusSeconds(MaximumFailSyncSeconds) &&
now < lastReauthorize.plusSeconds(MaximumFailSyncSeconds);
MonitorIndicator ind;
ind.serviceName = accountSuffix;
ind.status = syncOk;
ind.message = string() + "Sync with MasterBanker: " + (syncOk ? "OK" : "ERROR");
return ind;
}
const CurrencyPool SlaveBanker::DefaultSpendRate = CurrencyPool(USD(0.10));
} // namespace RTBKIT
<commit_msg>Tentative fix to prevent the slave bankers from being stuck re-authorizing a budget when the master banker returns an error.<commit_after>/* slave_banker.cc
Jeremy Barnes, 8 November 2012
Copyright (c) 2012 Datacratic Inc. All rights reserved.
Slave banker implementation.
*/
#include "slave_banker.h"
#include "jml/utils/vector_utils.h"
using namespace std;
static constexpr int MaximumFailSyncSeconds = 3;
namespace RTBKIT {
/*****************************************************************************/
/* SLAVE BUDGET CONTROLLER */
/*****************************************************************************/
SlaveBudgetController::
SlaveBudgetController()
{
}
void
SlaveBudgetController::
addAccount(const AccountKey & account,
const OnBudgetResult & onResult)
{
applicationLayer->addAccount(account, onResult);
}
void
SlaveBudgetController::
topupTransfer(const AccountKey & account,
CurrencyPool amount,
const OnBudgetResult & onResult)
{
applicationLayer->topupTransfer(account, AT_BUDGET, amount, onResult);
}
void
SlaveBudgetController::
setBudget(const std::string & topLevelAccount,
CurrencyPool amount,
const OnBudgetResult & onResult)
{
applicationLayer->setBudget(topLevelAccount, amount, onResult);
}
void
SlaveBudgetController::
addBudget(const std::string & topLevelAccount,
CurrencyPool amount,
const OnBudgetResult & onResult)
{
throw ML::Exception("addBudget no good any more");
}
void
SlaveBudgetController::
getAccountList(const AccountKey & account,
int depth,
std::function<void (std::exception_ptr,
std::vector<AccountKey> &&)>)
{
throw ML::Exception("getAccountList not needed anymore");
}
void
SlaveBudgetController::
getAccountSummary(const AccountKey & account,
int depth,
std::function<void (std::exception_ptr,
AccountSummary &&)> onResult)
{
applicationLayer->getAccountSummary(account, depth, onResult);
}
void
SlaveBudgetController::
getAccount(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
Account &&)> onResult)
{
applicationLayer->getAccount(accountKey, onResult);
}
/*****************************************************************************/
/* SLAVE BANKER */
/*****************************************************************************/
SlaveBanker::
SlaveBanker(const std::string & accountSuffix, CurrencyPool spendRate)
: createdAccounts(128), reauthorizing(false), numReauthorized(0)
{
init(accountSuffix, spendRate);
}
void
SlaveBanker::
init(const std::string & accountSuffix, CurrencyPool spendRate)
{
if (accountSuffix.empty()) {
throw ML::Exception("'accountSuffix' cannot be empty");
}
if (spendRate.isZero()) {
throw ML::Exception("'spendRate' can not be zero");
}
// When our account manager creates an account, it will call this
// function. We can't do anything from it (because the lock could
// be held), but we *can* push a message asynchronously to be
// handled later...
accounts.onNewAccount = [=] (const AccountKey & accountKey)
{
//cerr << "((((1)))) new account " << accountKey << endl;
createdAccounts.push(accountKey);
};
// ... here. Now we know that no lock is held and so we can
// perform the work we need to synchronize the account with
// the server.
createdAccounts.onEvent = [=] (const AccountKey & accountKey)
{
//cerr << "((((2)))) new account " << accountKey << endl;
auto onDone = [=] (std::exception_ptr exc,
ShadowAccount && account)
{
#if 0
cerr << "((((3)))) new account " << accountKey << endl;
cerr << "got back shadow account " << account
<< " for " << accountKey << endl;
cerr << "current status is " << accounts.getAccount(accountKey)
<< endl;
#endif
};
addSpendAccount(accountKey, USD(0), onDone);
};
addSource("SlaveBanker::createdAccounts", createdAccounts);
this->accountSuffix = accountSuffix;
this->spendRate = spendRate;
lastSync = lastReauthorize = Date::now();
addPeriodic("SlaveBanker::reportSpend", 1.0,
std::bind(&SlaveBanker::reportSpend,
this,
std::placeholders::_1),
true /* single threaded */);
addPeriodic("SlaveBanker::reauthorizeBudget", 1.0,
std::bind(&SlaveBanker::reauthorizeBudget,
this,
std::placeholders::_1),
true /* single threaded */);
}
ShadowAccount
SlaveBanker::
syncAccountSync(const AccountKey & account)
{
BankerSyncResult<ShadowAccount> result;
syncAccount(account, result);
return result.get();
}
void
SlaveBanker::
onSyncResult(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
ShadowAccount &&)> onDone,
std::exception_ptr exc,
Account&& masterAccount)
{
ShadowAccount result;
try {
if (exc) {
onDone(exc, std::move(result));
return;
}
//cerr << "got result from master for " << accountKey
// << " which is "
// << masterAccount << endl;
result = accounts.syncFromMaster(accountKey, masterAccount);
} catch (...) {
onDone(std::current_exception(), std::move(result));
}
try {
onDone(nullptr, std::move(result));
} catch (...) {
cerr << "warning: onDone handler threw" << endl;
}
}
void
SlaveBanker::
onInitializeResult(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
ShadowAccount &&)> onDone,
std::exception_ptr exc,
Account&& masterAccount)
{
ShadowAccount result;
try {
if (exc) {
onDone(exc, std::move(result));
return;
}
result = accounts.initializeAndMergeState(accountKey, masterAccount);
} catch (...) {
onDone(std::current_exception(), std::move(result));
}
try {
onDone(nullptr, std::move(result));
} catch (...) {
cerr << "warning: onDone handler threw" << endl;
}
}
void
SlaveBanker::
syncAccount(const AccountKey & accountKey,
std::function<void (std::exception_ptr,
ShadowAccount &&)> onDone)
{
auto onDone2
= std::bind(&SlaveBanker::onSyncResult,
this,
accountKey,
onDone,
std::placeholders::_1,
std::placeholders::_2);
//cerr << "syncing account " << accountKey << ": "
// << accounts.getAccount(accountKey) << endl;
applicationLayer->syncAccount(
accounts.getAccount(accountKey),
getShadowAccountStr(accountKey),
onDone2);
}
void
SlaveBanker::
syncAllSync()
{
BankerSyncResult<void> result;
syncAll(result);
result.get();
}
void
SlaveBanker::
syncAll(std::function<void (std::exception_ptr)> onDone)
{
auto allKeys = accounts.getAccountKeys();
vector<AccountKey> filteredKeys;
for (auto k: allKeys)
if (accounts.isInitialized(k))
filteredKeys.push_back(k);
allKeys.swap(filteredKeys);
if (allKeys.empty()) {
// We need some kind of synchronization here because the lastSync
// member variable will also be read in the context of an other
// MessageLoop (the MonitorProviderClient). Thus, if we want to avoid
// data-race here, we grab a lock.
std::lock_guard<Lock> guard(syncLock);
lastSync = Date::now();
if (onDone)
onDone(nullptr);
return;
}
struct Aggregator {
Aggregator(SlaveBanker *self, int numTotal,
std::function<void (std::exception_ptr)> onDone)
: itl(new Itl())
{
itl->self = self;
itl->numTotal = numTotal;
itl->numFinished = 0;
itl->exc = nullptr;
itl->onDone = onDone;
}
struct Itl {
SlaveBanker *self;
int numTotal;
int numFinished;
std::exception_ptr exc;
std::function<void (std::exception_ptr)> onDone;
};
std::shared_ptr<Itl> itl;
void operator () (std::exception_ptr exc, ShadowAccount && account)
{
if (exc)
itl->exc = exc;
int nowDone = __sync_add_and_fetch(&itl->numFinished, 1);
if (nowDone == itl->numTotal) {
if (!itl->exc) {
std::lock_guard<Lock> guard(itl->self->syncLock);
itl->self->lastSync = Date::now();
}
if (itl->onDone)
itl->onDone(itl->exc);
else {
if (itl->exc)
cerr << "warning: async callback aggregator ate "
<< "exception" << endl;
}
}
}
};
Aggregator aggregator(const_cast<SlaveBanker *>(this), allKeys.size(), onDone);
//cerr << "syncing " << allKeys.size() << " keys" << endl;
for (auto & key: allKeys) {
// We take its parent since syncAccount assumes nothing was added
if (accounts.isInitialized(key))
syncAccount(key, aggregator);
}
}
void
SlaveBanker::
addSpendAccount(const AccountKey & accountKey,
CurrencyPool accountFloat,
std::function<void (std::exception_ptr, ShadowAccount&&)> onDone)
{
bool first = accounts.createAccountAtomic(accountKey);
if(!first) {
// already done
if (onDone) {
auto account = accounts.getAccount(accountKey);
onDone(nullptr, std::move(account));
}
}
else {
// TODO: record float
//accountFloats[accountKey] = accountFloat;
// Now kick off the initial synchronization step
auto onDone2 = std::bind(&SlaveBanker::onInitializeResult,
this,
accountKey,
onDone,
std::placeholders::_1,
std::placeholders::_2);
cerr << "********* calling addSpendAccount for " << accountKey
<< " for SlaveBanker " << accountSuffix << endl;
applicationLayer->addSpendAccount(getShadowAccountStr(accountKey), onDone2);
}
}
void
SlaveBanker::
reportSpend(uint64_t numTimeoutsExpired)
{
if (numTimeoutsExpired > 1) {
cerr << "warning: slave banker missed " << numTimeoutsExpired
<< " timeouts" << endl;
}
if (reportSpendSent != Date())
cerr << "warning: report spend still in progress" << endl;
//cerr << "started report spend" << endl;
auto onDone = [=] (std::exception_ptr exc)
{
//cerr << "finished report spend" << endl;
reportSpendSent = Date();
if (exc)
cerr << "reportSpend got exception" << endl;
};
syncAll(onDone);
}
void
SlaveBanker::
reauthorizeBudget(uint64_t numTimeoutsExpired)
{
if (numTimeoutsExpired > 1) {
cerr << "warning: slave banker missed " << numTimeoutsExpired
<< " timeouts" << endl;
}
//std::unique_lock<Lock> guard(lock);
if (reauthorizing) {
cerr << "warning: reauthorize budget still in progress" << endl;
return;
}
accountsLeft = 0;
// For each of our accounts, we report back what has been spent
// and re-up to our desired float
auto onAccount = [&] (const AccountKey & key,
const ShadowAccount & account)
{
Json::Value payload = spendRate.toJson();
auto onDone = std::bind(&SlaveBanker::onReauthorizeBudgetMessage, this,
key,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3);
accountsLeft++;
// Finally, send it out
applicationLayer->request(
"POST", "/v1/accounts/" + getShadowAccountStr(key) + "/balance",
{ { "accountType", "spend" } },
payload.toString(),
onDone);
};
accounts.forEachInitializedAccount(onAccount);
if (accountsLeft > 0) {
reauthorizing = true;
reauthorizeDate = Date::now();
}
}
void
SlaveBanker::
onReauthorizeBudgetMessage(const AccountKey & accountKey,
std::exception_ptr exc,
int responseCode,
const std::string & payload)
{
accountsLeft--;
if (exc) {
cerr << "reauthorize budget got exception" << payload << endl;
cerr << "accountKey = " << accountKey << endl;
return;
}
else if (responseCode == 200) {
Account masterAccount = Account::fromJson(Json::parse(payload));
accounts.syncFromMaster(accountKey, masterAccount);
}
reauthorizeBudgetSent = Date();
if (accountsLeft == 0) {
lastReauthorizeDelay = Date::now() - reauthorizeDate;
numReauthorized++;
reauthorizing = false;
std::lock_guard<Lock> guard(syncLock);
lastReauthorize = Date::now();
}
}
void
SlaveBanker::
waitReauthorized()
const
{
while (reauthorizing) {
ML::sleep(0.2);
}
}
MonitorIndicator
SlaveBanker::
getProviderIndicators() const
{
Date now = Date::now();
// See syncAll for the reason of this lock
std::lock_guard<Lock> guard(syncLock);
bool syncOk = now < lastSync.plusSeconds(MaximumFailSyncSeconds) &&
now < lastReauthorize.plusSeconds(MaximumFailSyncSeconds);
MonitorIndicator ind;
ind.serviceName = accountSuffix;
ind.status = syncOk;
ind.message = string() + "Sync with MasterBanker: " + (syncOk ? "OK" : "ERROR");
return ind;
}
const CurrencyPool SlaveBanker::DefaultSpendRate = CurrencyPool(USD(0.10));
} // namespace RTBKIT
<|endoftext|> |
<commit_before><commit_msg>Scale Bias post processor for ARM (#5795)<commit_after><|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.
*/
#include "ShadowNode.h"
#include "ShadowNodeFragment.h"
#include <better/small_vector.h>
#include <react/core/ComponentDescriptor.h>
#include <react/core/ShadowNodeFragment.h>
#include <react/debug/DebugStringConvertible.h>
#include <react/debug/debugStringConvertibleUtils.h>
namespace facebook {
namespace react {
SharedShadowNodeSharedList ShadowNode::emptySharedShadowNodeSharedList() {
static const auto emptySharedShadowNodeSharedList =
std::make_shared<SharedShadowNodeList>();
return emptySharedShadowNodeSharedList;
}
bool ShadowNode::sameFamily(const ShadowNode &first, const ShadowNode &second) {
return first.family_ == second.family_;
}
static int computeStateRevision(
State::Shared const &state,
SharedShadowNodeSharedList const &children) {
int fragmentStateRevision = state ? state->getRevision() : 0;
int childrenSum = 0;
if (children) {
for (auto const &child : *children) {
childrenSum += child->getStateRevision();
}
}
return fragmentStateRevision + childrenSum;
}
#pragma mark - Constructors
ShadowNode::ShadowNode(
ShadowNodeFragment const &fragment,
ShadowNodeFamily::Shared const &family,
ShadowNodeTraits traits)
:
#if RN_DEBUG_STRING_CONVERTIBLE
revision_(1),
#endif
props_(fragment.props),
children_(
fragment.children ? fragment.children
: emptySharedShadowNodeSharedList()),
state_(fragment.state),
orderIndex_(0),
stateRevision_(computeStateRevision(state_, children_)),
family_(family),
traits_(traits) {
assert(props_);
assert(children_);
traits_.set(ShadowNodeTraits::Trait::ChildrenAreShared);
for (auto const &child : *children_) {
child->family_->setParent(family_);
}
// The first node of the family gets its state committed automatically.
family_->setMostRecentState(state_);
}
ShadowNode::ShadowNode(
const ShadowNode &sourceShadowNode,
const ShadowNodeFragment &fragment)
:
#if RN_DEBUG_STRING_CONVERTIBLE
revision_(sourceShadowNode.revision_ + 1),
#endif
props_(fragment.props ? fragment.props : sourceShadowNode.props_),
children_(
fragment.children ? fragment.children : sourceShadowNode.children_),
state_(
fragment.state ? fragment.state
: sourceShadowNode.getMostRecentState()),
orderIndex_(sourceShadowNode.orderIndex_),
stateRevision_(computeStateRevision(state_, children_)),
family_(sourceShadowNode.family_),
traits_(sourceShadowNode.traits_) {
assert(props_);
assert(children_);
traits_.set(ShadowNodeTraits::Trait::ChildrenAreShared);
if (fragment.children) {
for (const auto &child : *children_) {
child->family_->setParent(family_);
}
}
}
UnsharedShadowNode ShadowNode::clone(const ShadowNodeFragment &fragment) const {
return family_->componentDescriptor_.cloneShadowNode(*this, fragment);
}
#pragma mark - Getters
ComponentName ShadowNode::getComponentName() const {
return family_->getComponentName();
}
ComponentHandle ShadowNode::getComponentHandle() const {
return family_->getComponentHandle();
}
const SharedShadowNodeList &ShadowNode::getChildren() const {
return *children_;
}
ShadowNodeTraits ShadowNode::getTraits() const {
return traits_;
}
const SharedProps &ShadowNode::getProps() const {
return props_;
}
const SharedEventEmitter &ShadowNode::getEventEmitter() const {
return family_->eventEmitter_;
}
Tag ShadowNode::getTag() const {
return family_->tag_;
}
SurfaceId ShadowNode::getSurfaceId() const {
return family_->surfaceId_;
}
const ComponentDescriptor &ShadowNode::getComponentDescriptor() const {
return family_->componentDescriptor_;
}
const State::Shared &ShadowNode::getState() const {
return state_;
}
State::Shared ShadowNode::getMostRecentState() const {
return family_->getMostRecentState();
}
int ShadowNode::getOrderIndex() const {
return orderIndex_;
}
void ShadowNode::sealRecursive() const {
if (getSealed()) {
return;
}
seal();
props_->seal();
for (auto child : *children_) {
child->sealRecursive();
}
}
#pragma mark - Mutating Methods
void ShadowNode::appendChild(const ShadowNode::Shared &child) {
ensureUnsealed();
cloneChildrenIfShared();
auto nonConstChildren =
std::const_pointer_cast<SharedShadowNodeList>(children_);
nonConstChildren->push_back(child);
child->family_->setParent(family_);
stateRevision_ += child->getStateRevision();
}
void ShadowNode::replaceChild(
ShadowNode const &oldChild,
ShadowNode::Shared const &newChild,
int suggestedIndex) {
ensureUnsealed();
stateRevision_ += newChild->getStateRevision() - oldChild.getStateRevision();
cloneChildrenIfShared();
newChild->family_->setParent(family_);
auto &children =
*std::const_pointer_cast<ShadowNode::ListOfShared>(children_);
auto size = children.size();
if (suggestedIndex != -1 && suggestedIndex < size) {
// If provided `suggestedIndex` is accurate,
// replacing in place using the index.
if (children.at(suggestedIndex).get() == &oldChild) {
children[suggestedIndex] = newChild;
return;
}
}
for (auto index = 0; index < size; index++) {
if (children.at(index).get() == &oldChild) {
children[index] = newChild;
return;
}
}
assert(false && "Child to replace was not found.");
}
void ShadowNode::cloneChildrenIfShared() {
if (!traits_.check(ShadowNodeTraits::Trait::ChildrenAreShared)) {
return;
}
traits_.unset(ShadowNodeTraits::Trait::ChildrenAreShared);
children_ = std::make_shared<SharedShadowNodeList>(*children_);
}
void ShadowNode::setMounted(bool mounted) const {
if (mounted) {
family_->setMostRecentState(getState());
}
family_->eventEmitter_->setEnabled(mounted);
}
ShadowNodeFamily const &ShadowNode::getFamily() const {
return *family_;
}
int ShadowNode::getStateRevision() const {
return stateRevision_;
}
ShadowNode::Unshared ShadowNode::cloneTree(
ShadowNodeFamily const &shadowNodeFamily,
std::function<ShadowNode::Unshared(ShadowNode const &oldShadowNode)>
callback) const {
auto ancestors = shadowNodeFamily.getAncestors(*this);
if (ancestors.size() == 0) {
return ShadowNode::Unshared{nullptr};
}
auto &parent = ancestors.back();
auto &oldShadowNode = parent.first.get().getChildren().at(parent.second);
auto newShadowNode = callback(*oldShadowNode);
auto childNode = newShadowNode;
for (auto it = ancestors.rbegin(); it != ancestors.rend(); ++it) {
auto &parentNode = it->first.get();
auto childIndex = it->second;
auto children = parentNode.getChildren();
assert(ShadowNode::sameFamily(*children.at(childIndex), *childNode));
children[childIndex] = childNode;
childNode = parentNode.clone({
ShadowNodeFragment::propsPlaceholder(),
std::make_shared<SharedShadowNodeList>(children),
});
}
return std::const_pointer_cast<ShadowNode>(childNode);
}
#pragma mark - DebugStringConvertible
#if RN_DEBUG_STRING_CONVERTIBLE
std::string ShadowNode::getDebugName() const {
return getComponentName();
}
std::string ShadowNode::getDebugValue() const {
return "r" + folly::to<std::string>(revision_) + "/sr" +
folly::to<std::string>(stateRevision_) + "/s" +
folly::to<std::string>(state_ ? state_->getRevision() : 0) +
(getSealed() ? "/sealed" : "");
}
SharedDebugStringConvertibleList ShadowNode::getDebugChildren() const {
auto debugChildren = SharedDebugStringConvertibleList{};
for (auto child : *children_) {
auto debugChild =
std::dynamic_pointer_cast<const DebugStringConvertible>(child);
if (debugChild) {
debugChildren.push_back(debugChild);
}
}
return debugChildren;
}
SharedDebugStringConvertibleList ShadowNode::getDebugProps() const {
return props_->getDebugProps() +
SharedDebugStringConvertibleList{
debugStringConvertibleItem("tag", folly::to<std::string>(getTag()))};
}
#endif
} // namespace react
} // namespace facebook
<commit_msg>Fabric: Added assert in ShadowNode<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.
*/
#include "ShadowNode.h"
#include "ShadowNodeFragment.h"
#include <better/small_vector.h>
#include <react/core/ComponentDescriptor.h>
#include <react/core/ShadowNodeFragment.h>
#include <react/debug/DebugStringConvertible.h>
#include <react/debug/debugStringConvertibleUtils.h>
namespace facebook {
namespace react {
SharedShadowNodeSharedList ShadowNode::emptySharedShadowNodeSharedList() {
static const auto emptySharedShadowNodeSharedList =
std::make_shared<SharedShadowNodeList>();
return emptySharedShadowNodeSharedList;
}
bool ShadowNode::sameFamily(const ShadowNode &first, const ShadowNode &second) {
return first.family_ == second.family_;
}
static int computeStateRevision(
State::Shared const &state,
SharedShadowNodeSharedList const &children) {
int fragmentStateRevision = state ? state->getRevision() : 0;
int childrenSum = 0;
if (children) {
for (auto const &child : *children) {
childrenSum += child->getStateRevision();
}
}
return fragmentStateRevision + childrenSum;
}
#pragma mark - Constructors
ShadowNode::ShadowNode(
ShadowNodeFragment const &fragment,
ShadowNodeFamily::Shared const &family,
ShadowNodeTraits traits)
:
#if RN_DEBUG_STRING_CONVERTIBLE
revision_(1),
#endif
props_(fragment.props),
children_(
fragment.children ? fragment.children
: emptySharedShadowNodeSharedList()),
state_(fragment.state),
orderIndex_(0),
stateRevision_(computeStateRevision(state_, children_)),
family_(family),
traits_(traits) {
assert(props_);
assert(children_);
traits_.set(ShadowNodeTraits::Trait::ChildrenAreShared);
for (auto const &child : *children_) {
child->family_->setParent(family_);
}
// The first node of the family gets its state committed automatically.
family_->setMostRecentState(state_);
}
ShadowNode::ShadowNode(
const ShadowNode &sourceShadowNode,
const ShadowNodeFragment &fragment)
:
#if RN_DEBUG_STRING_CONVERTIBLE
revision_(sourceShadowNode.revision_ + 1),
#endif
props_(fragment.props ? fragment.props : sourceShadowNode.props_),
children_(
fragment.children ? fragment.children : sourceShadowNode.children_),
state_(
fragment.state ? fragment.state
: sourceShadowNode.getMostRecentState()),
orderIndex_(sourceShadowNode.orderIndex_),
stateRevision_(computeStateRevision(state_, children_)),
family_(sourceShadowNode.family_),
traits_(sourceShadowNode.traits_) {
assert(props_);
assert(children_);
traits_.set(ShadowNodeTraits::Trait::ChildrenAreShared);
if (fragment.children) {
for (const auto &child : *children_) {
child->family_->setParent(family_);
}
}
}
UnsharedShadowNode ShadowNode::clone(const ShadowNodeFragment &fragment) const {
return family_->componentDescriptor_.cloneShadowNode(*this, fragment);
}
#pragma mark - Getters
ComponentName ShadowNode::getComponentName() const {
return family_->getComponentName();
}
ComponentHandle ShadowNode::getComponentHandle() const {
return family_->getComponentHandle();
}
const SharedShadowNodeList &ShadowNode::getChildren() const {
return *children_;
}
ShadowNodeTraits ShadowNode::getTraits() const {
return traits_;
}
const SharedProps &ShadowNode::getProps() const {
return props_;
}
const SharedEventEmitter &ShadowNode::getEventEmitter() const {
return family_->eventEmitter_;
}
Tag ShadowNode::getTag() const {
return family_->tag_;
}
SurfaceId ShadowNode::getSurfaceId() const {
return family_->surfaceId_;
}
const ComponentDescriptor &ShadowNode::getComponentDescriptor() const {
return family_->componentDescriptor_;
}
const State::Shared &ShadowNode::getState() const {
return state_;
}
State::Shared ShadowNode::getMostRecentState() const {
return family_->getMostRecentState();
}
int ShadowNode::getOrderIndex() const {
return orderIndex_;
}
void ShadowNode::sealRecursive() const {
if (getSealed()) {
return;
}
seal();
props_->seal();
for (auto child : *children_) {
child->sealRecursive();
}
}
#pragma mark - Mutating Methods
void ShadowNode::appendChild(const ShadowNode::Shared &child) {
ensureUnsealed();
cloneChildrenIfShared();
auto nonConstChildren =
std::const_pointer_cast<SharedShadowNodeList>(children_);
nonConstChildren->push_back(child);
child->family_->setParent(family_);
stateRevision_ += child->getStateRevision();
}
void ShadowNode::replaceChild(
ShadowNode const &oldChild,
ShadowNode::Shared const &newChild,
int suggestedIndex) {
ensureUnsealed();
stateRevision_ += newChild->getStateRevision() - oldChild.getStateRevision();
cloneChildrenIfShared();
newChild->family_->setParent(family_);
auto &children =
*std::const_pointer_cast<ShadowNode::ListOfShared>(children_);
auto size = children.size();
if (suggestedIndex != -1 && suggestedIndex < size) {
// If provided `suggestedIndex` is accurate,
// replacing in place using the index.
if (children.at(suggestedIndex).get() == &oldChild) {
children[suggestedIndex] = newChild;
return;
}
}
for (auto index = 0; index < size; index++) {
if (children.at(index).get() == &oldChild) {
children[index] = newChild;
return;
}
}
assert(false && "Child to replace was not found.");
}
void ShadowNode::cloneChildrenIfShared() {
if (!traits_.check(ShadowNodeTraits::Trait::ChildrenAreShared)) {
return;
}
traits_.unset(ShadowNodeTraits::Trait::ChildrenAreShared);
children_ = std::make_shared<SharedShadowNodeList>(*children_);
}
void ShadowNode::setMounted(bool mounted) const {
if (mounted) {
family_->setMostRecentState(getState());
}
family_->eventEmitter_->setEnabled(mounted);
}
ShadowNodeFamily const &ShadowNode::getFamily() const {
return *family_;
}
int ShadowNode::getStateRevision() const {
return stateRevision_;
}
ShadowNode::Unshared ShadowNode::cloneTree(
ShadowNodeFamily const &shadowNodeFamily,
std::function<ShadowNode::Unshared(ShadowNode const &oldShadowNode)>
callback) const {
auto ancestors = shadowNodeFamily.getAncestors(*this);
if (ancestors.size() == 0) {
return ShadowNode::Unshared{nullptr};
}
auto &parent = ancestors.back();
auto &oldShadowNode = parent.first.get().getChildren().at(parent.second);
auto newShadowNode = callback(*oldShadowNode);
assert(
newShadowNode &&
"`callback` returned `nullptr` which is not allowed value.");
auto childNode = newShadowNode;
for (auto it = ancestors.rbegin(); it != ancestors.rend(); ++it) {
auto &parentNode = it->first.get();
auto childIndex = it->second;
auto children = parentNode.getChildren();
assert(ShadowNode::sameFamily(*children.at(childIndex), *childNode));
children[childIndex] = childNode;
childNode = parentNode.clone({
ShadowNodeFragment::propsPlaceholder(),
std::make_shared<SharedShadowNodeList>(children),
});
}
return std::const_pointer_cast<ShadowNode>(childNode);
}
#pragma mark - DebugStringConvertible
#if RN_DEBUG_STRING_CONVERTIBLE
std::string ShadowNode::getDebugName() const {
return getComponentName();
}
std::string ShadowNode::getDebugValue() const {
return "r" + folly::to<std::string>(revision_) + "/sr" +
folly::to<std::string>(stateRevision_) + "/s" +
folly::to<std::string>(state_ ? state_->getRevision() : 0) +
(getSealed() ? "/sealed" : "");
}
SharedDebugStringConvertibleList ShadowNode::getDebugChildren() const {
auto debugChildren = SharedDebugStringConvertibleList{};
for (auto child : *children_) {
auto debugChild =
std::dynamic_pointer_cast<const DebugStringConvertible>(child);
if (debugChild) {
debugChildren.push_back(debugChild);
}
}
return debugChildren;
}
SharedDebugStringConvertibleList ShadowNode::getDebugProps() const {
return props_->getDebugProps() +
SharedDebugStringConvertibleList{
debugStringConvertibleItem("tag", folly::to<std::string>(getTag()))};
}
#endif
} // namespace react
} // namespace facebook
<|endoftext|> |
<commit_before>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "player_service.h"
#include "swganh/logger.h"
#include "swganh/event_dispatcher.h"
#include "swganh/service/service_description.h"
#include "swganh/service/service_manager.h"
#include "swganh_core/connection/connection_client_interface.h"
#include "swganh_core/object/player/player.h"
#include "swganh_core/object/creature/creature.h"
#include "swganh_core/object/object_controller.h"
#include "swganh_core/messages/system_message.h"
#include "swganh_core/messages/out_of_band.h"
#include "swganh_core/messages/opened_container_message.h"
#include "swganh_core/simulation/simulation_service_interface.h"
#include "swganh_core/equipment/equipment_service.h"
#include "swganh_core/messages/controllers/add_buff.h"
#include "swganh_core/combat/buff_interface.h"
#include "swganh/database/database_manager.h"
#include <cppconn/exception.h>
#include <cppconn/connection.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/sqlstring.h>
using namespace std;
using namespace swganh;
using namespace swganh::service;
using namespace swganh::player;
using namespace swganh::object;
using namespace swganh::messages;
PlayerService::PlayerService(swganh::app::SwganhKernel* kernel)
: kernel_(kernel)
{
kernel_->GetEventDispatcher()->Subscribe(
"ObjectReadyEvent",
[this] (shared_ptr<EventInterface> incoming_event)
{
auto creature = static_pointer_cast<ValueEvent<shared_ptr<Creature>>>(incoming_event)->Get();
//Reload buffs from last login
auto controller = creature->GetController();
auto object_id = creature->GetObjectId();
//Resend buffs we current have left over
creature->ViewBuffs([&, this] (std::pair<boost::posix_time::ptime, std::shared_ptr<swganh::combat::BuffInterface>> entry) {
uint32_t duration = (entry.first - boost::posix_time::second_clock::local_time()).total_seconds();
swganh::messages::controllers::AddBuffMessage msg;
msg.buff = entry.second->GetName();
msg.duration = static_cast<float>(duration);
controller->Notify(&msg);
});
//Re-Add buffs from the db we still need.
auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy");
auto statement = shared_ptr<sql::Statement>(conn->createStatement());
stringstream ss;
ss << "SELECT b.name, b.duration FROM buffs b WHERE b.id=" << object_id << ";" ;
statement->execute(ss.str());
unique_ptr<sql::ResultSet> result(statement->getResultSet());
while(result->next())
{
creature->AddBuff(result->getString(1), result->getUInt(2));
}
});
player_removed_ = kernel_->GetEventDispatcher()->Subscribe(
"Connection::PlayerRemoved",
[this] (shared_ptr<EventInterface> incoming_event)
{
const auto& player = static_pointer_cast<ValueEvent<shared_ptr<Player>>>(incoming_event)->Get();
OnPlayerExit(player);
});
SetServiceDescription(ServiceDescription(
"PlayerService",
"player",
"0.1",
"127.0.0.1",
0,
0,
0));
}
PlayerService::~PlayerService()
{}
void PlayerService::Initialize()
{
simulation_service_ = kernel_->GetServiceManager()->
GetService<swganh::simulation::SimulationServiceInterface>("SimulationService");
equipment_service_ = kernel_->GetServiceManager()->
GetService<swganh::equipment::EquipmentService>("EquipmentService");
}
void PlayerService::Startup()
{}
void PlayerService::OnPlayerEnter(shared_ptr<swganh::object::Player> player)
{
if (player)
{
player->ClearStatusFlags();
}
}
void PlayerService::OnPlayerExit(shared_ptr<swganh::object::Player> player)
{
if (player)
{
player->ClearStatusFlags();
player->AddStatusFlag(swganh::object::LD);
// set a timer to 30 seconds to destroy the object, unless logged back in.
auto deadline_timer = std::make_shared<boost::asio::deadline_timer>(kernel_->GetCpuThreadPool(), boost::posix_time::seconds(30));
auto parent = std::static_pointer_cast<swganh::object::Object>(player->GetContainer());
auto object_controller = std::static_pointer_cast<swganh::object::ObjectController>(parent->GetController());
if(object_controller != nullptr)
{
deadline_timer->async_wait(boost::bind(&PlayerService::RemoveClientTimerHandler_, this, boost::asio::placeholders::error, deadline_timer, 30, object_controller));
}
}
}
void PlayerService::SendTip(
const shared_ptr<Creature>& from,
const shared_ptr<Creature>& to,
uint32_t amount, bool bank)
{
// Check to see if we even have the proper amount
if (amount < 1 || amount > 1000000)
{
SystemMessage::Send(from, L"Invalid tip amount, set amount between 1 and 1,000,000");
return;
}
if (bank)
{
int32_t total_amount = (int32_t)(amount * 1.05); // 5% tip charge
int32_t from_amount = from->GetBankCredits();
if ( from_amount - total_amount > 0)
{
from->SetBankCredits( from_amount - total_amount );
int32_t to_amount = to->GetBankCredits();
to->SetBankCredits( to_amount + amount );
SystemMessage::Send(from, OutOfBand("base_player", "prose_wire_pass_self",0,0,to->GetObjectId(),amount), false, false);
SystemMessage::Send(to, OutOfBand("base_player", "prose_wire_pass_target",0,0,from->GetObjectId(),amount), false, false);
}
else
{
SystemMessage::Send(from, OutOfBand("base_player", "prose_tip_nsf_bank",0,to->GetObjectId(),0,total_amount), false, false);
}
}
else
{
int32_t total_amount = (int32_t)(amount * 1.05); // 5% tip charge
int32_t from_amount = from->GetCashCredits();
if ( from_amount - total_amount > 0)
{
from->SetCashCredits( from_amount - total_amount );
int32_t to_amount = to->GetBankCredits();
to->SetCashCredits( to_amount + amount );
SystemMessage::Send(from, OutOfBand("base_player", "prose_tip_pass_self",0,to->GetObjectId(),0,amount), false, false);
SystemMessage::Send(to, OutOfBand("base_player", "prose_tip_pass_target",0,from->GetObjectId(),0,amount), false, false);
}
else
{
SystemMessage::Send(from, OutOfBand("base_player", "prose_tip_nsf_cash",0,to->GetObjectId(),0,total_amount), false, false);
}
}
}
void PlayerService::OpenContainer(const std::shared_ptr<swganh::object::Creature>& owner, std::shared_ptr<swganh::object::Object> object)
{
// Send Open Container
OpenedContainerMessage opened_container;
opened_container.container_object_id = object->GetObjectId();
owner->NotifyObservers(&opened_container);
}
bool PlayerService::HasCalledMount(std::shared_ptr<swganh::object::Creature> owner)
{
auto equipment = kernel_->GetServiceManager()->GetService<swganh::equipment::EquipmentServiceInterface>("EquipmentService");
auto datapad = equipment->GetEquippedObject(owner, "datapad");
bool result = false;
if(datapad)
{
datapad->ViewObjects(nullptr, 0, true, [&] (std::shared_ptr<Object> object) {
if(!result && object->HasAttribute("is_mount") && !object->HasContainedObjects())
{
result = true;
}
});
}
return result;
}
void PlayerService::StoreAllCalledMounts(std::shared_ptr<swganh::object::Creature> owner)
{
auto simulation = kernel_->GetServiceManager()->GetService<swganh::simulation::SimulationServiceInterface>("SimulationService");
auto equipment = kernel_->GetServiceManager()->GetService<swganh::equipment::EquipmentServiceInterface>("EquipmentService");
auto datapad = equipment->GetEquippedObject(owner, "datapad");
if(datapad)
{
std::list<std::shared_ptr<Object>> objects = datapad->GetObjects(nullptr, 1, true);
for(auto& object : objects) {
if(object->HasAttribute("is_mount") && !object->HasContainedObjects())
{
auto mobile = simulation->GetObjectById((uint64_t)object->GetAttribute<int64_t>("mobile_id"));
if(mobile)
{
mobile->GetContainer()->TransferObject(owner, mobile, object, glm::vec3(0, 0, 0));
}
}
}
}
}
void PlayerService::StoreAllCalledObjects(std::shared_ptr<swganh::object::Creature> owner)
{
auto simulation = kernel_->GetServiceManager()->GetService<swganh::simulation::SimulationServiceInterface>("SimulationService");
auto equipment = kernel_->GetServiceManager()->GetService<swganh::equipment::EquipmentServiceInterface>("EquipmentService");
auto datapad = equipment->GetEquippedObject(owner, "datapad");
if(datapad)
{
datapad->ViewObjects(nullptr, 0, true, [&] (std::shared_ptr<Object> object) {
if(object->HasAttribute("mobile_id") && !object->HasContainedObjects())
{
auto mobile = simulation->GetObjectById((uint64_t)object->GetAttribute<int64_t>("mobile_id"));
if(mobile)
{
mobile->GetContainer()->TransferObject(owner, mobile, object, glm::vec3(0, 0, 0));
}
}
});
}
}
void PlayerService::RemoveClientTimerHandler_(
const boost::system::error_code& e,
shared_ptr<boost::asio::deadline_timer> timer,
int delay_in_secs,
shared_ptr<swganh::object::ObjectController> controller)
{
if (controller)
{
// destroy if they haven't reconnected
if (controller->GetRemoteClient() == nullptr || !controller->GetRemoteClient()->connected())
{
auto object = controller->GetObject();
DLOG(info) << "Destroying Object " << object->GetObjectId() << " after " << delay_in_secs << " seconds.";
simulation_service_->RemoveObject(object);
//Persist buffs
auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy");
auto object_id = object->GetObjectId();
auto creature = std::static_pointer_cast<Creature>(object);
creature->ViewBuffs([this,&conn,&object_id] (std::pair<boost::posix_time::ptime, std::shared_ptr<swganh::combat::BuffInterface>> entry) {
std::shared_ptr<sql::PreparedStatement> statement(conn->prepareStatement("INSERT INTO buffs VALUES (?,?,?)"));
uint32_t duration = (entry.first - boost::posix_time::second_clock::local_time()).total_seconds();
statement->setUInt64(1, object_id);
statement->setString(2, entry.second->filename);
statement->setInt(3, duration);
statement->execute();
});
creature->CleanUpBuffs();
kernel_->GetEventDispatcher()->Dispatch(
make_shared<ValueEvent<shared_ptr<swganh::object::Object>>>("ObjectRemovedEvent", object));
}
}
}<commit_msg>Store mounts when removing a player from the world.<commit_after>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "player_service.h"
#include "swganh/logger.h"
#include "swganh/event_dispatcher.h"
#include "swganh/service/service_description.h"
#include "swganh/service/service_manager.h"
#include "swganh_core/connection/connection_client_interface.h"
#include "swganh_core/object/player/player.h"
#include "swganh_core/object/creature/creature.h"
#include "swganh_core/object/object_controller.h"
#include "swganh_core/messages/system_message.h"
#include "swganh_core/messages/out_of_band.h"
#include "swganh_core/messages/opened_container_message.h"
#include "swganh_core/simulation/simulation_service_interface.h"
#include "swganh_core/equipment/equipment_service.h"
#include "swganh_core/messages/controllers/add_buff.h"
#include "swganh_core/combat/buff_interface.h"
#include "swganh/database/database_manager.h"
#include <cppconn/exception.h>
#include <cppconn/connection.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/sqlstring.h>
using namespace std;
using namespace swganh;
using namespace swganh::service;
using namespace swganh::player;
using namespace swganh::object;
using namespace swganh::messages;
PlayerService::PlayerService(swganh::app::SwganhKernel* kernel)
: kernel_(kernel)
{
kernel_->GetEventDispatcher()->Subscribe(
"ObjectReadyEvent",
[this] (shared_ptr<EventInterface> incoming_event)
{
auto creature = static_pointer_cast<ValueEvent<shared_ptr<Creature>>>(incoming_event)->Get();
//Reload buffs from last login
auto controller = creature->GetController();
auto object_id = creature->GetObjectId();
//Resend buffs we current have left over
creature->ViewBuffs([&, this] (std::pair<boost::posix_time::ptime, std::shared_ptr<swganh::combat::BuffInterface>> entry) {
uint32_t duration = (entry.first - boost::posix_time::second_clock::local_time()).total_seconds();
swganh::messages::controllers::AddBuffMessage msg;
msg.buff = entry.second->GetName();
msg.duration = static_cast<float>(duration);
controller->Notify(&msg);
});
//Re-Add buffs from the db we still need.
auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy");
auto statement = shared_ptr<sql::Statement>(conn->createStatement());
stringstream ss;
ss << "SELECT b.name, b.duration FROM buffs b WHERE b.id=" << object_id << ";" ;
statement->execute(ss.str());
unique_ptr<sql::ResultSet> result(statement->getResultSet());
while(result->next())
{
creature->AddBuff(result->getString(1), result->getUInt(2));
}
});
player_removed_ = kernel_->GetEventDispatcher()->Subscribe(
"Connection::PlayerRemoved",
[this] (shared_ptr<EventInterface> incoming_event)
{
const auto& player = static_pointer_cast<ValueEvent<shared_ptr<Player>>>(incoming_event)->Get();
OnPlayerExit(player);
});
SetServiceDescription(ServiceDescription(
"PlayerService",
"player",
"0.1",
"127.0.0.1",
0,
0,
0));
}
PlayerService::~PlayerService()
{}
void PlayerService::Initialize()
{
simulation_service_ = kernel_->GetServiceManager()->
GetService<swganh::simulation::SimulationServiceInterface>("SimulationService");
equipment_service_ = kernel_->GetServiceManager()->
GetService<swganh::equipment::EquipmentService>("EquipmentService");
}
void PlayerService::Startup()
{}
void PlayerService::OnPlayerEnter(shared_ptr<swganh::object::Player> player)
{
if (player)
{
player->ClearStatusFlags();
}
}
void PlayerService::OnPlayerExit(shared_ptr<swganh::object::Player> player)
{
if (player)
{
player->ClearStatusFlags();
player->AddStatusFlag(swganh::object::LD);
// set a timer to 30 seconds to destroy the object, unless logged back in.
auto deadline_timer = std::make_shared<boost::asio::deadline_timer>(kernel_->GetCpuThreadPool(), boost::posix_time::seconds(30));
auto parent = std::static_pointer_cast<swganh::object::Object>(player->GetContainer());
auto object_controller = std::static_pointer_cast<swganh::object::ObjectController>(parent->GetController());
if(object_controller != nullptr)
{
deadline_timer->async_wait(boost::bind(&PlayerService::RemoveClientTimerHandler_, this, boost::asio::placeholders::error, deadline_timer, 30, object_controller));
}
}
}
void PlayerService::SendTip(
const shared_ptr<Creature>& from,
const shared_ptr<Creature>& to,
uint32_t amount, bool bank)
{
// Check to see if we even have the proper amount
if (amount < 1 || amount > 1000000)
{
SystemMessage::Send(from, L"Invalid tip amount, set amount between 1 and 1,000,000");
return;
}
if (bank)
{
int32_t total_amount = (int32_t)(amount * 1.05); // 5% tip charge
int32_t from_amount = from->GetBankCredits();
if ( from_amount - total_amount > 0)
{
from->SetBankCredits( from_amount - total_amount );
int32_t to_amount = to->GetBankCredits();
to->SetBankCredits( to_amount + amount );
SystemMessage::Send(from, OutOfBand("base_player", "prose_wire_pass_self",0,0,to->GetObjectId(),amount), false, false);
SystemMessage::Send(to, OutOfBand("base_player", "prose_wire_pass_target",0,0,from->GetObjectId(),amount), false, false);
}
else
{
SystemMessage::Send(from, OutOfBand("base_player", "prose_tip_nsf_bank",0,to->GetObjectId(),0,total_amount), false, false);
}
}
else
{
int32_t total_amount = (int32_t)(amount * 1.05); // 5% tip charge
int32_t from_amount = from->GetCashCredits();
if ( from_amount - total_amount > 0)
{
from->SetCashCredits( from_amount - total_amount );
int32_t to_amount = to->GetBankCredits();
to->SetCashCredits( to_amount + amount );
SystemMessage::Send(from, OutOfBand("base_player", "prose_tip_pass_self",0,to->GetObjectId(),0,amount), false, false);
SystemMessage::Send(to, OutOfBand("base_player", "prose_tip_pass_target",0,from->GetObjectId(),0,amount), false, false);
}
else
{
SystemMessage::Send(from, OutOfBand("base_player", "prose_tip_nsf_cash",0,to->GetObjectId(),0,total_amount), false, false);
}
}
}
void PlayerService::OpenContainer(const std::shared_ptr<swganh::object::Creature>& owner, std::shared_ptr<swganh::object::Object> object)
{
// Send Open Container
OpenedContainerMessage opened_container;
opened_container.container_object_id = object->GetObjectId();
owner->NotifyObservers(&opened_container);
}
bool PlayerService::HasCalledMount(std::shared_ptr<swganh::object::Creature> owner)
{
auto equipment = kernel_->GetServiceManager()->GetService<swganh::equipment::EquipmentServiceInterface>("EquipmentService");
auto datapad = equipment->GetEquippedObject(owner, "datapad");
bool result = false;
if(datapad)
{
datapad->ViewObjects(nullptr, 0, true, [&] (std::shared_ptr<Object> object) {
if(!result && object->HasAttribute("is_mount") && !object->HasContainedObjects())
{
result = true;
}
});
}
return result;
}
void PlayerService::StoreAllCalledMounts(std::shared_ptr<swganh::object::Creature> owner)
{
auto simulation = kernel_->GetServiceManager()->GetService<swganh::simulation::SimulationServiceInterface>("SimulationService");
auto equipment = kernel_->GetServiceManager()->GetService<swganh::equipment::EquipmentServiceInterface>("EquipmentService");
auto datapad = equipment->GetEquippedObject(owner, "datapad");
if(datapad)
{
std::list<std::shared_ptr<Object>> objects = datapad->GetObjects(nullptr, 1, true);
for(auto& object : objects) {
if(object->HasAttribute("is_mount") && !object->HasContainedObjects())
{
auto mobile = simulation->GetObjectById((uint64_t)object->GetAttribute<int64_t>("mobile_id"));
if(mobile)
{
mobile->GetContainer()->TransferObject(owner, mobile, object, glm::vec3(0, 0, 0));
}
}
}
}
}
void PlayerService::StoreAllCalledObjects(std::shared_ptr<swganh::object::Creature> owner)
{
auto simulation = kernel_->GetServiceManager()->GetService<swganh::simulation::SimulationServiceInterface>("SimulationService");
auto equipment = kernel_->GetServiceManager()->GetService<swganh::equipment::EquipmentServiceInterface>("EquipmentService");
auto datapad = equipment->GetEquippedObject(owner, "datapad");
if(datapad)
{
datapad->ViewObjects(nullptr, 0, true, [&] (std::shared_ptr<Object> object) {
if(object->HasAttribute("mobile_id") && !object->HasContainedObjects())
{
auto mobile = simulation->GetObjectById((uint64_t)object->GetAttribute<int64_t>("mobile_id"));
if(mobile)
{
mobile->GetContainer()->TransferObject(owner, mobile, object, glm::vec3(0, 0, 0));
}
}
});
}
}
void PlayerService::RemoveClientTimerHandler_(
const boost::system::error_code& e,
shared_ptr<boost::asio::deadline_timer> timer,
int delay_in_secs,
shared_ptr<swganh::object::ObjectController> controller)
{
if (controller)
{
// destroy if they haven't reconnected
if (controller->GetRemoteClient() == nullptr || !controller->GetRemoteClient()->connected())
{
auto object = controller->GetObject();
DLOG(info) << "Destroying Object " << object->GetObjectId() << " after " << delay_in_secs << " seconds.";
simulation_service_->RemoveObject(object);
//Persist buffs
auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy");
auto object_id = object->GetObjectId();
auto creature = std::static_pointer_cast<Creature>(object);
creature->ViewBuffs([this,&conn,&object_id] (std::pair<boost::posix_time::ptime, std::shared_ptr<swganh::combat::BuffInterface>> entry) {
std::shared_ptr<sql::PreparedStatement> statement(conn->prepareStatement("INSERT INTO buffs VALUES (?,?,?)"));
uint32_t duration = (entry.first - boost::posix_time::second_clock::local_time()).total_seconds();
statement->setUInt64(1, object_id);
statement->setString(2, entry.second->filename);
statement->setInt(3, duration);
statement->execute();
});
StoreAllCalledMounts(creature);
creature->CleanUpBuffs();
kernel_->GetEventDispatcher()->Dispatch(
make_shared<ValueEvent<shared_ptr<swganh::object::Object>>>("ObjectRemovedEvent", object));
}
}
}<|endoftext|> |
<commit_before><commit_msg>Planning: do not reroute when close to destination<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: file_path_helper.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:45:56 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sal.hxx"
/*******************************************
Includes
******************************************/
#ifndef _OSL_FILE_PATH_HELPER_H_
#include "file_path_helper.h"
#endif
#ifndef _OSL_FILE_PATH_HELPER_HXX_
#include "file_path_helper.hxx"
#endif
#ifndef _OSL_UUNXAPI_HXX_
#include "uunxapi.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
/*******************************************
Constants
******************************************/
const sal_Unicode FPH_CHAR_PATH_SEPARATOR = (sal_Unicode)'/';
const sal_Unicode FPH_CHAR_DOT = (sal_Unicode)'.';
const sal_Unicode FPH_CHAR_COLON = (sal_Unicode)':';
inline const rtl::OUString FPH_PATH_SEPARATOR()
{ return rtl::OUString::createFromAscii("/"); }
inline const rtl::OUString FPH_LOCAL_DIR_ENTRY()
{ return rtl::OUString::createFromAscii("."); }
inline const rtl::OUString FPH_PARENT_DIR_ENTRY()
{ return rtl::OUString::createFromAscii(".."); }
/*******************************************
* osl_systemPathRemoveSeparator
******************************************/
void SAL_CALL osl_systemPathRemoveSeparator(rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathRemoveSeparator: Invalid parameter");
// maybe there are more than one separator at end
// so we run in a loop
while ((pustrPath->length > 1) && (FPH_CHAR_PATH_SEPARATOR == pustrPath->buffer[pustrPath->length - 1]))
{
pustrPath->length--;
pustrPath->buffer[pustrPath->length] = (sal_Unicode)'\0';
}
OSL_POSTCOND((0 == pustrPath->length) || (1 == pustrPath->length) || \
(pustrPath->length > 1 && pustrPath->buffer[pustrPath->length - 1] != FPH_CHAR_PATH_SEPARATOR), \
"osl_systemPathRemoveSeparator: Post condition failed");
}
/*******************************************
osl_systemPathEnsureSeparator
******************************************/
void SAL_CALL osl_systemPathEnsureSeparator(rtl_uString** ppustrPath)
{
OSL_PRECOND(ppustrPath && (NULL != *ppustrPath), \
"osl_systemPathEnsureSeparator: Invalid parameter");
rtl::OUString path(*ppustrPath);
sal_Int32 lp = path.getLength();
sal_Int32 i = path.lastIndexOf(FPH_CHAR_PATH_SEPARATOR);
if ((lp > 1 && i != (lp - 1)) || ((lp < 2) && i < 0))
{
path += FPH_PATH_SEPARATOR();
rtl_uString_assign(ppustrPath, path.pData);
}
OSL_POSTCOND(path.lastIndexOf(FPH_CHAR_PATH_SEPARATOR) == (path.getLength() - 1), \
"osl_systemPathEnsureSeparator: Post condition failed");
}
/*******************************************
* osl_systemPathIsRelativePath
******************************************/
sal_Bool SAL_CALL osl_systemPathIsRelativePath(const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsRelativePath: Invalid parameter");
return ((0 == pustrPath->length) || (pustrPath->buffer[0] != FPH_CHAR_PATH_SEPARATOR));
}
/******************************************
* osl_systemPathIsAbsolutePath
*****************************************/
sal_Bool SAL_CALL osl_systemPathIsAbsolutePath(const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsAbsolutePath: Invalid parameter");
return (!osl_systemPathIsRelativePath(pustrPath));
}
/******************************************
osl_systemPathMakeAbsolutePath
*****************************************/
void SAL_CALL osl_systemPathMakeAbsolutePath(
const rtl_uString* pustrBasePath,
const rtl_uString* pustrRelPath,
rtl_uString** ppustrAbsolutePath)
{
rtl::OUString base(rtl_uString_getStr(const_cast<rtl_uString*>(pustrBasePath)));
rtl::OUString rel(const_cast<rtl_uString*>(pustrRelPath));
if (base.getLength() > 0)
osl_systemPathEnsureSeparator(&base.pData);
base += rel;
rtl_uString_acquire(base.pData);
*ppustrAbsolutePath = base.pData;
}
/*******************************************
osl_systemPathGetFileOrLastDirectoryPart
******************************************/
void SAL_CALL osl_systemPathGetFileNameOrLastDirectoryPart(
const rtl_uString* pustrPath,
rtl_uString** ppustrFileNameOrLastDirPart)
{
OSL_PRECOND(pustrPath && ppustrFileNameOrLastDirPart, \
"osl_systemPathGetFileNameOrLastDirectoryPart: Invalid parameter");
rtl::OUString path(const_cast<rtl_uString*>(pustrPath));
osl_systemPathRemoveSeparator(path.pData);
rtl::OUString last_part;
if (path.getLength() > 1 || (1 == path.getLength() && *path.getStr() != FPH_CHAR_PATH_SEPARATOR))
{
sal_Int32 idx_ps = path.lastIndexOf(FPH_CHAR_PATH_SEPARATOR);
idx_ps++; // always right to increment by one even if idx_ps == -1!
last_part = rtl::OUString(path.getStr() + idx_ps);
}
rtl_uString_assign(ppustrFileNameOrLastDirPart, last_part.pData);
}
/********************************************
osl_systemPathIsHiddenFileOrDirectoryEntry
*********************************************/
sal_Bool SAL_CALL osl_systemPathIsHiddenFileOrDirectoryEntry(
const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsHiddenFileOrDirectoryEntry: Invalid parameter");
sal_Bool is_hidden = sal_False;
if (pustrPath->length > 0)
{
rtl::OUString fdp;
osl_systemPathGetFileNameOrLastDirectoryPart(pustrPath, &fdp.pData);
is_hidden = ((fdp.pData->length > 0) && (fdp.pData->buffer[0] == FPH_CHAR_DOT) &&
!osl_systemPathIsLocalOrParentDirectoryEntry(fdp.pData));
}
return is_hidden;
}
/************************************************
osl_systemPathIsLocalOrParentDirectoryEntry
************************************************/
sal_Bool SAL_CALL osl_systemPathIsLocalOrParentDirectoryEntry(
const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsLocalOrParentDirectoryEntry: Invalid parameter");
rtl::OUString dirent;
osl_systemPathGetFileNameOrLastDirectoryPart(pustrPath, &dirent.pData);
return (
(dirent == FPH_LOCAL_DIR_ENTRY()) ||
(dirent == FPH_PARENT_DIR_ENTRY())
);
}
/***********************************************
Simple iterator for a path list separated by
the specified character
**********************************************/
class path_list_iterator
{
public:
/******************************************
constructor
after construction get_current_item
returns the first path in list, no need
to call reset first
*****************************************/
path_list_iterator(const rtl::OUString& path_list, sal_Unicode list_separator = FPH_CHAR_COLON) :
m_path_list(path_list),
m_end(m_path_list.getStr() + m_path_list.getLength() + 1),
m_separator(list_separator)
{
reset();
}
/******************************************
reset the iterator
*****************************************/
void reset()
{
m_path_segment_begin = m_path_segment_end = m_path_list.getStr();
advance();
}
/******************************************
move the iterator to the next position
*****************************************/
void next()
{
OSL_PRECOND(!done(), "path_list_iterator: Already done!");
m_path_segment_begin = ++m_path_segment_end;
advance();
}
/******************************************
check if done
*****************************************/
bool done() const
{
return (m_path_segment_end >= m_end);
}
/******************************************
return the current item
*****************************************/
rtl::OUString get_current_item() const
{
return rtl::OUString(
m_path_segment_begin,
(m_path_segment_end - m_path_segment_begin));
}
private:
/******************************************
move m_path_end to the next separator or
to the edn of the string
*****************************************/
void advance()
{
while (!done() && *m_path_segment_end && (*m_path_segment_end != m_separator))
++m_path_segment_end;
OSL_ASSERT(m_path_segment_end <= m_end);
}
private:
rtl::OUString m_path_list;
const sal_Unicode* m_end;
const sal_Unicode m_separator;
const sal_Unicode* m_path_segment_begin;
const sal_Unicode* m_path_segment_end;
// prevent copy and assignment
private:
/******************************************
copy constructor
remember: do not simply copy m_path_begin
and m_path_end because they point to
the memory of other.m_path_list!
*****************************************/
path_list_iterator(const path_list_iterator& other);
/******************************************
assignment operator
remember: do not simply copy m_path_begin
and m_path_end because they point to
the memory of other.m_path_list!
*****************************************/
path_list_iterator& operator=(const path_list_iterator& other);
};
/************************************************
osl_searchPath
***********************************************/
sal_Bool SAL_CALL osl_searchPath(
const rtl_uString* pustrFilePath,
const rtl_uString* pustrSearchPathList,
rtl_uString** ppustrPathFound)
{
OSL_PRECOND(pustrFilePath && pustrSearchPathList && ppustrPathFound, "osl_searchPath: Invalid parameter");
bool bfound = false;
rtl::OUString fp(const_cast<rtl_uString*>(pustrFilePath));
rtl::OUString pl = rtl::OUString(const_cast<rtl_uString*>(pustrSearchPathList));
path_list_iterator pli(pl);
while (!pli.done())
{
rtl::OUString p = pli.get_current_item();
osl::systemPathEnsureSeparator(p);
p += fp;
if (osl::access(p, F_OK) > -1)
{
bfound = true;
rtl_uString_assign(ppustrPathFound, p.pData);
break;
}
pli.next();
}
return bfound;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.234); FILE MERGED 2008/03/31 13:23:43 rt 1.7.234.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: file_path_helper.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sal.hxx"
/*******************************************
Includes
******************************************/
#ifndef _OSL_FILE_PATH_HELPER_H_
#include "file_path_helper.h"
#endif
#ifndef _OSL_FILE_PATH_HELPER_HXX_
#include "file_path_helper.hxx"
#endif
#ifndef _OSL_UUNXAPI_HXX_
#include "uunxapi.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
/*******************************************
Constants
******************************************/
const sal_Unicode FPH_CHAR_PATH_SEPARATOR = (sal_Unicode)'/';
const sal_Unicode FPH_CHAR_DOT = (sal_Unicode)'.';
const sal_Unicode FPH_CHAR_COLON = (sal_Unicode)':';
inline const rtl::OUString FPH_PATH_SEPARATOR()
{ return rtl::OUString::createFromAscii("/"); }
inline const rtl::OUString FPH_LOCAL_DIR_ENTRY()
{ return rtl::OUString::createFromAscii("."); }
inline const rtl::OUString FPH_PARENT_DIR_ENTRY()
{ return rtl::OUString::createFromAscii(".."); }
/*******************************************
* osl_systemPathRemoveSeparator
******************************************/
void SAL_CALL osl_systemPathRemoveSeparator(rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathRemoveSeparator: Invalid parameter");
// maybe there are more than one separator at end
// so we run in a loop
while ((pustrPath->length > 1) && (FPH_CHAR_PATH_SEPARATOR == pustrPath->buffer[pustrPath->length - 1]))
{
pustrPath->length--;
pustrPath->buffer[pustrPath->length] = (sal_Unicode)'\0';
}
OSL_POSTCOND((0 == pustrPath->length) || (1 == pustrPath->length) || \
(pustrPath->length > 1 && pustrPath->buffer[pustrPath->length - 1] != FPH_CHAR_PATH_SEPARATOR), \
"osl_systemPathRemoveSeparator: Post condition failed");
}
/*******************************************
osl_systemPathEnsureSeparator
******************************************/
void SAL_CALL osl_systemPathEnsureSeparator(rtl_uString** ppustrPath)
{
OSL_PRECOND(ppustrPath && (NULL != *ppustrPath), \
"osl_systemPathEnsureSeparator: Invalid parameter");
rtl::OUString path(*ppustrPath);
sal_Int32 lp = path.getLength();
sal_Int32 i = path.lastIndexOf(FPH_CHAR_PATH_SEPARATOR);
if ((lp > 1 && i != (lp - 1)) || ((lp < 2) && i < 0))
{
path += FPH_PATH_SEPARATOR();
rtl_uString_assign(ppustrPath, path.pData);
}
OSL_POSTCOND(path.lastIndexOf(FPH_CHAR_PATH_SEPARATOR) == (path.getLength() - 1), \
"osl_systemPathEnsureSeparator: Post condition failed");
}
/*******************************************
* osl_systemPathIsRelativePath
******************************************/
sal_Bool SAL_CALL osl_systemPathIsRelativePath(const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsRelativePath: Invalid parameter");
return ((0 == pustrPath->length) || (pustrPath->buffer[0] != FPH_CHAR_PATH_SEPARATOR));
}
/******************************************
* osl_systemPathIsAbsolutePath
*****************************************/
sal_Bool SAL_CALL osl_systemPathIsAbsolutePath(const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsAbsolutePath: Invalid parameter");
return (!osl_systemPathIsRelativePath(pustrPath));
}
/******************************************
osl_systemPathMakeAbsolutePath
*****************************************/
void SAL_CALL osl_systemPathMakeAbsolutePath(
const rtl_uString* pustrBasePath,
const rtl_uString* pustrRelPath,
rtl_uString** ppustrAbsolutePath)
{
rtl::OUString base(rtl_uString_getStr(const_cast<rtl_uString*>(pustrBasePath)));
rtl::OUString rel(const_cast<rtl_uString*>(pustrRelPath));
if (base.getLength() > 0)
osl_systemPathEnsureSeparator(&base.pData);
base += rel;
rtl_uString_acquire(base.pData);
*ppustrAbsolutePath = base.pData;
}
/*******************************************
osl_systemPathGetFileOrLastDirectoryPart
******************************************/
void SAL_CALL osl_systemPathGetFileNameOrLastDirectoryPart(
const rtl_uString* pustrPath,
rtl_uString** ppustrFileNameOrLastDirPart)
{
OSL_PRECOND(pustrPath && ppustrFileNameOrLastDirPart, \
"osl_systemPathGetFileNameOrLastDirectoryPart: Invalid parameter");
rtl::OUString path(const_cast<rtl_uString*>(pustrPath));
osl_systemPathRemoveSeparator(path.pData);
rtl::OUString last_part;
if (path.getLength() > 1 || (1 == path.getLength() && *path.getStr() != FPH_CHAR_PATH_SEPARATOR))
{
sal_Int32 idx_ps = path.lastIndexOf(FPH_CHAR_PATH_SEPARATOR);
idx_ps++; // always right to increment by one even if idx_ps == -1!
last_part = rtl::OUString(path.getStr() + idx_ps);
}
rtl_uString_assign(ppustrFileNameOrLastDirPart, last_part.pData);
}
/********************************************
osl_systemPathIsHiddenFileOrDirectoryEntry
*********************************************/
sal_Bool SAL_CALL osl_systemPathIsHiddenFileOrDirectoryEntry(
const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsHiddenFileOrDirectoryEntry: Invalid parameter");
sal_Bool is_hidden = sal_False;
if (pustrPath->length > 0)
{
rtl::OUString fdp;
osl_systemPathGetFileNameOrLastDirectoryPart(pustrPath, &fdp.pData);
is_hidden = ((fdp.pData->length > 0) && (fdp.pData->buffer[0] == FPH_CHAR_DOT) &&
!osl_systemPathIsLocalOrParentDirectoryEntry(fdp.pData));
}
return is_hidden;
}
/************************************************
osl_systemPathIsLocalOrParentDirectoryEntry
************************************************/
sal_Bool SAL_CALL osl_systemPathIsLocalOrParentDirectoryEntry(
const rtl_uString* pustrPath)
{
OSL_PRECOND(pustrPath, "osl_systemPathIsLocalOrParentDirectoryEntry: Invalid parameter");
rtl::OUString dirent;
osl_systemPathGetFileNameOrLastDirectoryPart(pustrPath, &dirent.pData);
return (
(dirent == FPH_LOCAL_DIR_ENTRY()) ||
(dirent == FPH_PARENT_DIR_ENTRY())
);
}
/***********************************************
Simple iterator for a path list separated by
the specified character
**********************************************/
class path_list_iterator
{
public:
/******************************************
constructor
after construction get_current_item
returns the first path in list, no need
to call reset first
*****************************************/
path_list_iterator(const rtl::OUString& path_list, sal_Unicode list_separator = FPH_CHAR_COLON) :
m_path_list(path_list),
m_end(m_path_list.getStr() + m_path_list.getLength() + 1),
m_separator(list_separator)
{
reset();
}
/******************************************
reset the iterator
*****************************************/
void reset()
{
m_path_segment_begin = m_path_segment_end = m_path_list.getStr();
advance();
}
/******************************************
move the iterator to the next position
*****************************************/
void next()
{
OSL_PRECOND(!done(), "path_list_iterator: Already done!");
m_path_segment_begin = ++m_path_segment_end;
advance();
}
/******************************************
check if done
*****************************************/
bool done() const
{
return (m_path_segment_end >= m_end);
}
/******************************************
return the current item
*****************************************/
rtl::OUString get_current_item() const
{
return rtl::OUString(
m_path_segment_begin,
(m_path_segment_end - m_path_segment_begin));
}
private:
/******************************************
move m_path_end to the next separator or
to the edn of the string
*****************************************/
void advance()
{
while (!done() && *m_path_segment_end && (*m_path_segment_end != m_separator))
++m_path_segment_end;
OSL_ASSERT(m_path_segment_end <= m_end);
}
private:
rtl::OUString m_path_list;
const sal_Unicode* m_end;
const sal_Unicode m_separator;
const sal_Unicode* m_path_segment_begin;
const sal_Unicode* m_path_segment_end;
// prevent copy and assignment
private:
/******************************************
copy constructor
remember: do not simply copy m_path_begin
and m_path_end because they point to
the memory of other.m_path_list!
*****************************************/
path_list_iterator(const path_list_iterator& other);
/******************************************
assignment operator
remember: do not simply copy m_path_begin
and m_path_end because they point to
the memory of other.m_path_list!
*****************************************/
path_list_iterator& operator=(const path_list_iterator& other);
};
/************************************************
osl_searchPath
***********************************************/
sal_Bool SAL_CALL osl_searchPath(
const rtl_uString* pustrFilePath,
const rtl_uString* pustrSearchPathList,
rtl_uString** ppustrPathFound)
{
OSL_PRECOND(pustrFilePath && pustrSearchPathList && ppustrPathFound, "osl_searchPath: Invalid parameter");
bool bfound = false;
rtl::OUString fp(const_cast<rtl_uString*>(pustrFilePath));
rtl::OUString pl = rtl::OUString(const_cast<rtl_uString*>(pustrSearchPathList));
path_list_iterator pli(pl);
while (!pli.done())
{
rtl::OUString p = pli.get_current_item();
osl::systemPathEnsureSeparator(p);
p += fp;
if (osl::access(p, F_OK) > -1)
{
bfound = true;
rtl_uString_assign(ppustrPathFound, p.pData);
break;
}
pli.next();
}
return bfound;
}
<|endoftext|> |
<commit_before>//===- GlobalCombinerEmitter.cpp - Generate a combiner --------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
/// \file Generate a combiner implementation for GlobalISel from a declarative
/// syntax
///
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Timer.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "CodeGenTarget.h"
using namespace llvm;
#define DEBUG_TYPE "gicombiner-emitter"
cl::OptionCategory
GICombinerEmitterCat("Options for -gen-global-isel-combiner");
static cl::list<std::string>
SelectedCombiners("combiners", cl::desc("Emit the specified combiners"),
cl::cat(GICombinerEmitterCat), cl::CommaSeparated);
namespace {
class GICombinerEmitter {
StringRef Name;
Record *Combiner;
public:
explicit GICombinerEmitter(RecordKeeper &RK, StringRef Name);
~GICombinerEmitter() {}
StringRef getClassName() const {
return Combiner->getValueAsString("Classname");
}
void run(raw_ostream &OS);
};
GICombinerEmitter::GICombinerEmitter(RecordKeeper &RK, StringRef Name)
: Name(Name), Combiner(RK.getDef(Name)) {}
void GICombinerEmitter::run(raw_ostream &OS) {
NamedRegionTimer T("Emit", "Time spent emitting the combiner",
"Code Generation", "Time spent generating code",
TimeRegions);
OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_DEPS\n"
<< "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_DEPS\n\n";
OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_H\n"
<< "class " << getClassName() << " {\n"
<< "public:\n"
<< " bool tryCombineAll(\n"
<< " GISelChangeObserver &Observer,\n"
<< " MachineInstr &MI,\n"
<< " MachineIRBuilder &B) const;\n"
<< "};\n";
OS << "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_H\n\n";
OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_CPP\n"
<< "\n"
<< "bool " << getClassName() << "::tryCombineAll(\n"
<< " GISelChangeObserver &Observer,\n"
<< " MachineInstr &MI,\n"
<< " MachineIRBuilder &B) const {\n"
<< " MachineBasicBlock *MBB = MI.getParent();\n"
<< " MachineFunction *MF = MBB->getParent();\n"
<< " MachineRegisterInfo &MRI = MF->getRegInfo();\n"
<< " (void)MBB; (void)MF; (void)MRI;\n\n";
OS << "\n return false;\n"
<< "}\n"
<< "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_CPP\n";
}
} // end anonymous namespace
//===----------------------------------------------------------------------===//
namespace llvm {
void EmitGICombiner(RecordKeeper &RK, raw_ostream &OS) {
CodeGenTarget Target(RK);
emitSourceFileHeader("Global Combiner", OS);
if (SelectedCombiners.empty())
PrintFatalError("No combiners selected with -combiners");
for (const auto &Combiner : SelectedCombiners)
GICombinerEmitter(RK, Combiner).run(OS);
}
} // namespace llvm
<commit_msg>[gicombiner] Fix a nullptr dereference when -combiners is given a name that isn't defined<commit_after>//===- GlobalCombinerEmitter.cpp - Generate a combiner --------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
/// \file Generate a combiner implementation for GlobalISel from a declarative
/// syntax
///
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Timer.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "CodeGenTarget.h"
using namespace llvm;
#define DEBUG_TYPE "gicombiner-emitter"
cl::OptionCategory
GICombinerEmitterCat("Options for -gen-global-isel-combiner");
static cl::list<std::string>
SelectedCombiners("combiners", cl::desc("Emit the specified combiners"),
cl::cat(GICombinerEmitterCat), cl::CommaSeparated);
namespace {
class GICombinerEmitter {
StringRef Name;
Record *Combiner;
public:
explicit GICombinerEmitter(RecordKeeper &RK, StringRef Name,
Record *Combiner);
~GICombinerEmitter() {}
StringRef getClassName() const {
return Combiner->getValueAsString("Classname");
}
void run(raw_ostream &OS);
};
GICombinerEmitter::GICombinerEmitter(RecordKeeper &RK, StringRef Name,
Record *Combiner)
: Name(Name), Combiner(Combiner) {}
void GICombinerEmitter::run(raw_ostream &OS) {
NamedRegionTimer T("Emit", "Time spent emitting the combiner",
"Code Generation", "Time spent generating code",
TimeRegions);
OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_DEPS\n"
<< "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_DEPS\n\n";
OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_H\n"
<< "class " << getClassName() << " {\n"
<< "public:\n"
<< " bool tryCombineAll(\n"
<< " GISelChangeObserver &Observer,\n"
<< " MachineInstr &MI,\n"
<< " MachineIRBuilder &B) const;\n"
<< "};\n";
OS << "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_H\n\n";
OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_CPP\n"
<< "\n"
<< "bool " << getClassName() << "::tryCombineAll(\n"
<< " GISelChangeObserver &Observer,\n"
<< " MachineInstr &MI,\n"
<< " MachineIRBuilder &B) const {\n"
<< " MachineBasicBlock *MBB = MI.getParent();\n"
<< " MachineFunction *MF = MBB->getParent();\n"
<< " MachineRegisterInfo &MRI = MF->getRegInfo();\n"
<< " (void)MBB; (void)MF; (void)MRI;\n\n";
OS << "\n return false;\n"
<< "}\n"
<< "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_CPP\n";
}
} // end anonymous namespace
//===----------------------------------------------------------------------===//
namespace llvm {
void EmitGICombiner(RecordKeeper &RK, raw_ostream &OS) {
CodeGenTarget Target(RK);
emitSourceFileHeader("Global Combiner", OS);
if (SelectedCombiners.empty())
PrintFatalError("No combiners selected with -combiners");
for (const auto &Combiner : SelectedCombiners) {
Record *CombinerDef = RK.getDef(Combiner);
if (!CombinerDef)
PrintFatalError("Could not find " + Combiner);
GICombinerEmitter(RK, Combiner, CombinerDef).run(OS);
}
}
} // namespace llvm
<|endoftext|> |
<commit_before>/*
This file is part of Pack My Sprites.
Pack My Sprites 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.
Pack My Sprites 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pms/layout/atlas_page.hpp"
#include <sstream>
pms::layout::atlas_page::const_sprite_iterator
pms::layout::atlas_page::get_sprite_by_name( const std::string& n ) const
{
return
std::find_if
( sprites.begin(), sprites.end(),
[&]( const sprite& s ) -> bool
{
return s.name == n;
} );
}
void pms::layout::atlas_page::add_sprite( const sprite& s )
{
if ( (s.source_box.width <= 0) || (s.source_box.height <= 0) )
std::cerr << "Sprite '" << s.name << "' is not visible. Skipping."
<< std::endl;
else
sprites.push_back( s );
}
pms::layout::atlas_page::const_sprite_iterator
pms::layout::atlas_page::sprite_begin() const
{
return sprites.begin();
}
pms::layout::atlas_page::const_sprite_iterator
pms::layout::atlas_page::sprite_end() const
{
return sprites.end();
}
pms::layout::atlas_page::sprite_iterator
pms::layout::atlas_page::sprite_begin()
{
return sprites.begin();
}
pms::layout::atlas_page::sprite_iterator
pms::layout::atlas_page::sprite_end()
{
return sprites.end();
}
std::size_t pms::layout::atlas_page::sprite_count() const
{
return sprites.size();
}
void pms::layout::atlas_page::erase_sprite( const sprite_iterator& it )
{
sprites.erase( it );
}
std::string pms::layout::atlas_page::to_string() const
{
std::ostringstream oss;
oss << "size " << width << "×" << height;
if ( sprites.empty() )
{
oss << '\n';
return oss.str();
}
oss << ", sprites:\n";
for ( const sprite& s : sprites )
{
oss << " * '" << s.name
<< "' with image '" << images.find( s.image_id )->second
<< "', source box (left=" << s.source_box.position.x
<< ", top=" << s.source_box.position.y
<< ", width=" << s.source_box.width
<< ", height=" << s.source_box.height
<< "), output box (left=" << s.result_box.position.x
<< ", right=" << s.result_box.position.y
<< ", width=" << s.result_box.width
<< ", height=" << s.result_box.height
<< ", rotate=" << s.rotated
<< ", bleed=" << s.bleed
<< "), layers [";
for ( const resources::layer& layer : s.layers )
oss << ' ' << layer.index;
oss << " ], mask [";
for ( const resources::layer& layer : s.mask )
oss << ' ' << layer.index;
oss << " ]\n";
}
return oss.str();
}
<commit_msg>Fix typo in atlas_page::to_string.<commit_after>/*
This file is part of Pack My Sprites.
Pack My Sprites 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.
Pack My Sprites 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pms/layout/atlas_page.hpp"
#include <sstream>
pms::layout::atlas_page::const_sprite_iterator
pms::layout::atlas_page::get_sprite_by_name( const std::string& n ) const
{
return
std::find_if
( sprites.begin(), sprites.end(),
[&]( const sprite& s ) -> bool
{
return s.name == n;
} );
}
void pms::layout::atlas_page::add_sprite( const sprite& s )
{
if ( (s.source_box.width <= 0) || (s.source_box.height <= 0) )
std::cerr << "Sprite '" << s.name << "' is not visible. Skipping."
<< std::endl;
else
sprites.push_back( s );
}
pms::layout::atlas_page::const_sprite_iterator
pms::layout::atlas_page::sprite_begin() const
{
return sprites.begin();
}
pms::layout::atlas_page::const_sprite_iterator
pms::layout::atlas_page::sprite_end() const
{
return sprites.end();
}
pms::layout::atlas_page::sprite_iterator
pms::layout::atlas_page::sprite_begin()
{
return sprites.begin();
}
pms::layout::atlas_page::sprite_iterator
pms::layout::atlas_page::sprite_end()
{
return sprites.end();
}
std::size_t pms::layout::atlas_page::sprite_count() const
{
return sprites.size();
}
void pms::layout::atlas_page::erase_sprite( const sprite_iterator& it )
{
sprites.erase( it );
}
std::string pms::layout::atlas_page::to_string() const
{
std::ostringstream oss;
oss << "size " << width << "×" << height;
if ( sprites.empty() )
{
oss << '\n';
return oss.str();
}
oss << ", sprites:\n";
for ( const sprite& s : sprites )
{
oss << " * '" << s.name
<< "' with image '" << images.find( s.image_id )->second
<< "', source box (left=" << s.source_box.position.x
<< ", top=" << s.source_box.position.y
<< ", width=" << s.source_box.width
<< ", height=" << s.source_box.height
<< "), output box (left=" << s.result_box.position.x
<< ", top=" << s.result_box.position.y
<< ", width=" << s.result_box.width
<< ", height=" << s.result_box.height
<< ", rotate=" << s.rotated
<< ", bleed=" << s.bleed
<< "), layers [";
for ( const resources::layer& layer : s.layers )
oss << ' ' << layer.index;
oss << " ], mask [";
for ( const resources::layer& layer : s.mask )
oss << ' ' << layer.index;
oss << " ]\n";
}
return oss.str();
}
<|endoftext|> |
<commit_before>#include "FunctionNodalAverageIC.h"
registerMooseObject("RELAP7App", FunctionNodalAverageIC);
template <>
InputParameters
validParams<FunctionNodalAverageIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addClassDescription(
"Initial conditions for an elemental variable from a function using nodal average.");
params.addRequiredParam<FunctionName>("function", "The initial condition function.");
return params;
}
FunctionNodalAverageIC::FunctionNodalAverageIC(const InputParameters & parameters)
: InitialCondition(parameters), _func(getFunction("function"))
{
}
Real
FunctionNodalAverageIC::value(const Point & /*p*/)
{
const unsigned int n_nodes = _current_elem->n_nodes();
Real sum = 0.0;
for (unsigned int i = 0; i < n_nodes; i++)
{
const Node & node = _current_elem->node_ref(i);
sum += _func.value(_t, node);
}
return sum / n_nodes;
}
<commit_msg>MOOSE update<commit_after>#include "FunctionNodalAverageIC.h"
#include "Function.h"
registerMooseObject("RELAP7App", FunctionNodalAverageIC);
template <>
InputParameters
validParams<FunctionNodalAverageIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addClassDescription(
"Initial conditions for an elemental variable from a function using nodal average.");
params.addRequiredParam<FunctionName>("function", "The initial condition function.");
return params;
}
FunctionNodalAverageIC::FunctionNodalAverageIC(const InputParameters & parameters)
: InitialCondition(parameters), _func(getFunction("function"))
{
}
Real
FunctionNodalAverageIC::value(const Point & /*p*/)
{
const unsigned int n_nodes = _current_elem->n_nodes();
Real sum = 0.0;
for (unsigned int i = 0; i < n_nodes; i++)
{
const Node & node = _current_elem->node_ref(i);
sum += _func.value(_t, node);
}
return sum / n_nodes;
}
<|endoftext|> |
<commit_before>AliAnalysisTaskSE *AddTaskEmcalPreparation(const char *perstr = "LHC11h",
const char *pass = 0 /*should not be needed*/
) {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalPreparation", "No analysis manager to connect to.");
return NULL;
}
TString period(perstr);
period.ToLower();
Bool_t isMC = kFALSE;
if(period.Sizeof()>7) isMC = kTRUE;
// Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); //only works for ESD
if(isMC) Printf("AddTaskEmcalPreparation: Running on MC");
else Printf("AddTaskEmcalPreparation: Running on DATA");
//----------------------- Add tender -------------------------------------------------------
Bool_t distBC = kFALSE; //switch for recalculation cluster position from bad channel
Bool_t recalibClus = kFALSE;
Bool_t recalcClusPos = kFALSE;
Bool_t nonLinearCorr = kFALSE;
Bool_t remExoticCell = kFALSE;
Bool_t remExoticClus = kFALSE;
Bool_t fidRegion = kFALSE;
Bool_t calibEnergy = kTRUE;
Bool_t calibTime = kTRUE;
Bool_t remBC = kTRUE;
UInt_t nonLinFunct = 0;
Bool_t reclusterize = kFALSE;
Float_t seedthresh = 0.1; // 100 MeV
Float_t cellthresh = 0.05; // 50 MeV
UInt_t clusterizer = 0;
Bool_t trackMatch = kFALSE;
Bool_t updateCellOnly = kFALSE;
Float_t timeMin = -50e-9; // minimum time of physical signal in a cell/digit
Float_t timeMax = 50e-9; // maximum time of physical signal in a cell/digit
Float_t timeCut = 1e6;
if(isMC) {
timeMin = -1.;
timeMax = 1e6;
}
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C");//tendertasks
AliAnalysisTaskSE *tender = AddTaskEMCALTender(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus,
fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh,
cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut,pass);
//----------------------- Add clusterizer -------------------------------------------------------
clusterizer = AliEMCALRecParam::kClusterizerv2;
remExoticCell = kFALSE;
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskClusterizerFast.C");
AliAnalysisTaskEMCALClusterizeFast *clusterizerTask = AddTaskClusterizerFast("ClusterizerFast","","",clusterizer,cellthresh,seedthresh,
timeMin,timeMax,timeCut,remExoticCell,distBC,
AliAnalysisTaskEMCALClusterizeFast::kFEEData);
//----------------------- Add cluster maker -----------------------------------------------------
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusterMaker.C"); //cluster maker: non-linearity,
UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected;
if(isMC) {
if(period == "lhc12a15a")
nonLinFunct = AliEMCALRecoUtils::kPi0MCv2;
else
nonLinFunct = AliEMCALRecoUtils::kPi0MCv3;
}
remExoticClus = kTRUE;
AliEmcalClusterMaker *clusMaker = AddTaskEmcalClusterMaker(nonLinFunct,remExoticClus,0,"EmcCaloClusters",0.,kTRUE);
return clusMaker;
}
<commit_msg>turn off energy and timing calibration for MC<commit_after>AliAnalysisTaskSE *AddTaskEmcalPreparation(const char *perstr = "LHC11h",
const char *pass = 0 /*should not be needed*/
) {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalPreparation", "No analysis manager to connect to.");
return NULL;
}
TString period(perstr);
period.ToLower();
Bool_t isMC = kFALSE;
if(period.Sizeof()>7) isMC = kTRUE;
// Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); //only works for ESD
if(isMC) Printf("AddTaskEmcalPreparation: Running on MC");
else Printf("AddTaskEmcalPreparation: Running on DATA");
//----------------------- Add tender -------------------------------------------------------
Bool_t distBC = kFALSE; //switch for recalculation cluster position from bad channel
Bool_t recalibClus = kFALSE;
Bool_t recalcClusPos = kFALSE;
Bool_t nonLinearCorr = kFALSE;
Bool_t remExoticCell = kFALSE;
Bool_t remExoticClus = kFALSE;
Bool_t fidRegion = kFALSE;
Bool_t calibEnergy = kTRUE;
Bool_t calibTime = kTRUE;
Bool_t remBC = kTRUE;
UInt_t nonLinFunct = 0;
Bool_t reclusterize = kFALSE;
Float_t seedthresh = 0.1; // 100 MeV
Float_t cellthresh = 0.05; // 50 MeV
UInt_t clusterizer = 0;
Bool_t trackMatch = kFALSE;
Bool_t updateCellOnly = kFALSE;
Float_t timeMin = -50e-9; // minimum time of physical signal in a cell/digit
Float_t timeMax = 50e-9; // maximum time of physical signal in a cell/digit
Float_t timeCut = 1e6;
if(isMC) {
calibEnergy = kFALSE;
calibTime = kFALSE;
timeMin = -1.;
timeMax = 1e6;
}
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C");//tendertasks
AliAnalysisTaskSE *tender = AddTaskEMCALTender(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus,
fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh,
cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut,pass);
//----------------------- Add clusterizer -------------------------------------------------------
clusterizer = AliEMCALRecParam::kClusterizerv2;
remExoticCell = kFALSE;
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskClusterizerFast.C");
AliAnalysisTaskEMCALClusterizeFast *clusterizerTask = AddTaskClusterizerFast("ClusterizerFast","","",clusterizer,cellthresh,seedthresh,
timeMin,timeMax,timeCut,remExoticCell,distBC,
AliAnalysisTaskEMCALClusterizeFast::kFEEData);
//----------------------- Add cluster maker -----------------------------------------------------
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusterMaker.C"); //cluster maker: non-linearity,
UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected;
if(isMC) {
if(period == "lhc12a15a")
nonLinFunct = AliEMCALRecoUtils::kPi0MCv2;
else
nonLinFunct = AliEMCALRecoUtils::kPi0MCv3;
}
remExoticClus = kTRUE;
AliEmcalClusterMaker *clusMaker = AddTaskEmcalClusterMaker(nonLinFunct,remExoticClus,0,"EmcCaloClusters",0.,kTRUE);
return clusMaker;
}
<|endoftext|> |
<commit_before>#include "polylineStyle.h"
#include "tangram.h"
#include "gl/shaderProgram.h"
#include "scene/stops.h"
#include "tile/tile.h"
#include "util/mapProjection.h"
namespace Tangram {
PolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode)
: Style(_name, _blendMode, _drawMode) {
}
void PolylineStyle::constructVertexLayout() {
// TODO: Ideally this would be in the same location as the struct that it basically describes
m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
{"a_position", 3, GL_FLOAT, false, 0},
{"a_texcoord", 2, GL_FLOAT, false, 0},
{"a_extrude", 4, GL_FLOAT, false, 0},
{"a_color", 4, GL_UNSIGNED_BYTE, true, 0},
{"a_layer", 1, GL_FLOAT, false, 0}
}));
}
void PolylineStyle::constructShaderProgram() {
std::string vertShaderSrcStr = stringFromFile("shaders/polyline.vs", PathType::internal);
std::string fragShaderSrcStr = stringFromFile("shaders/polyline.fs", PathType::internal);
m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);
}
PolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const {
Parameters p;
uint32_t cap = 0, join = 0;
_rule.get(StyleParamKey::extrude, p.extrude);
_rule.get(StyleParamKey::color, p.color);
_rule.get(StyleParamKey::cap, cap);
_rule.get(StyleParamKey::join, join);
if (!_rule.get(StyleParamKey::order, p.order)) {
LOGW("No 'order' specified for feature, ordering cannot be guaranteed :(");
}
p.cap = static_cast<CapTypes>(cap);
p.join = static_cast<JoinTypes>(join);
p.outlineOrder = p.order; // will offset from fill later
if (_rule.get(StyleParamKey::outline_color, p.outlineColor) |
_rule.get(StyleParamKey::outline_order, p.outlineOrder) |
_rule.contains(StyleParamKey::outline_width) |
_rule.get(StyleParamKey::outline_cap, cap) |
_rule.get(StyleParamKey::outline_join, join)) {
p.outlineOn = true;
p.outlineCap = static_cast<CapTypes>(cap);
p.outlineJoin = static_cast<JoinTypes>(join);
}
return p;
}
void PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props,
VboMesh& _mesh, Tile& _tile) const {
for (const auto& line : _poly) {
buildLine(line, _rule, _props, _mesh, _tile);
}
}
double widthMeterToPixel(int _zoom, double _tileSize, double _width) {
// pixel per meter at z == 0
double meterRes = _tileSize / (2.0 * MapProjection::HALF_CIRCUMFERENCE);
// pixel per meter at zoom
meterRes *= exp2(_zoom);
return _width * meterRes;
}
bool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile,
float& width, float& dWdZ){
int zoom = _tile.getID().z;
double tileSize = _tile.getProjection()->TileSize();
// NB: 0.5 because 'width' will be extruded in both directions
double tileRes = 0.5 / _tile.getProjection()->TileSize();
auto& styleParam = _rule.findParameter(_key);
if (styleParam.stops) {
width = styleParam.stops->evalWidth(zoom);
width *= tileRes;
dWdZ = styleParam.stops->evalWidth(zoom + 1);
dWdZ *= tileRes;
// NB: Multiply by 2 for the outline to get the expected stroke pixel width.
if (_key == StyleParamKey::outline_width) {
width *= 2;
dWdZ *= 2;
}
dWdZ -= width;
return true;
}
if (styleParam.value.is<StyleParam::Width>()) {
auto& widthParam = styleParam.value.get<StyleParam::Width>();
width = widthParam.value;
if (widthParam.isMeter()) {
width = widthMeterToPixel(zoom, tileSize, width);
width *= tileRes;
dWdZ = width * 2;
} else {
width *= tileRes;
dWdZ = width;
}
if (_key == StyleParamKey::outline_width) {
width *= 2;
dWdZ *= 2;
}
dWdZ -= width;
return true;
}
logMsg("Error: Invalid type for Width '%d'\n", styleParam.value.which());
return false;
}
void PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props,
VboMesh& _mesh, Tile& _tile) const {
if (!_rule.contains(StyleParamKey::color)) {
const auto& blocks = m_shaderProgram->getSourceBlocks();
if (blocks.find("color") == blocks.end() && blocks.find("filter") == blocks.end()) {
return; // No color parameter or color block? NO SOUP FOR YOU
}
}
std::vector<PolylineVertex> vertices;
Parameters params = parseRule(_rule);
GLuint abgr = params.color;
float dWdZ = 0.f;
float width = 0.f;
if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) {
return;
}
if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) {
abgr = abgr << (_tile.getID().z % 6);
}
float height = 0.0f;
auto& extrude = params.extrude;
if (extrude[0] != 0.0f || extrude[1] != 0.0f) {
const static std::string key_height("height");
height = _props.getNumeric(key_height) * _tile.getInverseScale();
if (std::isnan(extrude[1])) {
if (!std::isnan(extrude[0])) {
height = extrude[0];
}
} else { height = extrude[1]; }
}
PolyLineBuilder builder {
[&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) {
glm::vec4 extrude = { normal.x, normal.y, width, dWdZ };
vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, (float)params.order });
},
[&](size_t sizeHint){ vertices.reserve(sizeHint); },
params.cap,
params.join
};
Builders::buildPolyLine(_line, builder);
if (params.outlineOn) {
GLuint abgrOutline = params.outlineColor;
float outlineOrder = std::min((float)params.outlineOrder, params.order - .5f);
float widthOutline = 0.f;
float dWdZOutline = 0.f;
if (!evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile,
widthOutline, dWdZOutline)) {
return;
}
widthOutline += width;
dWdZOutline += dWdZ;
if (params.outlineCap != params.cap || params.outlineJoin != params.join) {
// need to re-triangulate with different cap and/or join
builder.cap = params.outlineCap;
builder.join = params.outlineJoin;
Builders::buildPolyLine(_line, builder);
} else {
// re-use indices from original line
size_t oldSize = builder.indices.size();
size_t offset = vertices.size();
builder.indices.reserve(2 * oldSize);
for(size_t i = 0; i < oldSize; i++) {
builder.indices.push_back(offset + builder.indices[i]);
}
for (size_t i = 0; i < offset; i++) {
const auto& v = vertices[i];
glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline };
vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, outlineOrder });
}
}
}
auto& mesh = static_cast<PolylineStyle::Mesh&>(_mesh);
mesh.addVertices(std::move(vertices), std::move(builder.indices));
}
}
<commit_msg>Keep outline order on 'half' layers<commit_after>#include "polylineStyle.h"
#include "tangram.h"
#include "gl/shaderProgram.h"
#include "scene/stops.h"
#include "tile/tile.h"
#include "util/mapProjection.h"
namespace Tangram {
PolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode)
: Style(_name, _blendMode, _drawMode) {
}
void PolylineStyle::constructVertexLayout() {
// TODO: Ideally this would be in the same location as the struct that it basically describes
m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
{"a_position", 3, GL_FLOAT, false, 0},
{"a_texcoord", 2, GL_FLOAT, false, 0},
{"a_extrude", 4, GL_FLOAT, false, 0},
{"a_color", 4, GL_UNSIGNED_BYTE, true, 0},
{"a_layer", 1, GL_FLOAT, false, 0}
}));
}
void PolylineStyle::constructShaderProgram() {
std::string vertShaderSrcStr = stringFromFile("shaders/polyline.vs", PathType::internal);
std::string fragShaderSrcStr = stringFromFile("shaders/polyline.fs", PathType::internal);
m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);
}
PolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const {
Parameters p;
uint32_t cap = 0, join = 0;
_rule.get(StyleParamKey::extrude, p.extrude);
_rule.get(StyleParamKey::color, p.color);
_rule.get(StyleParamKey::cap, cap);
_rule.get(StyleParamKey::join, join);
if (!_rule.get(StyleParamKey::order, p.order)) {
LOGW("No 'order' specified for feature, ordering cannot be guaranteed :(");
}
p.cap = static_cast<CapTypes>(cap);
p.join = static_cast<JoinTypes>(join);
p.outlineOrder = p.order; // will offset from fill later
if (_rule.get(StyleParamKey::outline_color, p.outlineColor) |
_rule.get(StyleParamKey::outline_order, p.outlineOrder) |
_rule.contains(StyleParamKey::outline_width) |
_rule.get(StyleParamKey::outline_cap, cap) |
_rule.get(StyleParamKey::outline_join, join)) {
p.outlineOn = true;
p.outlineCap = static_cast<CapTypes>(cap);
p.outlineJoin = static_cast<JoinTypes>(join);
}
return p;
}
void PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props,
VboMesh& _mesh, Tile& _tile) const {
for (const auto& line : _poly) {
buildLine(line, _rule, _props, _mesh, _tile);
}
}
double widthMeterToPixel(int _zoom, double _tileSize, double _width) {
// pixel per meter at z == 0
double meterRes = _tileSize / (2.0 * MapProjection::HALF_CIRCUMFERENCE);
// pixel per meter at zoom
meterRes *= exp2(_zoom);
return _width * meterRes;
}
bool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile,
float& width, float& dWdZ){
int zoom = _tile.getID().z;
double tileSize = _tile.getProjection()->TileSize();
// NB: 0.5 because 'width' will be extruded in both directions
double tileRes = 0.5 / _tile.getProjection()->TileSize();
auto& styleParam = _rule.findParameter(_key);
if (styleParam.stops) {
width = styleParam.stops->evalWidth(zoom);
width *= tileRes;
dWdZ = styleParam.stops->evalWidth(zoom + 1);
dWdZ *= tileRes;
// NB: Multiply by 2 for the outline to get the expected stroke pixel width.
if (_key == StyleParamKey::outline_width) {
width *= 2;
dWdZ *= 2;
}
dWdZ -= width;
return true;
}
if (styleParam.value.is<StyleParam::Width>()) {
auto& widthParam = styleParam.value.get<StyleParam::Width>();
width = widthParam.value;
if (widthParam.isMeter()) {
width = widthMeterToPixel(zoom, tileSize, width);
width *= tileRes;
dWdZ = width * 2;
} else {
width *= tileRes;
dWdZ = width;
}
if (_key == StyleParamKey::outline_width) {
width *= 2;
dWdZ *= 2;
}
dWdZ -= width;
return true;
}
logMsg("Error: Invalid type for Width '%d'\n", styleParam.value.which());
return false;
}
void PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props,
VboMesh& _mesh, Tile& _tile) const {
if (!_rule.contains(StyleParamKey::color)) {
const auto& blocks = m_shaderProgram->getSourceBlocks();
if (blocks.find("color") == blocks.end() && blocks.find("filter") == blocks.end()) {
return; // No color parameter or color block? NO SOUP FOR YOU
}
}
std::vector<PolylineVertex> vertices;
Parameters params = parseRule(_rule);
GLuint abgr = params.color;
float dWdZ = 0.f;
float width = 0.f;
if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) {
return;
}
if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) {
abgr = abgr << (_tile.getID().z % 6);
}
float height = 0.0f;
auto& extrude = params.extrude;
if (extrude[0] != 0.0f || extrude[1] != 0.0f) {
const static std::string key_height("height");
height = _props.getNumeric(key_height) * _tile.getInverseScale();
if (std::isnan(extrude[1])) {
if (!std::isnan(extrude[0])) {
height = extrude[0];
}
} else { height = extrude[1]; }
}
PolyLineBuilder builder {
[&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) {
glm::vec4 extrude = { normal.x, normal.y, width, dWdZ };
vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, (float)params.order });
},
[&](size_t sizeHint){ vertices.reserve(sizeHint); },
params.cap,
params.join
};
Builders::buildPolyLine(_line, builder);
if (params.outlineOn) {
GLuint abgrOutline = params.outlineColor;
float outlineOrder = std::min(params.outlineOrder, params.order) - .5f;
float widthOutline = 0.f;
float dWdZOutline = 0.f;
if (!evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile,
widthOutline, dWdZOutline)) {
return;
}
widthOutline += width;
dWdZOutline += dWdZ;
if (params.outlineCap != params.cap || params.outlineJoin != params.join) {
// need to re-triangulate with different cap and/or join
builder.cap = params.outlineCap;
builder.join = params.outlineJoin;
Builders::buildPolyLine(_line, builder);
} else {
// re-use indices from original line
size_t oldSize = builder.indices.size();
size_t offset = vertices.size();
builder.indices.reserve(2 * oldSize);
for(size_t i = 0; i < oldSize; i++) {
builder.indices.push_back(offset + builder.indices[i]);
}
for (size_t i = 0; i < offset; i++) {
const auto& v = vertices[i];
glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline };
vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, outlineOrder });
}
}
}
auto& mesh = static_cast<PolylineStyle::Mesh&>(_mesh);
mesh.addVertices(std::move(vertices), std::move(builder.indices));
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// tutorial.cpp
// ------------
//
// Code from the tutorial featured at
// https://github.com/parsiad/QuantPDE/wiki/Getting-Started
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////
#include <QuantPDE/Core>
#include <QuantPDE/Modules/Operators>
using namespace QuantPDE;
using namespace QuantPDE::Modules;
#include <algorithm> // std::max
#include <iostream> // std::cout, std::endl
using namespace std;
int main() {
// Strike price
const Real K = 100.;
// Automatic grid
RectilinearGrid1 grid(
Axis::cluster(
0., // Left-hand boundary
10000., // Right-hand boundary
64, // Number of nodes
K, // Feature to cluster nodes around
5. // Intensity with which to cluster around K
)
);
// Hand-picked grid (this is generally not a robust approach)
/*
RectilinearGrid1 grid(
Axis {
0., 10., 20., 30., 40., 50., 60., 70.,
75., 80.,
84., 88., 92.,
94., 96., 98., 100., 102., 104., 106., 108., 110.,
114., 118.,
123.,
130., 140., 150.,
175.,
225.,
300.,
750.,
2000.,
10000.
}
);
*/
// Payoff for a put option
auto payoff = [K] (Real S) {
return max( K - S, 0. );
};
// Initial time
const Real t0 = 0.;
// Expiry time
const Real T = 1.;
// Timestep size
const Real dt = 0.01;
// Number of exercise times
const int E = 10;
ReverseConstantStepper stepper(t0, T, dt);
// Discrete dividends
/*
// A discrete dividend of one dollar
const Real D = 1.;
// Relates the value of V- to V (see the above derivation)
auto dividendEvent = [D] (const Interpolant1 &V, Real S) {
return V( max( S - D, 0. ) );
};
// Create uniformly spaced dividend payouts
for(int e = 0; e < E; ++e) {
// Time at which the event takes place
const Real te = T / E * e;
// Add the event
stepper.add(te, dividendEvent, grid);
}
*/
// Relates the value of V- to V (see the above derivation)
auto exerciseEvent = [K] (const Interpolant1 &V, Real S) {
return max( V(S) , K - S );
};
// Create uniformly spaced exercise times
for(int e = 0; e < E; ++e) {
// Time at which the event takes place
const Real te = T / E * e;
// Add the event
stepper.add(te, exerciseEvent, grid);
}
// Interest rate
const Real r = 0.04;
// Local volatility function
const Real alpha = 20.;
auto v = [alpha] (Real S) {
return alpha / S;
};
// A function of time and space could have been specified by using
// [] (Real t, Real S) { ... }
// Dividends
const Real q = 0.;
// Black-Scholes operator
BlackScholes1 bs(grid, r, v, q);
// Backward-differentiation formula of order two
ReverseBDFTwo1 bdf2(grid, bs);
bdf2.setIteration(stepper);
// Linear system solver
BiCGSTABSolver solver;
// Get the solution
auto V = stepper.solve(
grid, // Domain
payoff, // Initial condition
bdf2, // Backward-differentiation formula
solver // Linear system solver
);
// Axis::range(a, b, c) creates ticks a to c using a step-size of b
// This is equivalent to the a:b:c notation used in MATLAB/Octave
RectilinearGrid1 printGrid( Axis::range(0., 10., 200.) );
cout << accessor( printGrid, V );
} // main()
<commit_msg>Update tutorial.cpp<commit_after>////////////////////////////////////////////////////////////////////////////////
// tutorial.cpp
// ------------
//
// Code from the tutorial featured at
// https://github.com/parsiad/QuantPDE/wiki/Getting-Started
//
// Author: Parsiad Azimzadeh
////////////////////////////////////////////////////////////////////////////////
#include <QuantPDE/Core>
#include <QuantPDE/Modules/Operators>
using namespace QuantPDE;
using namespace QuantPDE::Modules;
#include <algorithm> // std::max
#include <iostream> // std::cout, std::endl
using namespace std;
int main() {
// Strike price
const Real K = 100.;
// Automatic grid
RectilinearGrid1 grid(
Axis::cluster(
0., // Left-hand boundary
10000., // Right-hand boundary
64, // Number of nodes
K, // Feature to cluster nodes around
5. // Intensity with which to cluster around K
)
);
// Hand-picked grid (this is generally not a robust approach)
/*
RectilinearGrid1 grid(
Axis {
0., 10., 20., 30., 40., 50., 60., 70.,
75., 80.,
84., 88., 92.,
94., 96., 98., 100., 102., 104., 106., 108., 110.,
114., 118.,
123.,
130., 140., 150.,
175.,
225.,
300.,
750.,
2000.,
10000.
}
);
*/
// Payoff for a put option
auto payoff = [K] (Real S) {
return max( K - S, 0. );
};
// Initial time
const Real t0 = 0.;
// Expiry time
const Real T = 1.;
// Timestep size
const Real dt = 0.01;
// Number of exercise times
const int E = 10;
ReverseConstantStepper stepper(t0, T, dt);
// Discrete dividends
/*
// A discrete dividend of one dollar
const Real D = 1.;
// Relates the value of V- to V (see the above derivation)
auto dividendEvent = [D] (const Interpolant1 &V, Real S) {
return V( max( S - D, 0. ) );
};
// Create uniformly spaced dividend payouts
for(int e = 0; e < E; ++e) {
// Time at which the event takes place
const Real te = T / E * e;
// Add the event
stepper.add(te, dividendEvent, grid);
}
*/
// Relates the value of V- to V
auto exerciseEvent = [K] (const Interpolant1 &V, Real S) {
return max( V(S) , K - S );
};
// Create uniformly spaced exercise times
for(int e = 0; e < E; ++e) {
// Time at which the event takes place
const Real te = T / E * e;
// Add the event
stepper.add(te, exerciseEvent, grid);
}
// Interest rate
const Real r = 0.04;
// Local volatility function
const Real alpha = 20.;
auto v = [alpha] (Real S) {
return alpha / S;
};
// A function of time and space could have been specified by using
// [] (Real t, Real S) { ... }
// Dividends
const Real q = 0.;
// Black-Scholes operator
BlackScholes1 bs(grid, r, v, q);
// Backward-differentiation formula of order two
ReverseBDFTwo1 bdf2(grid, bs);
bdf2.setIteration(stepper);
// Linear system solver
BiCGSTABSolver solver;
// Get the solution
auto V = stepper.solve(
grid, // Domain
payoff, // Initial condition
bdf2, // Backward-differentiation formula
solver // Linear system solver
);
// Axis::range(a, b, c) creates ticks a to c using a step-size of b
// This is equivalent to the a:b:c notation used in MATLAB/Octave
RectilinearGrid1 printGrid( Axis::range(0., 10., 200.) );
cout << accessor( printGrid, V );
} // main()
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013.
// 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 <stdarg.h>
#include "console.hpp"
#include "types.hpp"
namespace {
long current_line = 0;
long current_column = 0;
enum vga_color {
BLACK = 0,
BLUE = 1,
GREEN = 2,
CYAN = 3,
RED = 4,
MAGENTA = 5,
BROWN = 6,
LIGHT_GREY = 7,
DARK_GREY = 8,
LIGHT_BLUE = 9,
LIGHT_GREEN = 10,
LIGHT_CYAN = 11,
LIGHT_RED = 12,
LIGHT_MAGENTA = 13,
LIGHT_BROWN = 14,
WHITE = 15,
};
uint8_t make_color(vga_color fg, vga_color bg){
return fg | bg << 4;
}
uint16_t make_vga_entry(char c, uint8_t color){
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
template<typename N>
uint64_t digits(N number){
if(number < 10){
return 1;
}
uint64_t i = 0;
while(number != 0){
number /= 10;
++i;
}
return i;
}
template<int B, typename D>
void print_unsigned(D number){
if(number == 0){
k_print('0');
return;
}
char buffer[B];
int i = 0;
while(number != 0){
buffer[i++] = '0' + number % 10;
number /= 10;
}
--i;
for(; i >= 0; --i){
k_print(buffer[i]);
}
}
} //end of anonymous namespace
void set_column(long column){
current_column = column;
}
long get_column(){
return current_column;
}
void set_line(long line){
current_line= line;
}
long get_line(){
return current_line;
}
void k_print(uint8_t number){
print_unsigned<3>(number);
}
void k_print(uint16_t number){
print_unsigned<5>(number);
}
void k_print(uint32_t number){
print_unsigned<10>(number);
}
void k_print(uint64_t number){
print_unsigned<20>(number);
}
void k_print(char key){
if(key == '\n'){
++current_line;
current_column = 0;
} else if(key == '\t'){
k_print(" ");
} else {
uint16_t* vga_buffer = reinterpret_cast<uint16_t*>(0x0B8000);
vga_buffer[current_line * 80 + current_column] = make_vga_entry(key, make_color(WHITE, BLACK));
++current_column;
}
}
void k_print(const char* string){
for(uint64_t i = 0; string[i] != 0; ++i){
k_print(string[i]);
}
}
void k_print(const char* string, uint64_t end){
for(uint64_t i = 0; string[i] != 0 && i < end; ++i){
k_print(string[i]);
}
}
void wipeout(){
current_line = 0;
current_column = 0;
for(int line = 0; line < 25; ++line){
for(uint64_t column = 0; column < 80; ++column){
k_print(' ');
}
}
current_line = 0;
current_column = 0;
}
void k_printf(const char* fmt, ...){
va_list va;
va_start(va, fmt);
char ch;
while ((ch=*(fmt++))) {
if(ch != '%'){
k_print(ch);
} else {
ch = *(fmt++);
uint64_t min_width = 0;
while(ch >= '0' && ch <= '9'){
min_width = 10 * min_width + (ch - '0');
ch = *(fmt++);
}
uint64_t min_digits = 0;
if(ch == '.'){
ch = *(fmt++);
while(ch >= '0' && ch <= '9'){
min_digits = 10 * min_digits + (ch - '0');
ch = *(fmt++);
}
}
auto prev = current_column;
//Decimal
if(ch == 'd'){
auto arg = va_arg(va, uint64_t);
if(min_digits > 0){
auto d = digits(arg);
if(min_digits > d){
min_digits -= d;
while(min_digits > 0){
while(min_digits > 0){
k_print('0');
--min_digits;
}
}
}
}
k_print(arg);
}
//Hexadecimal
else if(ch == 'h'){
k_print("0x");
uint8_t buffer[20];
auto arg = va_arg(va, uint64_t);
int i = 0;
while(arg / 16 != 0){
buffer[i++] = arg % 16;
arg /= 16;
}
buffer[i] = arg;
if(min_digits > 0 && min_digits > i){
min_digits -= i + 1;
while(min_digits > 0){
k_print('0');
--min_digits;
}
}
while(i >= 0){
uint8_t digit = buffer[i];
if(digit < 10){
k_print(static_cast<char>('0' + digit));
} else {
switch(digit){
case 10:
k_print('A');
break;
case 11:
k_print('B');
break;
case 12:
k_print('C');
break;
case 13:
k_print('D');
break;
case 14:
k_print('E');
break;
case 15:
k_print('F');
break;
}
}
--i;
}
}
//Memory
else if(ch == 'm'){
auto memory= va_arg(va, uint64_t);
if(memory > 1024 * 1024 * 1024){
k_print(memory / (1024 * 1024 * 1024));
k_print("GiB");
} else if(memory > 1024 * 1024){
k_print(memory / (1024 * 1024));
k_print("MiB");
} else if(memory > 1024){
k_print(memory / 1024);
k_print("KiB");
} else {
k_print(memory);
k_print("B");
}
}
//String
else if(ch == 's'){
auto arg = va_arg(va, const char*);
k_print(arg);
}
if(min_width > 0){
auto width = current_column - prev;
if(min_width > width){
min_width -= width;
while(min_width > 0){
k_print(' ');
--min_width;
}
}
}
}
}
va_end(va);
}
<commit_msg>Fix current line when overflowing the line<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013.
// 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 <stdarg.h>
#include "console.hpp"
#include "types.hpp"
namespace {
long current_line = 0;
long current_column = 0;
enum vga_color {
BLACK = 0,
BLUE = 1,
GREEN = 2,
CYAN = 3,
RED = 4,
MAGENTA = 5,
BROWN = 6,
LIGHT_GREY = 7,
DARK_GREY = 8,
LIGHT_BLUE = 9,
LIGHT_GREEN = 10,
LIGHT_CYAN = 11,
LIGHT_RED = 12,
LIGHT_MAGENTA = 13,
LIGHT_BROWN = 14,
WHITE = 15,
};
uint8_t make_color(vga_color fg, vga_color bg){
return fg | bg << 4;
}
uint16_t make_vga_entry(char c, uint8_t color){
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
template<typename N>
uint64_t digits(N number){
if(number < 10){
return 1;
}
uint64_t i = 0;
while(number != 0){
number /= 10;
++i;
}
return i;
}
template<int B, typename D>
void print_unsigned(D number){
if(number == 0){
k_print('0');
return;
}
char buffer[B];
int i = 0;
while(number != 0){
buffer[i++] = '0' + number % 10;
number /= 10;
}
--i;
for(; i >= 0; --i){
k_print(buffer[i]);
}
}
} //end of anonymous namespace
void set_column(long column){
current_column = column;
}
long get_column(){
return current_column;
}
void set_line(long line){
current_line= line;
}
long get_line(){
return current_line;
}
void k_print(uint8_t number){
print_unsigned<3>(number);
}
void k_print(uint16_t number){
print_unsigned<5>(number);
}
void k_print(uint32_t number){
print_unsigned<10>(number);
}
void k_print(uint64_t number){
print_unsigned<20>(number);
}
void k_print(char key){
if(key == '\n'){
++current_line;
current_column = 0;
} else if(key == '\t'){
k_print(" ");
} else {
uint16_t* vga_buffer = reinterpret_cast<uint16_t*>(0x0B8000);
vga_buffer[current_line * 80 + current_column] = make_vga_entry(key, make_color(WHITE, BLACK));
++current_column;
if(current_column == 80){
current_column = 0;
++current_line;
}
}
}
void k_print(const char* string){
for(uint64_t i = 0; string[i] != 0; ++i){
k_print(string[i]);
}
}
void k_print(const char* string, uint64_t end){
for(uint64_t i = 0; string[i] != 0 && i < end; ++i){
k_print(string[i]);
}
}
void wipeout(){
current_line = 0;
current_column = 0;
for(int line = 0; line < 25; ++line){
for(uint64_t column = 0; column < 80; ++column){
k_print(' ');
}
}
current_line = 0;
current_column = 0;
}
void k_printf(const char* fmt, ...){
va_list va;
va_start(va, fmt);
char ch;
while ((ch=*(fmt++))) {
if(ch != '%'){
k_print(ch);
} else {
ch = *(fmt++);
uint64_t min_width = 0;
while(ch >= '0' && ch <= '9'){
min_width = 10 * min_width + (ch - '0');
ch = *(fmt++);
}
uint64_t min_digits = 0;
if(ch == '.'){
ch = *(fmt++);
while(ch >= '0' && ch <= '9'){
min_digits = 10 * min_digits + (ch - '0');
ch = *(fmt++);
}
}
auto prev = current_column;
//Decimal
if(ch == 'd'){
auto arg = va_arg(va, uint64_t);
if(min_digits > 0){
auto d = digits(arg);
if(min_digits > d){
min_digits -= d;
while(min_digits > 0){
while(min_digits > 0){
k_print('0');
--min_digits;
}
}
}
}
k_print(arg);
}
//Hexadecimal
else if(ch == 'h'){
k_print("0x");
uint8_t buffer[20];
auto arg = va_arg(va, uint64_t);
int i = 0;
while(arg / 16 != 0){
buffer[i++] = arg % 16;
arg /= 16;
}
buffer[i] = arg;
if(min_digits > 0 && min_digits > i){
min_digits -= i + 1;
while(min_digits > 0){
k_print('0');
--min_digits;
}
}
while(i >= 0){
uint8_t digit = buffer[i];
if(digit < 10){
k_print(static_cast<char>('0' + digit));
} else {
switch(digit){
case 10:
k_print('A');
break;
case 11:
k_print('B');
break;
case 12:
k_print('C');
break;
case 13:
k_print('D');
break;
case 14:
k_print('E');
break;
case 15:
k_print('F');
break;
}
}
--i;
}
}
//Memory
else if(ch == 'm'){
auto memory= va_arg(va, uint64_t);
if(memory > 1024 * 1024 * 1024){
k_print(memory / (1024 * 1024 * 1024));
k_print("GiB");
} else if(memory > 1024 * 1024){
k_print(memory / (1024 * 1024));
k_print("MiB");
} else if(memory > 1024){
k_print(memory / 1024);
k_print("KiB");
} else {
k_print(memory);
k_print("B");
}
}
//String
else if(ch == 's'){
auto arg = va_arg(va, const char*);
k_print(arg);
}
if(min_width > 0){
auto width = current_column - prev;
if(min_width > width){
min_width -= width;
while(min_width > 0){
k_print(' ');
--min_width;
}
}
}
}
}
va_end(va);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: interpr6.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: nn $ $Date: 2001-01-05 18:27:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "core_pch.hxx"
#endif
#pragma hdrstop
#include <math.h>
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "interpre.hxx"
//! #66556# for os2icci3 this function MUST be compiled without optimizations,
//! otherwise it won't work at all or even worse will produce false results!
double ScInterpreter::GetGammaDist(double x, double alpha, double beta)
{
if (x == 0.0)
return 0.0;
x /= beta;
double gamma = alpha;
double c = 0.918938533204672741;
double d[10] = {
0.833333333333333333E-1,
-0.277777777777777778E-2,
0.793650793650793651E-3,
-0.595238095238095238E-3,
0.841750841750841751E-3,
-0.191752691752691753E-2,
0.641025641025641025E-2,
-0.295506535947712418E-1,
0.179644372368830573,
-0.139243221690590111E1
};
int ipr = 6;
double dx = x;
double dgamma = gamma;
int maxit = 10000;
double z = dgamma;
double den = 1.0;
while ( z < 10.0 ) //! approx?
{
den *= z;
z += 1.0;
}
double z2 = z*z;
double z3 = z*z2;
double z4 = z2*z2;
double z5 = z2*z3;
double a = ( z - 0.5 ) * log(z) - z + c;
double b = d[0]/z + d[1]/z3 + d[2]/z5 + d[3]/(z2*z5) + d[4]/(z4*z5) +
d[5]/(z*z5*z5) + d[6]/(z3*z5*z5) + d[7]/(z5*z5*z5) + d[8]/(z2*z5*z5*z5);
// double g = exp(a+b) / den;
double sum = 1.0 / dgamma;
double term = 1.0 / dgamma;
double cut1 = dx - dgamma;
double cut2 = dx * 10000000000.0;
for ( int i=1; i<=maxit; i++ )
{
double ai = i;
term = dx * term / ( dgamma + ai );
sum += term;
double cutoff = cut1 + ( cut2 * term / sum );
if ( ai > cutoff )
{
double t = sum;
// return pow( dx, dgamma ) * exp( -dx ) * t / g;
return exp( dgamma * log(dx) - dx - a - b ) * t * den;
}
}
// DBG_ERROR("GetGammaDist bricht nicht ab");
return 1.0; // should not happen ...
}
#if 0
//! this algorithm doesn't work right in every cases!
double ScInterpreter::GetGammaDist(double x, double alpha, double beta)
{
if (x == 0.0)
return 0.0;
double fEps = 1.0E-6;
double fGamma;
double G = GetLogGamma(alpha);
x /= beta;
G = alpha*log(x)-x-G;
if (x <= alpha+1.0)
{
if (x < fEps || fabs(G) >= 500.0)
fGamma = 0.0;
else
{
double fF = 1.0/alpha;
double fS = fF;
double anum = alpha;
for (USHORT i = 0; i < 100; i++)
{
anum += 1.0;
fF *= x/anum;
fS += fF;
if (fF < fEps)
i = 100;
}
fGamma = fS*exp(G);
}
}
else
{
if (fabs(G) >= 500.0)
fGamma = 1.0;
else
{
double a0, b0, a1, b1, cf, fnorm, a2j, a2j1, cfnew;
a0 = 0.0; b0 = 1.0; a1 = 1.0;
b1 = x;
cf = fEps;
fnorm = 1.0;
cfnew = 0.0;
for (USHORT j = 1; j <= 100; j++)
{
a2j = ((double) j) - alpha;
a2j1 = (double) j;
a0 = (a1+a2j*a0); // *fnorm;
b0 = (b1+a2j*b0); // *fnorm;
a1 = (x*a0+a2j1*a1)*fnorm;
b1 = (x*b0+a2j1*b1)*fnorm;
if (b1 != 0.0)
{
fnorm = 1.0/b1;
cfnew = a1*fnorm;
if (fabs(cf-cfnew)/cf < fEps)
j = 101;
else
cf = cfnew;
}
}
fGamma = 1.0 - exp(G)*cfnew;
}
}
return fGamma;
}
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.936); FILE MERGED 2005/09/05 15:02:05 rt 1.2.936.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: interpr6.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:46:03 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "core_pch.hxx"
#endif
#pragma hdrstop
#include <math.h>
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "interpre.hxx"
//! #66556# for os2icci3 this function MUST be compiled without optimizations,
//! otherwise it won't work at all or even worse will produce false results!
double ScInterpreter::GetGammaDist(double x, double alpha, double beta)
{
if (x == 0.0)
return 0.0;
x /= beta;
double gamma = alpha;
double c = 0.918938533204672741;
double d[10] = {
0.833333333333333333E-1,
-0.277777777777777778E-2,
0.793650793650793651E-3,
-0.595238095238095238E-3,
0.841750841750841751E-3,
-0.191752691752691753E-2,
0.641025641025641025E-2,
-0.295506535947712418E-1,
0.179644372368830573,
-0.139243221690590111E1
};
int ipr = 6;
double dx = x;
double dgamma = gamma;
int maxit = 10000;
double z = dgamma;
double den = 1.0;
while ( z < 10.0 ) //! approx?
{
den *= z;
z += 1.0;
}
double z2 = z*z;
double z3 = z*z2;
double z4 = z2*z2;
double z5 = z2*z3;
double a = ( z - 0.5 ) * log(z) - z + c;
double b = d[0]/z + d[1]/z3 + d[2]/z5 + d[3]/(z2*z5) + d[4]/(z4*z5) +
d[5]/(z*z5*z5) + d[6]/(z3*z5*z5) + d[7]/(z5*z5*z5) + d[8]/(z2*z5*z5*z5);
// double g = exp(a+b) / den;
double sum = 1.0 / dgamma;
double term = 1.0 / dgamma;
double cut1 = dx - dgamma;
double cut2 = dx * 10000000000.0;
for ( int i=1; i<=maxit; i++ )
{
double ai = i;
term = dx * term / ( dgamma + ai );
sum += term;
double cutoff = cut1 + ( cut2 * term / sum );
if ( ai > cutoff )
{
double t = sum;
// return pow( dx, dgamma ) * exp( -dx ) * t / g;
return exp( dgamma * log(dx) - dx - a - b ) * t * den;
}
}
// DBG_ERROR("GetGammaDist bricht nicht ab");
return 1.0; // should not happen ...
}
#if 0
//! this algorithm doesn't work right in every cases!
double ScInterpreter::GetGammaDist(double x, double alpha, double beta)
{
if (x == 0.0)
return 0.0;
double fEps = 1.0E-6;
double fGamma;
double G = GetLogGamma(alpha);
x /= beta;
G = alpha*log(x)-x-G;
if (x <= alpha+1.0)
{
if (x < fEps || fabs(G) >= 500.0)
fGamma = 0.0;
else
{
double fF = 1.0/alpha;
double fS = fF;
double anum = alpha;
for (USHORT i = 0; i < 100; i++)
{
anum += 1.0;
fF *= x/anum;
fS += fF;
if (fF < fEps)
i = 100;
}
fGamma = fS*exp(G);
}
}
else
{
if (fabs(G) >= 500.0)
fGamma = 1.0;
else
{
double a0, b0, a1, b1, cf, fnorm, a2j, a2j1, cfnew;
a0 = 0.0; b0 = 1.0; a1 = 1.0;
b1 = x;
cf = fEps;
fnorm = 1.0;
cfnew = 0.0;
for (USHORT j = 1; j <= 100; j++)
{
a2j = ((double) j) - alpha;
a2j1 = (double) j;
a0 = (a1+a2j*a0); // *fnorm;
b0 = (b1+a2j*b0); // *fnorm;
a1 = (x*a0+a2j1*a1)*fnorm;
b1 = (x*b0+a2j1*b1)*fnorm;
if (b1 != 0.0)
{
fnorm = 1.0/b1;
cfnew = a1*fnorm;
if (fabs(cf-cfnew)/cf < fEps)
j = 101;
else
cf = cfnew;
}
}
fGamma = 1.0 - exp(G)*cfnew;
}
}
return fGamma;
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************/
/* remote_transform_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 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 "remote_transform_2d.h"
#include "scene/scene_string_names.h"
void RemoteTransform2D::_update_cache() {
cache = 0;
if (has_node(remote_node)) {
Node *node = get_node(remote_node);
if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
return;
}
cache = node->get_instance_id();
}
}
void RemoteTransform2D::_update_remote() {
if (!is_inside_tree())
return;
if (!cache)
return;
Node2D *n = Object::cast_to<Node2D>(ObjectDB::get_instance(cache));
if (!n)
return;
if (!n->is_inside_tree())
return;
//todo make faster
if (use_global_coordinates) {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_global_transform(get_global_transform());
} else {
Transform2D n_trans = n->get_global_transform();
Transform2D our_trans = get_global_transform();
Vector2 n_scale = n->get_global_scale();
if (!update_remote_position)
our_trans.set_origin(n_trans.get_origin());
if (!update_remote_rotation)
our_trans.set_rotation(n_trans.get_rotation());
n->set_global_transform(our_trans);
if (update_remote_scale)
n->set_scale(get_global_scale());
else
n->set_scale(n_scale);
}
} else {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_transform(get_transform());
} else {
Transform2D n_trans = n->get_transform();
Transform2D our_trans = get_transform();
Vector2 n_scale = n->get_scale();
if (!update_remote_position)
our_trans.set_origin(n_trans.get_origin());
if (!update_remote_rotation)
our_trans.set_rotation(n_trans.get_rotation());
n->set_transform(our_trans);
if (update_remote_scale)
n->set_scale(get_scale());
else
n->set_scale(n_scale);
}
}
}
void RemoteTransform2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY: {
_update_cache();
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
if (!is_inside_tree())
break;
if (cache) {
_update_remote();
}
} break;
}
}
void RemoteTransform2D::set_remote_node(const NodePath &p_remote_node) {
remote_node = p_remote_node;
if (is_inside_tree())
_update_cache();
update_configuration_warning();
}
NodePath RemoteTransform2D::get_remote_node() const {
return remote_node;
}
void RemoteTransform2D::set_use_global_coordinates(const bool p_enable) {
use_global_coordinates = p_enable;
}
bool RemoteTransform2D::get_use_global_coordinates() const {
return use_global_coordinates;
}
void RemoteTransform2D::set_update_position(const bool p_update) {
update_remote_position = p_update;
_update_remote();
}
bool RemoteTransform2D::get_update_position() const {
return update_remote_position;
}
void RemoteTransform2D::set_update_rotation(const bool p_update) {
update_remote_rotation = p_update;
_update_remote();
}
bool RemoteTransform2D::get_update_rotation() const {
return update_remote_rotation;
}
void RemoteTransform2D::set_update_scale(const bool p_update) {
update_remote_scale = p_update;
_update_remote();
}
bool RemoteTransform2D::get_update_scale() const {
return update_remote_scale;
}
String RemoteTransform2D::get_configuration_warning() const {
if (!has_node(remote_node) || !Object::cast_to<Node2D>(get_node(remote_node))) {
return TTR("Path property must point to a valid Node2D node to work.");
}
return String();
}
void RemoteTransform2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform2D::set_remote_node);
ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform2D::get_remote_node);
ClassDB::bind_method(D_METHOD("set_use_global_coordinates", "use_global_coordinates"), &RemoteTransform2D::set_use_global_coordinates);
ClassDB::bind_method(D_METHOD("get_use_global_coordinates"), &RemoteTransform2D::get_use_global_coordinates);
ClassDB::bind_method(D_METHOD("set_update_position", "update_remote_position"), &RemoteTransform2D::set_update_position);
ClassDB::bind_method(D_METHOD("get_update_position"), &RemoteTransform2D::get_update_position);
ClassDB::bind_method(D_METHOD("set_update_rotation", "update_remote_rotation"), &RemoteTransform2D::set_update_rotation);
ClassDB::bind_method(D_METHOD("get_update_rotation"), &RemoteTransform2D::get_update_rotation);
ClassDB::bind_method(D_METHOD("set_update_scale", "update_remote_scale"), &RemoteTransform2D::set_update_scale);
ClassDB::bind_method(D_METHOD("get_update_scale"), &RemoteTransform2D::get_update_scale);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_remote_node", "get_remote_node");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_global_coordinates"), "set_use_global_coordinates", "get_use_global_coordinates");
ADD_GROUP("Update", "update_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_position"), "set_update_position", "get_update_position");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_rotation"), "set_update_rotation", "get_update_rotation");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_scale"), "set_update_scale", "get_update_scale");
}
RemoteTransform2D::RemoteTransform2D() {
use_global_coordinates = true;
update_remote_position = true;
update_remote_rotation = true;
update_remote_scale = true;
cache = 0;
set_notify_transform(true);
}
<commit_msg>Fix properly keep scale in RemoteTransform2D, fixes #17692, closes #17690<commit_after>/*************************************************************************/
/* remote_transform_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 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 "remote_transform_2d.h"
#include "scene/scene_string_names.h"
void RemoteTransform2D::_update_cache() {
cache = 0;
if (has_node(remote_node)) {
Node *node = get_node(remote_node);
if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
return;
}
cache = node->get_instance_id();
}
}
void RemoteTransform2D::_update_remote() {
if (!is_inside_tree())
return;
if (!cache)
return;
Node2D *n = Object::cast_to<Node2D>(ObjectDB::get_instance(cache));
if (!n)
return;
if (!n->is_inside_tree())
return;
//todo make faster
if (use_global_coordinates) {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_global_transform(get_global_transform());
} else {
Transform2D n_trans = n->get_global_transform();
Transform2D our_trans = get_global_transform();
Vector2 n_scale = n->get_scale();
if (!update_remote_position)
our_trans.set_origin(n_trans.get_origin());
if (!update_remote_rotation)
our_trans.set_rotation(n_trans.get_rotation());
n->set_global_transform(our_trans);
if (update_remote_scale)
n->set_scale(get_global_scale());
else
n->set_scale(n_scale);
}
} else {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_transform(get_transform());
} else {
Transform2D n_trans = n->get_transform();
Transform2D our_trans = get_transform();
Vector2 n_scale = n->get_scale();
if (!update_remote_position)
our_trans.set_origin(n_trans.get_origin());
if (!update_remote_rotation)
our_trans.set_rotation(n_trans.get_rotation());
n->set_transform(our_trans);
if (update_remote_scale)
n->set_scale(get_scale());
else
n->set_scale(n_scale);
}
}
}
void RemoteTransform2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY: {
_update_cache();
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
if (!is_inside_tree())
break;
if (cache) {
_update_remote();
}
} break;
}
}
void RemoteTransform2D::set_remote_node(const NodePath &p_remote_node) {
remote_node = p_remote_node;
if (is_inside_tree())
_update_cache();
update_configuration_warning();
}
NodePath RemoteTransform2D::get_remote_node() const {
return remote_node;
}
void RemoteTransform2D::set_use_global_coordinates(const bool p_enable) {
use_global_coordinates = p_enable;
}
bool RemoteTransform2D::get_use_global_coordinates() const {
return use_global_coordinates;
}
void RemoteTransform2D::set_update_position(const bool p_update) {
update_remote_position = p_update;
_update_remote();
}
bool RemoteTransform2D::get_update_position() const {
return update_remote_position;
}
void RemoteTransform2D::set_update_rotation(const bool p_update) {
update_remote_rotation = p_update;
_update_remote();
}
bool RemoteTransform2D::get_update_rotation() const {
return update_remote_rotation;
}
void RemoteTransform2D::set_update_scale(const bool p_update) {
update_remote_scale = p_update;
_update_remote();
}
bool RemoteTransform2D::get_update_scale() const {
return update_remote_scale;
}
String RemoteTransform2D::get_configuration_warning() const {
if (!has_node(remote_node) || !Object::cast_to<Node2D>(get_node(remote_node))) {
return TTR("Path property must point to a valid Node2D node to work.");
}
return String();
}
void RemoteTransform2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform2D::set_remote_node);
ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform2D::get_remote_node);
ClassDB::bind_method(D_METHOD("set_use_global_coordinates", "use_global_coordinates"), &RemoteTransform2D::set_use_global_coordinates);
ClassDB::bind_method(D_METHOD("get_use_global_coordinates"), &RemoteTransform2D::get_use_global_coordinates);
ClassDB::bind_method(D_METHOD("set_update_position", "update_remote_position"), &RemoteTransform2D::set_update_position);
ClassDB::bind_method(D_METHOD("get_update_position"), &RemoteTransform2D::get_update_position);
ClassDB::bind_method(D_METHOD("set_update_rotation", "update_remote_rotation"), &RemoteTransform2D::set_update_rotation);
ClassDB::bind_method(D_METHOD("get_update_rotation"), &RemoteTransform2D::get_update_rotation);
ClassDB::bind_method(D_METHOD("set_update_scale", "update_remote_scale"), &RemoteTransform2D::set_update_scale);
ClassDB::bind_method(D_METHOD("get_update_scale"), &RemoteTransform2D::get_update_scale);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_remote_node", "get_remote_node");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_global_coordinates"), "set_use_global_coordinates", "get_use_global_coordinates");
ADD_GROUP("Update", "update_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_position"), "set_update_position", "get_update_position");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_rotation"), "set_update_rotation", "get_update_rotation");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_scale"), "set_update_scale", "get_update_scale");
}
RemoteTransform2D::RemoteTransform2D() {
use_global_coordinates = true;
update_remote_position = true;
update_remote_rotation = true;
update_remote_scale = true;
cache = 0;
set_notify_transform(true);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, Inc.
*
* 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 "dcp_mutation.h"
#include "engine_wrapper.h"
#include "utilities.h"
#include "../../mcbp.h"
#include <platform/compress.h>
#include <limits>
#include <stdexcept>
#include <xattr/blob.h>
#include <xattr/utils.h>
ENGINE_ERROR_CODE dcp_message_mutation(const void* void_cookie,
uint32_t opaque,
item* it,
uint16_t vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t lock_time,
const void* meta,
uint16_t nmeta,
uint8_t nru) {
auto* c = cookie2mcbp(void_cookie, __func__);
c->setCmd(PROTOCOL_BINARY_CMD_DCP_MUTATION);
// Use a unique_ptr to make sure we release the item in all error paths
cb::unique_item_ptr item(it, cb::ItemDeleter{c->getBucketEngineAsV0()});
item_info info;
if (!bucket_get_item_info(c, it, &info)) {
LOG_WARNING(c, "%u: Failed to get item info", c->getId());
return ENGINE_FAILED;
}
char* root = reinterpret_cast<char*>(info.value[0].iov_base);
cb::char_buffer buffer{root, info.value[0].iov_len};
cb::compression::Buffer inflated;
if (c->isDcpNoValue() && !c->isDcpXattrAware()) {
// The client don't want the body or any xattrs.. just
// drop everything
buffer.len = 0;
info.datatype = PROTOCOL_BINARY_RAW_BYTES;
} else if (!c->isDcpNoValue() && c->isDcpXattrAware()) {
// The client want both value and xattrs.. we don't need to
// do anything
} else {
// we want either values or xattrs
if (mcbp::datatype::is_compressed(info.datatype)) {
if (!cb::compression::inflate(
cb::compression::Algorithm::Snappy,
buffer.buf, buffer.len, inflated)) {
LOG_WARNING(c, "%u: Failed to inflate document",
c->getId());
return ENGINE_FAILED;
}
// @todo figure out this one.. Right now our tempAlloc list is
// memory allocated by cb_malloc... it would probably be
// better if we had something similar for new'd memory..
buffer.buf = reinterpret_cast<char*>(cb_malloc(inflated.len));
if (buffer.buf == nullptr) {
return ENGINE_ENOMEM;
}
buffer.len = inflated.len;
memcpy(buffer.buf, inflated.data.get(), buffer.len);
if (!c->pushTempAlloc(buffer.buf)) {
cb_free(buffer.buf);
return ENGINE_ENOMEM;
}
}
if (c->isDcpXattrAware()) {
if (mcbp::datatype::is_xattr(info.datatype)) {
buffer.len = cb::xattr::get_body_offset({buffer.buf, buffer.len});
} else {
buffer.len = 0;
info.datatype = PROTOCOL_BINARY_RAW_BYTES;
}
} else {
// we want the body
if (mcbp::datatype::is_xattr(info.datatype)) {
auto body = cb::xattr::get_body({buffer.buf, buffer.len});
buffer.buf = const_cast<char*>(body.buf);
buffer.len = body.len;
info.datatype &= ~PROTOCOL_BINARY_DATATYPE_XATTR;
}
}
}
protocol_binary_request_dcp_mutation packet;
if (c->write.bytes + sizeof(packet.bytes) + nmeta >= c->write.size) {
/* We don't have room in the buffer */
return ENGINE_E2BIG;
}
if (!c->reserveItem(it)) {
LOG_WARNING(c, "%u: Failed to grow item array", c->getId());
return ENGINE_FAILED;
}
// we've reserved the item, and it'll be released when we're done sending
// the item.
item.release();
const uint8_t extlen = 31; // 2*uint64_t, 3*uint32_t, 1*uint16_t, 1*uint8_t
const uint32_t bodylen = uint32_t(buffer.len) + extlen + nmeta + info.nkey;
memset(packet.bytes, 0, sizeof(packet));
packet.message.header.request.magic = (uint8_t)PROTOCOL_BINARY_REQ;
packet.message.header.request.opcode = (uint8_t)PROTOCOL_BINARY_CMD_DCP_MUTATION;
packet.message.header.request.opaque = opaque;
packet.message.header.request.vbucket = htons(vbucket);
packet.message.header.request.cas = htonll(info.cas);
packet.message.header.request.keylen = htons(info.nkey);
packet.message.header.request.extlen = extlen;
packet.message.header.request.bodylen = ntohl(bodylen);
packet.message.header.request.datatype = info.datatype;
packet.message.body.by_seqno = htonll(by_seqno);
packet.message.body.rev_seqno = htonll(rev_seqno);
packet.message.body.lock_time = htonl(lock_time);
packet.message.body.flags = info.flags;
packet.message.body.expiration = htonl(info.exptime);
packet.message.body.nmeta = htons(nmeta);
packet.message.body.nru = nru;
memcpy(c->write.curr, packet.bytes, sizeof(packet.bytes));
c->addIov(c->write.curr, sizeof(packet.bytes));
c->write.curr += sizeof(packet.bytes);
c->write.bytes += sizeof(packet.bytes);
c->addIov(info.key, info.nkey);
c->addIov(buffer.buf, buffer.len);
memcpy(c->write.curr, meta, nmeta);
c->addIov(c->write.curr, nmeta);
c->write.curr += nmeta;
c->write.bytes += nmeta;
return ENGINE_SUCCESS;
}
static inline ENGINE_ERROR_CODE do_dcp_mutation(McbpConnection* conn,
void* packet) {
auto* req = reinterpret_cast<protocol_binary_request_dcp_mutation*>(packet);
const uint16_t nkey = ntohs(req->message.header.request.keylen);
const DocKey key{req->bytes + sizeof(req->bytes), nkey,
DocNamespace::DefaultCollection};
const auto opaque = req->message.header.request.opaque;
const auto datatype = req->message.header.request.datatype;
const uint64_t cas = ntohll(req->message.header.request.cas);
const uint16_t vbucket = ntohs(req->message.header.request.vbucket);
const uint64_t by_seqno = ntohll(req->message.body.by_seqno);
const uint64_t rev_seqno = ntohll(req->message.body.rev_seqno);
const uint32_t flags = req->message.body.flags;
const uint32_t expiration = ntohl(req->message.body.expiration);
const uint32_t lock_time = ntohl(req->message.body.lock_time);
const uint16_t nmeta = ntohs(req->message.body.nmeta);
const uint32_t valuelen = ntohl(req->message.header.request.bodylen) -
nkey - req->message.header.request.extlen -
nmeta;
cb::const_byte_buffer value{req->bytes + sizeof(req->bytes) + nkey,
valuelen};
cb::const_byte_buffer meta{value.buf + valuelen, nmeta};
uint32_t priv_bytes = 0;
if (mcbp::datatype::is_xattr(datatype)) {
cb::const_char_buffer payload{reinterpret_cast<const char*>(value.buf),
value.len};
cb::byte_buffer buffer{const_cast<uint8_t*>(value.buf),
cb::xattr::get_body_offset(payload)};
cb::xattr::Blob blob(buffer);
priv_bytes = uint32_t(blob.get_system_size());
}
auto engine = conn->getBucketEngine();
return engine->dcp.mutation(conn->getBucketEngineAsV0(), conn->getCookie(),
opaque, key, value, priv_bytes, datatype, cas,
vbucket, flags, by_seqno, rev_seqno, expiration,
lock_time, meta, req->message.body.nru);
}
void dcp_mutation_executor(McbpConnection* c, void* packet) {
ENGINE_ERROR_CODE ret = c->getAiostat();
c->setAiostat(ENGINE_SUCCESS);
c->setEwouldblock(false);
if (ret == ENGINE_SUCCESS) {
ret = do_dcp_mutation(c, packet);
}
switch (ret) {
case ENGINE_SUCCESS:
c->setState(conn_new_cmd);
break;
case ENGINE_DISCONNECT:
c->setState(conn_closing);
break;
case ENGINE_EWOULDBLOCK:
c->setEwouldblock(true);
break;
default:
mcbp_write_packet(c, engine_error_2_mcbp_protocol_error(ret));
}
}
<commit_msg>MB-23085: Strip extended datatype flags for XATTR only DCP mutation<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, Inc.
*
* 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 "dcp_mutation.h"
#include "engine_wrapper.h"
#include "utilities.h"
#include "../../mcbp.h"
#include <platform/compress.h>
#include <limits>
#include <stdexcept>
#include <xattr/blob.h>
#include <xattr/utils.h>
ENGINE_ERROR_CODE dcp_message_mutation(const void* void_cookie,
uint32_t opaque,
item* it,
uint16_t vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t lock_time,
const void* meta,
uint16_t nmeta,
uint8_t nru) {
auto* c = cookie2mcbp(void_cookie, __func__);
c->setCmd(PROTOCOL_BINARY_CMD_DCP_MUTATION);
// Use a unique_ptr to make sure we release the item in all error paths
cb::unique_item_ptr item(it, cb::ItemDeleter{c->getBucketEngineAsV0()});
item_info info;
if (!bucket_get_item_info(c, it, &info)) {
LOG_WARNING(c, "%u: Failed to get item info", c->getId());
return ENGINE_FAILED;
}
char* root = reinterpret_cast<char*>(info.value[0].iov_base);
cb::char_buffer buffer{root, info.value[0].iov_len};
cb::compression::Buffer inflated;
if (c->isDcpNoValue() && !c->isDcpXattrAware()) {
// The client don't want the body or any xattrs.. just
// drop everything
buffer.len = 0;
info.datatype = PROTOCOL_BINARY_RAW_BYTES;
} else if (!c->isDcpNoValue() && c->isDcpXattrAware()) {
// The client want both value and xattrs.. we don't need to
// do anything
} else {
// we want either values or xattrs
if (mcbp::datatype::is_compressed(info.datatype)) {
if (!cb::compression::inflate(
cb::compression::Algorithm::Snappy,
buffer.buf, buffer.len, inflated)) {
LOG_WARNING(c, "%u: Failed to inflate document",
c->getId());
return ENGINE_FAILED;
}
// @todo figure out this one.. Right now our tempAlloc list is
// memory allocated by cb_malloc... it would probably be
// better if we had something similar for new'd memory..
buffer.buf = reinterpret_cast<char*>(cb_malloc(inflated.len));
if (buffer.buf == nullptr) {
return ENGINE_ENOMEM;
}
buffer.len = inflated.len;
memcpy(buffer.buf, inflated.data.get(), buffer.len);
if (!c->pushTempAlloc(buffer.buf)) {
cb_free(buffer.buf);
return ENGINE_ENOMEM;
}
}
if (c->isDcpXattrAware()) {
if (mcbp::datatype::is_xattr(info.datatype)) {
buffer.len = cb::xattr::get_body_offset({buffer.buf, buffer.len});
// MB-23085 - Remove all other datatype flags as we're only
// sending the xattrs
info.datatype = PROTOCOL_BINARY_DATATYPE_XATTR;
} else {
buffer.len = 0;
info.datatype = PROTOCOL_BINARY_RAW_BYTES;
}
} else {
// we want the body
if (mcbp::datatype::is_xattr(info.datatype)) {
auto body = cb::xattr::get_body({buffer.buf, buffer.len});
buffer.buf = const_cast<char*>(body.buf);
buffer.len = body.len;
info.datatype &= ~PROTOCOL_BINARY_DATATYPE_XATTR;
}
}
}
protocol_binary_request_dcp_mutation packet;
if (c->write.bytes + sizeof(packet.bytes) + nmeta >= c->write.size) {
/* We don't have room in the buffer */
return ENGINE_E2BIG;
}
if (!c->reserveItem(it)) {
LOG_WARNING(c, "%u: Failed to grow item array", c->getId());
return ENGINE_FAILED;
}
// we've reserved the item, and it'll be released when we're done sending
// the item.
item.release();
const uint8_t extlen = 31; // 2*uint64_t, 3*uint32_t, 1*uint16_t, 1*uint8_t
const uint32_t bodylen = uint32_t(buffer.len) + extlen + nmeta + info.nkey;
memset(packet.bytes, 0, sizeof(packet));
packet.message.header.request.magic = (uint8_t)PROTOCOL_BINARY_REQ;
packet.message.header.request.opcode = (uint8_t)PROTOCOL_BINARY_CMD_DCP_MUTATION;
packet.message.header.request.opaque = opaque;
packet.message.header.request.vbucket = htons(vbucket);
packet.message.header.request.cas = htonll(info.cas);
packet.message.header.request.keylen = htons(info.nkey);
packet.message.header.request.extlen = extlen;
packet.message.header.request.bodylen = ntohl(bodylen);
packet.message.header.request.datatype = info.datatype;
packet.message.body.by_seqno = htonll(by_seqno);
packet.message.body.rev_seqno = htonll(rev_seqno);
packet.message.body.lock_time = htonl(lock_time);
packet.message.body.flags = info.flags;
packet.message.body.expiration = htonl(info.exptime);
packet.message.body.nmeta = htons(nmeta);
packet.message.body.nru = nru;
memcpy(c->write.curr, packet.bytes, sizeof(packet.bytes));
c->addIov(c->write.curr, sizeof(packet.bytes));
c->write.curr += sizeof(packet.bytes);
c->write.bytes += sizeof(packet.bytes);
c->addIov(info.key, info.nkey);
c->addIov(buffer.buf, buffer.len);
memcpy(c->write.curr, meta, nmeta);
c->addIov(c->write.curr, nmeta);
c->write.curr += nmeta;
c->write.bytes += nmeta;
return ENGINE_SUCCESS;
}
static inline ENGINE_ERROR_CODE do_dcp_mutation(McbpConnection* conn,
void* packet) {
auto* req = reinterpret_cast<protocol_binary_request_dcp_mutation*>(packet);
const uint16_t nkey = ntohs(req->message.header.request.keylen);
const DocKey key{req->bytes + sizeof(req->bytes), nkey,
DocNamespace::DefaultCollection};
const auto opaque = req->message.header.request.opaque;
const auto datatype = req->message.header.request.datatype;
const uint64_t cas = ntohll(req->message.header.request.cas);
const uint16_t vbucket = ntohs(req->message.header.request.vbucket);
const uint64_t by_seqno = ntohll(req->message.body.by_seqno);
const uint64_t rev_seqno = ntohll(req->message.body.rev_seqno);
const uint32_t flags = req->message.body.flags;
const uint32_t expiration = ntohl(req->message.body.expiration);
const uint32_t lock_time = ntohl(req->message.body.lock_time);
const uint16_t nmeta = ntohs(req->message.body.nmeta);
const uint32_t valuelen = ntohl(req->message.header.request.bodylen) -
nkey - req->message.header.request.extlen -
nmeta;
cb::const_byte_buffer value{req->bytes + sizeof(req->bytes) + nkey,
valuelen};
cb::const_byte_buffer meta{value.buf + valuelen, nmeta};
uint32_t priv_bytes = 0;
if (mcbp::datatype::is_xattr(datatype)) {
cb::const_char_buffer payload{reinterpret_cast<const char*>(value.buf),
value.len};
cb::byte_buffer buffer{const_cast<uint8_t*>(value.buf),
cb::xattr::get_body_offset(payload)};
cb::xattr::Blob blob(buffer);
priv_bytes = uint32_t(blob.get_system_size());
}
auto engine = conn->getBucketEngine();
return engine->dcp.mutation(conn->getBucketEngineAsV0(), conn->getCookie(),
opaque, key, value, priv_bytes, datatype, cas,
vbucket, flags, by_seqno, rev_seqno, expiration,
lock_time, meta, req->message.body.nru);
}
void dcp_mutation_executor(McbpConnection* c, void* packet) {
ENGINE_ERROR_CODE ret = c->getAiostat();
c->setAiostat(ENGINE_SUCCESS);
c->setEwouldblock(false);
if (ret == ENGINE_SUCCESS) {
ret = do_dcp_mutation(c, packet);
}
switch (ret) {
case ENGINE_SUCCESS:
c->setState(conn_new_cmd);
break;
case ENGINE_DISCONNECT:
c->setState(conn_closing);
break;
case ENGINE_EWOULDBLOCK:
c->setEwouldblock(true);
break;
default:
mcbp_write_packet(c, engine_error_2_mcbp_protocol_error(ret));
}
}
<|endoftext|> |
<commit_before>//
// TimeLine.cpp
// Natron
//
// Created by Frédéric Devernay on 24/09/13.
//
//
#include "TimeLine.h"
#ifndef NDEBUG
#include <QThread>
#include <QCoreApplication>
#endif
#include <cassert>
#include "Engine/Project.h"
#include "Engine/AppInstance.h"
#include "Engine/Node.h"
#include "Engine/EffectInstance.h"
TimeLine::TimeLine(Natron::Project* project)
: _currentFrame(1)
, _keyframes()
, _project(project)
{
}
SequenceTime
TimeLine::currentFrame() const
{
QMutexLocker l(&_lock);
return _currentFrame;
}
void
TimeLine::seekFrame(SequenceTime frame,
bool updateLastCaller,
Natron::OutputEffectInstance* caller,
Natron::TimelineChangeReasonEnum reason)
{
bool changed = false;
{
QMutexLocker l(&_lock);
if (_currentFrame != frame) {
_currentFrame = frame;
changed = true;
}
}
if (_project && updateLastCaller) {
_project->getApp()->setLastViewerUsingTimeline(caller->getNode());
}
if (changed) {
emit frameChanged(frame, (int)reason);
}
}
void
TimeLine::incrementCurrentFrame()
{
SequenceTime frame;
{
QMutexLocker l(&_lock);
++_currentFrame;
frame = _currentFrame;
}
emit frameChanged(frame, (int)Natron::eTimelineChangeReasonPlaybackSeek);
}
void
TimeLine::decrementCurrentFrame()
{
SequenceTime frame;
{
QMutexLocker l(&_lock);
--_currentFrame;
frame = _currentFrame;
}
emit frameChanged(frame, (int)Natron::eTimelineChangeReasonPlaybackSeek);
}
void
TimeLine::onFrameChanged(SequenceTime frame)
{
bool changed = false;
{
QMutexLocker l(&_lock);
if (_currentFrame != frame) {
_currentFrame = frame;
changed = true;
}
}
if (changed) {
/*This function is called in response to a signal emitted by a single timeline gui, but we also
need to sync all the other timelines potentially existing.*/
emit frameChanged(frame, (int)Natron::eTimelineChangeReasonUserSeek);
}
}
void
TimeLine::removeAllKeyframesIndicators()
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
bool wasEmpty = _keyframes.empty();
_keyframes.clear();
if (!wasEmpty) {
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::addKeyframeIndicator(SequenceTime time)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.push_back(time);
emit keyframeIndicatorsChanged();
}
void
TimeLine::addMultipleKeyframeIndicatorsAdded(const std::list<SequenceTime> & keys,
bool emitSignal)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.insert( _keyframes.begin(),keys.begin(),keys.end() );
if (!keys.empty() && emitSignal) {
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::removeKeyFrameIndicator(SequenceTime time)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
std::list<SequenceTime>::iterator it = std::find(_keyframes.begin(), _keyframes.end(), time);
if ( it != _keyframes.end() ) {
_keyframes.erase(it);
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::removeMultipleKeyframeIndicator(const std::list<SequenceTime> & keys,
bool emitSignal)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
for (std::list<SequenceTime>::const_iterator it = keys.begin(); it != keys.end(); ++it) {
std::list<SequenceTime>::iterator it2 = std::find(_keyframes.begin(), _keyframes.end(), *it);
if ( it2 != _keyframes.end() ) {
_keyframes.erase(it2);
}
}
if (!keys.empty() && emitSignal) {
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::addNodesKeyframesToTimeline(const std::list<Natron::Node*> & nodes)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
std::list<Natron::Node*>::const_iterator next = nodes.begin();
++next;
for (std::list<Natron::Node*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it,++next) {
(*it)->showKeyframesOnTimeline( next == nodes.end() );
}
}
void
TimeLine::addNodeKeyframesToTimeline(Natron::Node* node)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
node->showKeyframesOnTimeline(true);
}
void
TimeLine::removeNodesKeyframesFromTimeline(const std::list<Natron::Node*> & nodes)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
std::list<Natron::Node*>::const_iterator next = nodes.begin();
++next;
for (std::list<Natron::Node*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it,++next) {
(*it)->hideKeyframesFromTimeline( next == nodes.end() );
}
}
void
TimeLine::removeNodeKeyframesFromTimeline(Natron::Node* node)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
node->hideKeyframesFromTimeline(true);
}
void
TimeLine::getKeyframes(std::list<SequenceTime>* keys) const
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
*keys = _keyframes;
}
void
TimeLine::goToPreviousKeyframe()
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.sort();
std::list<SequenceTime>::iterator lowerBound = std::lower_bound(_keyframes.begin(), _keyframes.end(), _currentFrame);
if ( lowerBound != _keyframes.begin() ) {
--lowerBound;
seekFrame(*lowerBound, true, NULL, Natron::eTimelineChangeReasonPlaybackSeek);
}
}
void
TimeLine::goToNextKeyframe()
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.sort();
std::list<SequenceTime>::iterator upperBound = std::upper_bound(_keyframes.begin(), _keyframes.end(), _currentFrame);
if ( upperBound != _keyframes.end() ) {
seekFrame(*upperBound, true, NULL, Natron::eTimelineChangeReasonPlaybackSeek);
}
}
<commit_msg>Fix another wrong pointer usage<commit_after>//
// TimeLine.cpp
// Natron
//
// Created by Frédéric Devernay on 24/09/13.
//
//
#include "TimeLine.h"
#ifndef NDEBUG
#include <QThread>
#include <QCoreApplication>
#endif
#include <cassert>
#include "Engine/Project.h"
#include "Engine/AppInstance.h"
#include "Engine/Node.h"
#include "Engine/EffectInstance.h"
TimeLine::TimeLine(Natron::Project* project)
: _currentFrame(1)
, _keyframes()
, _project(project)
{
}
SequenceTime
TimeLine::currentFrame() const
{
QMutexLocker l(&_lock);
return _currentFrame;
}
void
TimeLine::seekFrame(SequenceTime frame,
bool updateLastCaller,
Natron::OutputEffectInstance* caller,
Natron::TimelineChangeReasonEnum reason)
{
bool changed = false;
{
QMutexLocker l(&_lock);
if (_currentFrame != frame) {
_currentFrame = frame;
changed = true;
}
}
if (_project && updateLastCaller) {
_project->getApp()->setLastViewerUsingTimeline(caller ? caller->getNode() : boost::shared_ptr<Natron::Node>());
}
if (changed) {
emit frameChanged(frame, (int)reason);
}
}
void
TimeLine::incrementCurrentFrame()
{
SequenceTime frame;
{
QMutexLocker l(&_lock);
++_currentFrame;
frame = _currentFrame;
}
emit frameChanged(frame, (int)Natron::eTimelineChangeReasonPlaybackSeek);
}
void
TimeLine::decrementCurrentFrame()
{
SequenceTime frame;
{
QMutexLocker l(&_lock);
--_currentFrame;
frame = _currentFrame;
}
emit frameChanged(frame, (int)Natron::eTimelineChangeReasonPlaybackSeek);
}
void
TimeLine::onFrameChanged(SequenceTime frame)
{
bool changed = false;
{
QMutexLocker l(&_lock);
if (_currentFrame != frame) {
_currentFrame = frame;
changed = true;
}
}
if (changed) {
/*This function is called in response to a signal emitted by a single timeline gui, but we also
need to sync all the other timelines potentially existing.*/
emit frameChanged(frame, (int)Natron::eTimelineChangeReasonUserSeek);
}
}
void
TimeLine::removeAllKeyframesIndicators()
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
bool wasEmpty = _keyframes.empty();
_keyframes.clear();
if (!wasEmpty) {
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::addKeyframeIndicator(SequenceTime time)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.push_back(time);
emit keyframeIndicatorsChanged();
}
void
TimeLine::addMultipleKeyframeIndicatorsAdded(const std::list<SequenceTime> & keys,
bool emitSignal)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.insert( _keyframes.begin(),keys.begin(),keys.end() );
if (!keys.empty() && emitSignal) {
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::removeKeyFrameIndicator(SequenceTime time)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
std::list<SequenceTime>::iterator it = std::find(_keyframes.begin(), _keyframes.end(), time);
if ( it != _keyframes.end() ) {
_keyframes.erase(it);
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::removeMultipleKeyframeIndicator(const std::list<SequenceTime> & keys,
bool emitSignal)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
for (std::list<SequenceTime>::const_iterator it = keys.begin(); it != keys.end(); ++it) {
std::list<SequenceTime>::iterator it2 = std::find(_keyframes.begin(), _keyframes.end(), *it);
if ( it2 != _keyframes.end() ) {
_keyframes.erase(it2);
}
}
if (!keys.empty() && emitSignal) {
emit keyframeIndicatorsChanged();
}
}
void
TimeLine::addNodesKeyframesToTimeline(const std::list<Natron::Node*> & nodes)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
std::list<Natron::Node*>::const_iterator next = nodes.begin();
++next;
for (std::list<Natron::Node*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it,++next) {
(*it)->showKeyframesOnTimeline( next == nodes.end() );
}
}
void
TimeLine::addNodeKeyframesToTimeline(Natron::Node* node)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
node->showKeyframesOnTimeline(true);
}
void
TimeLine::removeNodesKeyframesFromTimeline(const std::list<Natron::Node*> & nodes)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
std::list<Natron::Node*>::const_iterator next = nodes.begin();
++next;
for (std::list<Natron::Node*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it,++next) {
(*it)->hideKeyframesFromTimeline( next == nodes.end() );
}
}
void
TimeLine::removeNodeKeyframesFromTimeline(Natron::Node* node)
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
node->hideKeyframesFromTimeline(true);
}
void
TimeLine::getKeyframes(std::list<SequenceTime>* keys) const
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
*keys = _keyframes;
}
void
TimeLine::goToPreviousKeyframe()
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.sort();
std::list<SequenceTime>::iterator lowerBound = std::lower_bound(_keyframes.begin(), _keyframes.end(), _currentFrame);
if ( lowerBound != _keyframes.begin() ) {
--lowerBound;
seekFrame(*lowerBound, true, NULL, Natron::eTimelineChangeReasonPlaybackSeek);
}
}
void
TimeLine::goToNextKeyframe()
{
///runs only in the main thread
assert( QThread::currentThread() == qApp->thread() );
_keyframes.sort();
std::list<SequenceTime>::iterator upperBound = std::upper_bound(_keyframes.begin(), _keyframes.end(), _currentFrame);
if ( upperBound != _keyframes.end() ) {
seekFrame(*upperBound, true, NULL, Natron::eTimelineChangeReasonPlaybackSeek);
}
}
<|endoftext|> |
<commit_before>#ifndef BOARDS_MEGA_HH
#define BOARDS_MEGA_HH
#include <avr/io.h>
#include <avr/sleep.h>
/* This board is based on ATmega1280/2560 but only ATmega2560 is supported */
/**
* Cosa MEGA Board pin symbol definitions for the ATmega1280 and
* ATmega2560 based Arduino boards; Mega 1280/2560. Cosa does not use
* pin numbers as Arduino/Wiring, instead strong data type is used
* (enum types) for the specific pin classes; DigitalPin, AnalogPin,
* etc.
*
* The pin numbers for ATmega1280 and ATmega2560 are only symbolically
* mapped, i.e. a pin number/digit will not work, symbols must be
* used, e.g., Board::D42. Avoid iterations assuming that the symbols
* are in order.
*
* The static inline functions, SFR, BIT and UART, rely on compiler
* optimizations to be reduced.
*/
namespace Board
{
//====
// IO
//====
enum class Port: uint8_t
{
PORT_A = 0,
PORT_B,
PORT_C,
PORT_D,
PORT_E,
PORT_F,
PORT_G,
PORT_H,
PORT_J,
PORT_K,
PORT_L,
NONE = 0xFF
};
/**
* Digital pin symbols
*/
enum class DigitalPin: uint8_t
{
D0 = 0, // PE0/RX0
D1 = 1, // PE1/TX0
D2 = 4, // PE4
D3 = 5, // PE5
D4 = 85, // PG5
D5 = 3, // PE3
D6 = 11, // PH3
D7 = 12, // PH4
D8 = 13, // PH5
D9 = 14, // PH6
D10 = 20, // PB4
D11 = 21, // PB5
D12 = 22, // PB6
D13 = 23, // PB7
D14 = 73, // PJ1/TX3
D15 = 72, // PJ0/RX3
D16 = 9, // PH1/TX2
D17 = 8, // PH0/RX2
D18 = 43, // PD3/TX1
D19 = 42, // PD2/RX1
D20 = 41, // PD1/SDA
D21 = 40, // PD0/SCL
D22 = 24, // PA0/AD0
D23 = 25, // PA1
D24 = 26, // PA2
D25 = 27, // PA3
D26 = 28, // PA4
D27 = 29, // PA5
D28 = 30, // PA6
D29 = 31, // PA7
D30 = 39, // PC7
D31 = 38, // PC6
D32 = 37, // PC5
D33 = 36, // PC4
D34 = 35, // PC3
D35 = 34, // PC2
D36 = 33, // PC1
D37 = 32, // PC0
D38 = 47, // PD7
D39 = 82, // PG2
D40 = 81, // PG1
D41 = 80, // PG0
D42 = 55, // PL7
D43 = 54, // PL6
D44 = 53, // PL5
D45 = 52, // PL4
D46 = 51, // PL3
D47 = 50, // PL2
D48 = 49, // PL1
D49 = 48, // PL0
D50 = 19, // PB3/MISO
D51 = 18, // PB2/MOSI
D52 = 17, // PB1/SCK
D53 = 16, // PB0/SS
D54 = 56, // PF0/A0
D55 = 57, // PF1/A1
D56 = 58, // PF2/A2
D57 = 59, // PF3/A3
D58 = 60, // PF4/A4
D59 = 61, // PF5/A5
D60 = 62, // PF6/A6
D61 = 63, // PF7/A7
D62 = 64, // PK0/A8
D63 = 65, // PK1/A9
D64 = 66, // PK2/A10
D65 = 67, // PK3/A11
D66 = 68, // PK4/A12
D67 = 69, // PK5/A13
D68 = 70, // PK6/A14
D69 = 71, // PK7/A15
LED = D13,
NONE = 0XFF
};
//==============
// Analog Input
//==============
enum class AnalogClock: uint8_t
{
MAX_FREQ_50KHz = 0,
MAX_FREQ_100KHz,
MAX_FREQ_200KHz,
MAX_FREQ_500KHz,
MAX_FREQ_1MHz
};
enum class AnalogReference: uint8_t
{
AREF = 0,
AVCC,
INTERNAL_1_1V,
INTERNAL_2_56V
};
enum class AnalogPin: uint8_t
{
A0 = 0,
A1,
A2,
A3,
A4,
A5,
A6,
A7,
A8,
A9,
A10,
A11,
A12,
A13,
A14,
A15,
BANDGAP,
NONE = 0xFF
};
//===============
// IO interrupts
//===============
/**
* External interrupt pin symbols; sub-set of digital pins
* to allow compile time checking.
*/
namespace ExternalInterruptPin
{
constexpr const DigitalPin D21 = DigitalPin::D21; // PD0
constexpr const DigitalPin D20 = DigitalPin::D20; // PD1
constexpr const DigitalPin D19 = DigitalPin::D19; // PD2
constexpr const DigitalPin D18 = DigitalPin::D18; // PD3
constexpr const DigitalPin D2 = DigitalPin::D2; // PE4
constexpr const DigitalPin D3 = DigitalPin::D3; // PE5
constexpr const DigitalPin EXT0 = DigitalPin::D21; // PD0
constexpr const DigitalPin EXT1 = DigitalPin::D20; // PD1
constexpr const DigitalPin EXT2 = DigitalPin::D19; // PD2
constexpr const DigitalPin EXT3 = DigitalPin::D18; // PD3
constexpr const DigitalPin EXT4 = DigitalPin::D2; // PE4
constexpr const DigitalPin EXT5 = DigitalPin::D3; // PE5
};
/**
* Pin change interrupt (PCI) pins.
*/
namespace InterruptPin
{
// PB0-7
constexpr const DigitalPin D53 = DigitalPin::D53;
constexpr const DigitalPin D52 = DigitalPin::D52;
constexpr const DigitalPin D51 = DigitalPin::D51;
constexpr const DigitalPin D50 = DigitalPin::D50;
constexpr const DigitalPin D10 = DigitalPin::D10;
constexpr const DigitalPin D11 = DigitalPin::D11;
constexpr const DigitalPin D12 = DigitalPin::D12;
constexpr const DigitalPin D13 = DigitalPin::D13;
// PJ0-1
constexpr const DigitalPin D15 = DigitalPin::D15;
constexpr const DigitalPin D14 = DigitalPin::D14;
// PK0-7
constexpr const DigitalPin D62 = DigitalPin::D62;
constexpr const DigitalPin D63 = DigitalPin::D63;
constexpr const DigitalPin D64 = DigitalPin::D64;
constexpr const DigitalPin D65 = DigitalPin::D65;
constexpr const DigitalPin D66 = DigitalPin::D66;
constexpr const DigitalPin D67 = DigitalPin::D67;
constexpr const DigitalPin D68 = DigitalPin::D68;
constexpr const DigitalPin D69 = DigitalPin::D69;
};
//=======
// USART
//=======
enum class USART: uint8_t
{
USART0 = 0,
USART1 = 1,
USART2 = 2,
USART3 = 3
};
//=====
// SPI
//=====
// Nothing special
//========
// Timers
//========
enum class Timer: uint8_t
{
TIMER0,
TIMER1,
TIMER2,
TIMER3,
TIMER4,
TIMER5
};
//=============
// Sleep Modes
//=============
enum class SleepMode: uint8_t
{
IDLE = SLEEP_MODE_IDLE,
ADC_NOISE_REDUCTION = SLEEP_MODE_ADC,
POWER_DOWN = SLEEP_MODE_PWR_DOWN,
POWER_SAVE = SLEEP_MODE_PWR_SAVE,
STANDBY = SLEEP_MODE_STANDBY,
EXTENDED_STANDBY = SLEEP_MODE_EXT_STANDBY,
DEFAULT_MODE = 0xFF
};
};
/**
* Forward declare interrupt service routines to allow them as friends.
*/
extern "C" {
void ADC_vect(void) __attribute__ ((signal));
void ANALOG_COMP_vect(void) __attribute__ ((signal));
void INT0_vect(void) __attribute__ ((signal));
void INT1_vect(void) __attribute__ ((signal));
void INT2_vect(void) __attribute__ ((signal));
void INT3_vect(void) __attribute__ ((signal));
void INT4_vect(void) __attribute__ ((signal));
void INT5_vect(void) __attribute__ ((signal));
void INT6_vect(void) __attribute__ ((signal));
void INT7_vect(void) __attribute__ ((signal));
void PCINT0_vect(void) __attribute__ ((signal));
void PCINT1_vect(void) __attribute__ ((signal));
void PCINT2_vect(void) __attribute__ ((signal));
void SPI_STC_vect(void) __attribute__ ((signal));
void TIMER0_COMPA_vect(void) __attribute__ ((signal));
void TIMER0_COMPB_vect(void) __attribute__ ((signal));
void TIMER0_OVF_vect(void) __attribute__ ((signal));
void TIMER1_COMPA_vect(void) __attribute__ ((signal));
void TIMER1_COMPB_vect(void) __attribute__ ((signal));
void TIMER1_COMPC_vect(void) __attribute__ ((signal));
void TIMER1_OVF_vect(void) __attribute__ ((signal));
void TIMER1_CAPT_vect(void) __attribute__ ((signal));
void TIMER2_COMPA_vect(void) __attribute__ ((signal));
void TIMER2_COMPB_vect(void) __attribute__ ((signal));
void TIMER2_OVF_vect(void) __attribute__ ((signal));
void TIMER3_COMPA_vect(void) __attribute__ ((signal));
void TIMER3_COMPB_vect(void) __attribute__ ((signal));
void TIMER3_COMPC_vect(void) __attribute__ ((signal));
void TIMER3_OVF_vect(void) __attribute__ ((signal));
void TIMER3_CAPT_vect(void) __attribute__ ((signal));
void TIMER4_COMPA_vect(void) __attribute__ ((signal));
void TIMER4_COMPB_vect(void) __attribute__ ((signal));
void TIMER4_COMPC_vect(void) __attribute__ ((signal));
void TIMER4_OVF_vect(void) __attribute__ ((signal));
void TIMER4_CAPT_vect(void) __attribute__ ((signal));
void TIMER5_COMPA_vect(void) __attribute__ ((signal));
void TIMER5_COMPB_vect(void) __attribute__ ((signal));
void TIMER5_COMPC_vect(void) __attribute__ ((signal));
void TIMER5_OVF_vect(void) __attribute__ ((signal));
void TIMER5_CAPT_vect(void) __attribute__ ((signal));
void TWI_vect(void) __attribute__ ((signal));
void WDT_vect(void) __attribute__ ((signal));
void USART0_UDRE_vect(void) __attribute__ ((signal));
void USART0_RX_vect(void) __attribute__ ((signal));
void USART0_TX_vect(void) __attribute__ ((signal));
void USART1_UDRE_vect(void) __attribute__ ((signal));
void USART1_RX_vect(void) __attribute__ ((signal));
void USART1_TX_vect(void) __attribute__ ((signal));
void USART2_UDRE_vect(void) __attribute__ ((signal));
void USART2_RX_vect(void) __attribute__ ((signal));
void USART2_TX_vect(void) __attribute__ ((signal));
void USART3_UDRE_vect(void) __attribute__ ((signal));
void USART3_RX_vect(void) __attribute__ ((signal));
void USART3_TX_vect(void) __attribute__ ((signal));
}
#endif /* BOARDS_MEGA_HH */
<commit_msg>Remove outdated copyright as file has been completely rewritten, since introduction of traits for boards configuration.<commit_after>#ifndef BOARDS_MEGA_HH
#define BOARDS_MEGA_HH
#include <avr/io.h>
#include <avr/sleep.h>
/* This board is based on ATmega1280/2560 but only ATmega2560 is supported */
namespace Board
{
//====
// IO
//====
enum class Port: uint8_t
{
PORT_A = 0,
PORT_B,
PORT_C,
PORT_D,
PORT_E,
PORT_F,
PORT_G,
PORT_H,
PORT_J,
PORT_K,
PORT_L,
NONE = 0xFF
};
/**
* Digital pin symbols
*/
enum class DigitalPin: uint8_t
{
D0 = 0, // PE0/RX0
D1 = 1, // PE1/TX0
D2 = 4, // PE4
D3 = 5, // PE5
D4 = 85, // PG5
D5 = 3, // PE3
D6 = 11, // PH3
D7 = 12, // PH4
D8 = 13, // PH5
D9 = 14, // PH6
D10 = 20, // PB4
D11 = 21, // PB5
D12 = 22, // PB6
D13 = 23, // PB7
D14 = 73, // PJ1/TX3
D15 = 72, // PJ0/RX3
D16 = 9, // PH1/TX2
D17 = 8, // PH0/RX2
D18 = 43, // PD3/TX1
D19 = 42, // PD2/RX1
D20 = 41, // PD1/SDA
D21 = 40, // PD0/SCL
D22 = 24, // PA0/AD0
D23 = 25, // PA1
D24 = 26, // PA2
D25 = 27, // PA3
D26 = 28, // PA4
D27 = 29, // PA5
D28 = 30, // PA6
D29 = 31, // PA7
D30 = 39, // PC7
D31 = 38, // PC6
D32 = 37, // PC5
D33 = 36, // PC4
D34 = 35, // PC3
D35 = 34, // PC2
D36 = 33, // PC1
D37 = 32, // PC0
D38 = 47, // PD7
D39 = 82, // PG2
D40 = 81, // PG1
D41 = 80, // PG0
D42 = 55, // PL7
D43 = 54, // PL6
D44 = 53, // PL5
D45 = 52, // PL4
D46 = 51, // PL3
D47 = 50, // PL2
D48 = 49, // PL1
D49 = 48, // PL0
D50 = 19, // PB3/MISO
D51 = 18, // PB2/MOSI
D52 = 17, // PB1/SCK
D53 = 16, // PB0/SS
D54 = 56, // PF0/A0
D55 = 57, // PF1/A1
D56 = 58, // PF2/A2
D57 = 59, // PF3/A3
D58 = 60, // PF4/A4
D59 = 61, // PF5/A5
D60 = 62, // PF6/A6
D61 = 63, // PF7/A7
D62 = 64, // PK0/A8
D63 = 65, // PK1/A9
D64 = 66, // PK2/A10
D65 = 67, // PK3/A11
D66 = 68, // PK4/A12
D67 = 69, // PK5/A13
D68 = 70, // PK6/A14
D69 = 71, // PK7/A15
LED = D13,
NONE = 0XFF
};
//==============
// Analog Input
//==============
enum class AnalogClock: uint8_t
{
MAX_FREQ_50KHz = 0,
MAX_FREQ_100KHz,
MAX_FREQ_200KHz,
MAX_FREQ_500KHz,
MAX_FREQ_1MHz
};
enum class AnalogReference: uint8_t
{
AREF = 0,
AVCC,
INTERNAL_1_1V,
INTERNAL_2_56V
};
enum class AnalogPin: uint8_t
{
A0 = 0,
A1,
A2,
A3,
A4,
A5,
A6,
A7,
A8,
A9,
A10,
A11,
A12,
A13,
A14,
A15,
BANDGAP,
NONE = 0xFF
};
//===============
// IO interrupts
//===============
/**
* External interrupt pin symbols; sub-set of digital pins
* to allow compile time checking.
*/
namespace ExternalInterruptPin
{
constexpr const DigitalPin D21 = DigitalPin::D21; // PD0
constexpr const DigitalPin D20 = DigitalPin::D20; // PD1
constexpr const DigitalPin D19 = DigitalPin::D19; // PD2
constexpr const DigitalPin D18 = DigitalPin::D18; // PD3
constexpr const DigitalPin D2 = DigitalPin::D2; // PE4
constexpr const DigitalPin D3 = DigitalPin::D3; // PE5
constexpr const DigitalPin EXT0 = DigitalPin::D21; // PD0
constexpr const DigitalPin EXT1 = DigitalPin::D20; // PD1
constexpr const DigitalPin EXT2 = DigitalPin::D19; // PD2
constexpr const DigitalPin EXT3 = DigitalPin::D18; // PD3
constexpr const DigitalPin EXT4 = DigitalPin::D2; // PE4
constexpr const DigitalPin EXT5 = DigitalPin::D3; // PE5
};
/**
* Pin change interrupt (PCI) pins.
*/
namespace InterruptPin
{
// PB0-7
constexpr const DigitalPin D53 = DigitalPin::D53;
constexpr const DigitalPin D52 = DigitalPin::D52;
constexpr const DigitalPin D51 = DigitalPin::D51;
constexpr const DigitalPin D50 = DigitalPin::D50;
constexpr const DigitalPin D10 = DigitalPin::D10;
constexpr const DigitalPin D11 = DigitalPin::D11;
constexpr const DigitalPin D12 = DigitalPin::D12;
constexpr const DigitalPin D13 = DigitalPin::D13;
// PJ0-1
constexpr const DigitalPin D15 = DigitalPin::D15;
constexpr const DigitalPin D14 = DigitalPin::D14;
// PK0-7
constexpr const DigitalPin D62 = DigitalPin::D62;
constexpr const DigitalPin D63 = DigitalPin::D63;
constexpr const DigitalPin D64 = DigitalPin::D64;
constexpr const DigitalPin D65 = DigitalPin::D65;
constexpr const DigitalPin D66 = DigitalPin::D66;
constexpr const DigitalPin D67 = DigitalPin::D67;
constexpr const DigitalPin D68 = DigitalPin::D68;
constexpr const DigitalPin D69 = DigitalPin::D69;
};
//=======
// USART
//=======
enum class USART: uint8_t
{
USART0 = 0,
USART1 = 1,
USART2 = 2,
USART3 = 3
};
//=====
// SPI
//=====
// Nothing special
//========
// Timers
//========
enum class Timer: uint8_t
{
TIMER0,
TIMER1,
TIMER2,
TIMER3,
TIMER4,
TIMER5
};
//=============
// Sleep Modes
//=============
enum class SleepMode: uint8_t
{
IDLE = SLEEP_MODE_IDLE,
ADC_NOISE_REDUCTION = SLEEP_MODE_ADC,
POWER_DOWN = SLEEP_MODE_PWR_DOWN,
POWER_SAVE = SLEEP_MODE_PWR_SAVE,
STANDBY = SLEEP_MODE_STANDBY,
EXTENDED_STANDBY = SLEEP_MODE_EXT_STANDBY,
DEFAULT_MODE = 0xFF
};
};
/**
* Forward declare interrupt service routines to allow them as friends.
*/
extern "C" {
void ADC_vect(void) __attribute__ ((signal));
void ANALOG_COMP_vect(void) __attribute__ ((signal));
void INT0_vect(void) __attribute__ ((signal));
void INT1_vect(void) __attribute__ ((signal));
void INT2_vect(void) __attribute__ ((signal));
void INT3_vect(void) __attribute__ ((signal));
void INT4_vect(void) __attribute__ ((signal));
void INT5_vect(void) __attribute__ ((signal));
void INT6_vect(void) __attribute__ ((signal));
void INT7_vect(void) __attribute__ ((signal));
void PCINT0_vect(void) __attribute__ ((signal));
void PCINT1_vect(void) __attribute__ ((signal));
void PCINT2_vect(void) __attribute__ ((signal));
void SPI_STC_vect(void) __attribute__ ((signal));
void TIMER0_COMPA_vect(void) __attribute__ ((signal));
void TIMER0_COMPB_vect(void) __attribute__ ((signal));
void TIMER0_OVF_vect(void) __attribute__ ((signal));
void TIMER1_COMPA_vect(void) __attribute__ ((signal));
void TIMER1_COMPB_vect(void) __attribute__ ((signal));
void TIMER1_COMPC_vect(void) __attribute__ ((signal));
void TIMER1_OVF_vect(void) __attribute__ ((signal));
void TIMER1_CAPT_vect(void) __attribute__ ((signal));
void TIMER2_COMPA_vect(void) __attribute__ ((signal));
void TIMER2_COMPB_vect(void) __attribute__ ((signal));
void TIMER2_OVF_vect(void) __attribute__ ((signal));
void TIMER3_COMPA_vect(void) __attribute__ ((signal));
void TIMER3_COMPB_vect(void) __attribute__ ((signal));
void TIMER3_COMPC_vect(void) __attribute__ ((signal));
void TIMER3_OVF_vect(void) __attribute__ ((signal));
void TIMER3_CAPT_vect(void) __attribute__ ((signal));
void TIMER4_COMPA_vect(void) __attribute__ ((signal));
void TIMER4_COMPB_vect(void) __attribute__ ((signal));
void TIMER4_COMPC_vect(void) __attribute__ ((signal));
void TIMER4_OVF_vect(void) __attribute__ ((signal));
void TIMER4_CAPT_vect(void) __attribute__ ((signal));
void TIMER5_COMPA_vect(void) __attribute__ ((signal));
void TIMER5_COMPB_vect(void) __attribute__ ((signal));
void TIMER5_COMPC_vect(void) __attribute__ ((signal));
void TIMER5_OVF_vect(void) __attribute__ ((signal));
void TIMER5_CAPT_vect(void) __attribute__ ((signal));
void TWI_vect(void) __attribute__ ((signal));
void WDT_vect(void) __attribute__ ((signal));
void USART0_UDRE_vect(void) __attribute__ ((signal));
void USART0_RX_vect(void) __attribute__ ((signal));
void USART0_TX_vect(void) __attribute__ ((signal));
void USART1_UDRE_vect(void) __attribute__ ((signal));
void USART1_RX_vect(void) __attribute__ ((signal));
void USART1_TX_vect(void) __attribute__ ((signal));
void USART2_UDRE_vect(void) __attribute__ ((signal));
void USART2_RX_vect(void) __attribute__ ((signal));
void USART2_TX_vect(void) __attribute__ ((signal));
void USART3_UDRE_vect(void) __attribute__ ((signal));
void USART3_RX_vect(void) __attribute__ ((signal));
void USART3_TX_vect(void) __attribute__ ((signal));
}
#endif /* BOARDS_MEGA_HH */
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <stan/optimization/bfgs.hpp>
#include <test/test-models/no-main/optimization/rosenbrock.cpp>
TEST(OptimizationBfgs, rosenbrock_bfgs_convergence) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::BFGSUpdate_HInv<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret = 0;
while (ret == 0) {
ret = bfgs.step();
}
bfgs.params_r(cont_vector);
// Check that the return code is normal
EXPECT_GE(ret,0);
// Check the correct minimum was found
EXPECT_NEAR(cont_vector[0],1.0,1e-6);
EXPECT_NEAR(cont_vector[1],1.0,1e-6);
// Check that it didn't take too long to get there
EXPECT_LE(bfgs.iter_num(), 35);
EXPECT_LE(bfgs.grad_evals(), 70);
}
TEST(OptimizationBfgs, rosenbrock_bfgs_termconds) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::BFGSUpdate_HInv<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret;
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 0;
bfgs._conv_opts.maxIts = 5;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_MAXIT);
EXPECT_EQ(bfgs.iter_num(),bfgs._conv_opts.maxIts);
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSX);
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 1e-12;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSF);
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 1e+4;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELF);
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSGRAD);
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 1e+3;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELGRAD);
bfgs._conv_opts.tolRelGrad = 0;
}
TEST(OptimizationBfgs, rosenbrock_lbfgs_convergence) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::LBFGSUpdate<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret = 0;
while (ret == 0) {
ret = bfgs.step();
}
bfgs.params_r(cont_vector);
// std::cerr << "Convergence condition: " << bfgs.get_code_string(ret) << std::endl;
// std::cerr << "Converged after " << bfgs.iter_num() << " iterations and " << bfgs.grad_evals() << " gradient evaluations." << std::endl;
// Check that the return code is normal
EXPECT_GE(ret,0);
// Check the correct minimum was found
EXPECT_NEAR(cont_vector[0],1.0,1e-6);
EXPECT_NEAR(cont_vector[1],1.0,1e-6);
// Check that it didn't take too long to get there
EXPECT_LE(bfgs.iter_num(), 35);
EXPECT_LE(bfgs.grad_evals(), 70);
}
TEST(OptimizationBfgs, rosenbrock_lbfgs_termconds) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::LBFGSUpdate<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret;
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 0;
bfgs._conv_opts.maxIts = 5;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_MAXIT);
EXPECT_EQ(bfgs.iter_num(),bfgs._conv_opts.maxIts);
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSX);
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 1e-12;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSF);
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 1e+4;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELF);
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSGRAD);
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 1e+3;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELGRAD);
bfgs._conv_opts.tolRelGrad = 0;
}
<commit_msg>adding placeholder tests for each untested method in bfgs.hpp<commit_after>#include <gtest/gtest.h>
#include <stan/optimization/bfgs.hpp>
#include <test/test-models/no-main/optimization/rosenbrock.cpp>
TEST(OptimizationBfgs, rosenbrock_bfgs_convergence) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::BFGSUpdate_HInv<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret = 0;
while (ret == 0) {
ret = bfgs.step();
}
bfgs.params_r(cont_vector);
// Check that the return code is normal
EXPECT_GE(ret,0);
// Check the correct minimum was found
EXPECT_NEAR(cont_vector[0],1.0,1e-6);
EXPECT_NEAR(cont_vector[1],1.0,1e-6);
// Check that it didn't take too long to get there
EXPECT_LE(bfgs.iter_num(), 35);
EXPECT_LE(bfgs.grad_evals(), 70);
}
TEST(OptimizationBfgs, rosenbrock_bfgs_termconds) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::BFGSUpdate_HInv<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret;
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 0;
bfgs._conv_opts.maxIts = 5;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_MAXIT);
EXPECT_EQ(bfgs.iter_num(),bfgs._conv_opts.maxIts);
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSX);
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 1e-12;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSF);
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 1e+4;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELF);
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSGRAD);
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 1e+3;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELGRAD);
bfgs._conv_opts.tolRelGrad = 0;
}
TEST(OptimizationBfgs, rosenbrock_lbfgs_convergence) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::LBFGSUpdate<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret = 0;
while (ret == 0) {
ret = bfgs.step();
}
bfgs.params_r(cont_vector);
// std::cerr << "Convergence condition: " << bfgs.get_code_string(ret) << std::endl;
// std::cerr << "Converged after " << bfgs.iter_num() << " iterations and " << bfgs.grad_evals() << " gradient evaluations." << std::endl;
// Check that the return code is normal
EXPECT_GE(ret,0);
// Check the correct minimum was found
EXPECT_NEAR(cont_vector[0],1.0,1e-6);
EXPECT_NEAR(cont_vector[1],1.0,1e-6);
// Check that it didn't take too long to get there
EXPECT_LE(bfgs.iter_num(), 35);
EXPECT_LE(bfgs.grad_evals(), 70);
}
TEST(OptimizationBfgs, rosenbrock_lbfgs_termconds) {
// -1,1 is the standard initialization for the Rosenbrock function
std::vector<double> cont_vector(2);
cont_vector[0] = -1; cont_vector[1] = 1;
std::vector<int> disc_vector;
typedef rosenbrock_model_namespace::rosenbrock_model Model;
typedef stan::optimization::BFGSLineSearch<Model,stan::optimization::LBFGSUpdate<> > Optimizer;
static const std::string DATA = "";
std::stringstream data_stream(DATA);
stan::io::dump dummy_context(data_stream);
Model rb_model(dummy_context);
Optimizer bfgs(rb_model, cont_vector, disc_vector, &std::cout);
int ret;
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 0;
bfgs._conv_opts.maxIts = 5;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_MAXIT);
EXPECT_EQ(bfgs.iter_num(),bfgs._conv_opts.maxIts);
bfgs._conv_opts.maxIts = 1e9;
bfgs._conv_opts.tolAbsX = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSX);
bfgs._conv_opts.tolAbsX = 0;
bfgs._conv_opts.tolAbsF = 1e-12;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSF);
bfgs._conv_opts.tolAbsF = 0;
bfgs._conv_opts.tolRelF = 1e+4;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELF);
bfgs._conv_opts.tolRelF = 0;
bfgs._conv_opts.tolAbsGrad = 1e-8;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_ABSGRAD);
bfgs._conv_opts.tolAbsGrad = 0;
bfgs._conv_opts.tolRelGrad = 1e+3;
bfgs.initialize(cont_vector);
while(0 == (ret = bfgs.step()));
EXPECT_EQ(ret,stan::optimization::TERM_RELGRAD);
bfgs._conv_opts.tolRelGrad = 0;
}
TEST(OptimizationBfgs, ConvergenceOptions) {
FAIL()
<< "add tests as a means of fixing behavior";
}
TEST(OptimizationBfgs, LsOptions) {
FAIL()
<< "add tests as a means of fixing behavior";
}
TEST(OptimizationBfgs, BfgsMinimizer) {
FAIL()
<< "add tests for class BFGSMinimizer (construction)";
}
TEST(OptimizationBfgs, BfgsMinimizer__ls_opts) {
FAIL()
<< "add tests for class BFGSMinimizer._ls_opts";
}
TEST(OptimizationBfgs, BfgsMinimizer__conv_opts) {
FAIL()
<< "add tests for class BFGSMinimizer._conv_opts";
}
TEST(OptimizationBfgs, BfgsMinimizer_get_qnupdate) {
FAIL()
<< "add tests for class BFGSMinimizer.get_qnupdate()";
}
TEST(OptimizationBfgs, BfgsMinimizer_curr_f) {
FAIL()
<< "add tests for class BFGSMinimizer.curr_f()";
}
TEST(OptimizationBfgs, BfgsMinimizer_curr_x) {
FAIL()
<< "add tests for class BFGSMinimizer.curr_x()";
}
TEST(OptimizationBfgs, BfgsMinimizer_curr_g) {
FAIL()
<< "add tests for class BFGSMinimizer.curr_g()";
}
TEST(OptimizationBfgs, BfgsMinimizer_curr_p) {
FAIL()
<< "add tests for class BFGSMinimizer.curr_p()";
}
TEST(OptimizationBfgs, BfgsMinimizer_prev_f) {
FAIL()
<< "add tests for class BFGSMinimizer.prev_f()";
}
TEST(OptimizationBfgs, BfgsMinimizer_prev_x) {
FAIL()
<< "add tests for class BFGSMinimizer.prev_x()";
}
TEST(OptimizationBfgs, BfgsMinimizer_prev_g) {
FAIL()
<< "add tests for class BFGSMinimizer.prev_g()";
}
TEST(OptimizationBfgs, BfgsMinimizer_prev_p) {
FAIL()
<< "add tests for class BFGSMinimizer.prev_p()";
}
TEST(OptimizationBfgs, BfgsMinimizer_prev_step_size) {
FAIL()
<< "add tests for class BFGSMinimizer.prev_step_size()";
}
TEST(OptimizationBfgs, BfgsMinimizer_rel_grad_norm) {
FAIL()
<< "add tests for class BFGSMinimizer.rel_grad_norm()";
}
TEST(OptimizationBfgs, BfgsMinimizer_rel_obj_decrease) {
FAIL()
<< "add tests for class BFGSMinimizer.rel_grad_norm()";
}
TEST(OptimizationBfgs, BfgsMinimizer_alpha0) {
FAIL()
<< "add tests for class BFGSMinimizer.alpha0()";
}
TEST(OptimizationBfgs, BfgsMinimizer_alpha) {
FAIL()
<< "add tests for class BFGSMinimizer.alpha()";
}
TEST(OptimizationBfgs, BfgsMinimizer_iter_num) {
FAIL()
<< "add tests for class BFGSMinimizer.iter_num()";
}
TEST(OptimizationBfgs, BfgsMinimizer_note) {
FAIL()
<< "add tests for class BFGSMinimizer.note()";
}
TEST(OptimizationBfgs, BfgsMinimizer_get_code_string) {
FAIL()
<< "add tests for class BFGSMinimizer.get_code_string()";
}
TEST(OptimizationBfgs, BfgsMinimizer_initialize) {
FAIL()
<< "add tests for class BFGSMinimizer.initialize()";
}
TEST(OptimizationBfgs, BfgsMinimizer_step) {
FAIL()
<< "add tests for class BFGSMinimizer.step()";
}
TEST(OptimizationBfgs, BfgsMinimizer_minimize) {
FAIL()
<< "add tests for class BFGSMinimizer.minimize()";
}
TEST(OptimizationBfgs, lp_no_jacobian) {
FAIL()
<< "add tests for lp_no_jacobian() <- is this not used and should it be removed?";
}
TEST(OptimizationBfgs, ModelAdaptor) {
FAIL()
<< "add tests for ModelAdaptor (construction)";
}
TEST(OptimizationBfgs, ModelAdaptor_fevals) {
FAIL()
<< "add tests for ModelAdaptor.fevals()";
}
TEST(OptimizationBfgs, ModelAdaptor_operator_parens__matrix_double) {
FAIL()
<< "add tests for ModelAdaptor.operator(Eigen::Matrix, double)";
}
TEST(OptimizationBfgs, ModelAdaptor_operator_parens__matrix_double_matrix) {
FAIL()
<< "add tests for ModelAdaptor.operator(Eigen::Matrix, double, Eigen::Matrix)";
}
TEST(OptimizationBfgs, ModelAdaptor_df) {
FAIL()
<< "add tests for ModelAdaptor.fevals()";
}
TEST(OptimizationBfgs, BFGSLineSearch) {
FAIL()
<< "add tests for BFGSLineSearch (construction) -- see tests above";
}
TEST(OptimizationBfgs, BFGSLineSearch_initialize) {
FAIL()
<< "add tests for BFGSLineSearch.initialize()";
}
TEST(OptimizationBfgs, BFGSLineSearch_grad_evals) {
FAIL()
<< "add tests for BFGSLineSearch.grad_evals()";
}
TEST(OptimizationBfgs, BFGSLineSearch_logp) {
FAIL()
<< "add tests for BFGSLineSearch.logp()";
}
TEST(OptimizationBfgs, BFGSLineSearch_grad_norm) {
FAIL()
<< "add tests for BFGSLineSearch.grad_norm()";
}
TEST(OptimizationBfgs, BFGSLineSearch_grad) {
FAIL()
<< "add tests for BFGSLineSearch.grad()";
}
TEST(OptimizationBfgs, BFGSLineSearch_params_r) {
FAIL()
<< "add tests for BFGSLineSearch.params_r()";
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <tiramisu/debug.h>
#include <Halide.h>
using namespace Halide;
using namespace Halide::Internal;
using std::string;
using std::map;
using std::vector;
namespace tiramisu
{
namespace
{
string stmt_to_string(const string &str, const Stmt &s)
{
std::ostringstream stream;
stream << str << s << "\n";
return stream.str();
}
} // anonymous namespace
Module lower_halide_pipeline(const string &pipeline_name,
const Target &t,
const vector<Argument> &args,
const Internal::LoweredFunc::LinkageType linkage_type,
Stmt s)
{
Module result_module(pipeline_name, t);
// TODO(tiramisu): Compute the env (function DAG). This is needed for
// the sliding window and storage folding passes.
map<string, Function> env;
std::cout << "Lower halide pipeline...\n" << s << "\n";
DEBUG(3, tiramisu::str_dump("Performing sliding window optimization...\n"));
s = sliding_window(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after sliding window:\n", s)));
DEBUG(3, tiramisu::str_dump("Removing code that depends on undef values...\n"));
s = remove_undef(s);
DEBUG(4, tiramisu::str_dump(
stmt_to_string("Lowering after removing code that depends on undef values:\n", s)));
// This uniquifies the variable names, so we're good to simplify
// after this point. This lets later passes assume syntactic
// equivalence means semantic equivalence.
DEBUG(3, tiramisu::str_dump("Uniquifying variable names...\n"));
s = uniquify_variable_names(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after uniquifying variable names:\n", s)));
DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides
s = simplify(s, false);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s)));
DEBUG(3, tiramisu::str_dump("Performing storage folding optimization...\n"));
s = storage_folding(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after storage folding:\n", s)));
DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides
s = simplify(s, false);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s)));
/* DEBUG(3, tiramisu::str_dump("Injecting prefetches...\n"));
s = inject_prefetch(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting prefetches:\n", s)));
*/
DEBUG(3, tiramisu::str_dump("Destructuring tuple-valued realizations...\n"));
s = split_tuples(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after destructuring tuple-valued realizations:\n", s)));
DEBUG(3, tiramisu::str_dump("\n\n"));
// TODO(tiramisu): This pass is important to figure out all the buffer symbols.
// Maybe we should put it somewhere else instead of here.
DEBUG(3, tiramisu::str_dump("Unpacking buffer arguments...\n"));
s = unpack_buffers(s);
DEBUG(0, tiramisu::str_dump(stmt_to_string("Lowering after unpacking buffer arguments:\n", s)));
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute) ||
t.has_feature(Target::OpenGL) ||
(t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) {
DEBUG(3, tiramisu::str_dump("Selecting a GPU API for GPU loops...\n"));
s = select_gpu_api(s, t);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after selecting a GPU API:\n", s)));
DEBUG(3, tiramisu::str_dump("Injecting host <-> dev buffer copies...\n"));
s = inject_host_dev_buffer_copies(s, t);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting host <-> dev buffer copies:\n",
s)));
}
if (t.has_feature(Target::OpenGL))
{
DEBUG(3, tiramisu::str_dump("Injecting OpenGL texture intrinsics...\n"));
s = inject_opengl_intrinsics(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after OpenGL intrinsics:\n", s)));
}
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute))
{
DEBUG(3, tiramisu::str_dump("Injecting per-block gpu synchronization...\n"));
s = fuse_gpu_thread_loops(s);
DEBUG(4, tiramisu::str_dump(
stmt_to_string("Lowering after injecting per-block gpu synchronization:\n", s)));
}
DEBUG(3, tiramisu::str_dump("Simplifying...\n"));
s = simplify(s);
s = unify_duplicate_lets(s);
s = remove_trivial_for_loops(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after second simplifcation:\n", s)));
DEBUG(3, tiramisu::str_dump("Reduce prefetch dimension...\n"));
s = reduce_prefetch_dimension(s, t);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after reduce prefetch dimension:\n", s)));
DEBUG(3, tiramisu::str_dump("Unrolling...\n"));
s = unroll_loops(s);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after unrolling:\n", s)));
DEBUG(3, tiramisu::str_dump("Vectorizing...\n"));
s = vectorize_loops(s, t);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after vectorizing:\n", s)));
DEBUG(3, tiramisu::str_dump("Detecting vector interleavings...\n"));
s = rewrite_interleavings(s);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after rewriting vector interleavings:\n", s)));
DEBUG(3, tiramisu::str_dump("Partitioning loops to simplify boundary conditions...\n"));
s = partition_loops(s);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after partitioning loops:\n", s)));
DEBUG(3, tiramisu::str_dump("Trimming loops to the region over which they do something...\n"));
s = trim_no_ops(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after loop trimming:\n", s)));
DEBUG(3, tiramisu::str_dump("Injecting early frees...\n"));
s = inject_early_frees(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting early frees:\n", s)));
if (t.has_feature(Target::FuzzFloatStores))
{
DEBUG(3, tiramisu::str_dump("Fuzzing floating point stores...\n"));
s = fuzz_float_stores(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after fuzzing floating point stores:\n", s)));
}
DEBUG(3, tiramisu::str_dump("Simplifying...\n"));
s = common_subexpression_elimination(s);
if (t.has_feature(Target::OpenGL))
{
DEBUG(3, tiramisu::str_dump("Detecting varying attributes...\n"));
s = find_linear_expressions(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after detecting varying attributes:\n", s)));
DEBUG(3, tiramisu::str_dump("Moving varying attribute expressions out of the shader...\n"));
s = setup_gpu_vertex_buffer(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after removing varying attributes:\n", s)));
}
s = remove_dead_allocations(s);
s = remove_trivial_for_loops(s);
s = simplify(s);
s = loop_invariant_code_motion(s);
std::cout << "Lowering after final simplification:\n" << s << "\n";
DEBUG(3, tiramisu::str_dump("Splitting off Hexagon offload...\n"));
s = inject_hexagon_rpc(s, t, result_module);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after splitting off Hexagon offload:\n", s)));
vector<Argument> public_args = args;
// We're about to drop the environment and outputs vector, which
// contain the only strong refs to Functions that may still be
// pointed to by the IR. So make those refs strong.
class StrengthenRefs : public IRMutator {
using IRMutator::visit;
void visit(const Call *c) {
IRMutator::visit(c);
c = expr.as<Call>();
//internal_assert(c);
if (c->func.defined()) {
FunctionPtr ptr = c->func;
ptr.strengthen();
expr = Call::make(c->type, c->name, c->args, c->call_type,
ptr, c->value_index,
c->image, c->param);
}
}
};
s = StrengthenRefs().mutate(s);
LoweredFunc main_func(pipeline_name, public_args, s, linkage_type);
result_module.append(main_func);
// Append a wrapper for this pipeline that accepts old buffer_ts
// and upgrades them. It will use the same name, so it will
// require C++ linkage. We don't need it when jitting.
if (!t.has_feature(Target::JIT)) {
add_legacy_wrapper(result_module, main_func);
}
// Also append any wrappers for extern stages that expect the old buffer_t
wrap_legacy_extern_stages(result_module);
return result_module;
}
}
<commit_msg>Remove CSE<commit_after>#include <algorithm>
#include <iostream>
#include <tiramisu/debug.h>
#include <Halide.h>
using namespace Halide;
using namespace Halide::Internal;
using std::string;
using std::map;
using std::vector;
namespace tiramisu
{
namespace
{
string stmt_to_string(const string &str, const Stmt &s)
{
std::ostringstream stream;
stream << str << s << "\n";
return stream.str();
}
} // anonymous namespace
Module lower_halide_pipeline(const string &pipeline_name,
const Target &t,
const vector<Argument> &args,
const Internal::LoweredFunc::LinkageType linkage_type,
Stmt s)
{
Module result_module(pipeline_name, t);
// TODO(tiramisu): Compute the env (function DAG). This is needed for
// the sliding window and storage folding passes.
map<string, Function> env;
std::cout << "Lower halide pipeline...\n" << s << "\n";
DEBUG(3, tiramisu::str_dump("Performing sliding window optimization...\n"));
s = sliding_window(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after sliding window:\n", s)));
DEBUG(3, tiramisu::str_dump("Removing code that depends on undef values...\n"));
s = remove_undef(s);
DEBUG(4, tiramisu::str_dump(
stmt_to_string("Lowering after removing code that depends on undef values:\n", s)));
// This uniquifies the variable names, so we're good to simplify
// after this point. This lets later passes assume syntactic
// equivalence means semantic equivalence.
DEBUG(3, tiramisu::str_dump("Uniquifying variable names...\n"));
s = uniquify_variable_names(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after uniquifying variable names:\n", s)));
DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides
s = simplify(s, false);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s)));
DEBUG(3, tiramisu::str_dump("Performing storage folding optimization...\n"));
s = storage_folding(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after storage folding:\n", s)));
DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides
s = simplify(s, false);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s)));
/* DEBUG(3, tiramisu::str_dump("Injecting prefetches...\n"));
s = inject_prefetch(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting prefetches:\n", s)));
*/
DEBUG(3, tiramisu::str_dump("Destructuring tuple-valued realizations...\n"));
s = split_tuples(s, env);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after destructuring tuple-valued realizations:\n", s)));
DEBUG(3, tiramisu::str_dump("\n\n"));
// TODO(tiramisu): This pass is important to figure out all the buffer symbols.
// Maybe we should put it somewhere else instead of here.
DEBUG(3, tiramisu::str_dump("Unpacking buffer arguments...\n"));
s = unpack_buffers(s);
DEBUG(0, tiramisu::str_dump(stmt_to_string("Lowering after unpacking buffer arguments:\n", s)));
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute) ||
t.has_feature(Target::OpenGL) ||
(t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) {
DEBUG(3, tiramisu::str_dump("Selecting a GPU API for GPU loops...\n"));
s = select_gpu_api(s, t);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after selecting a GPU API:\n", s)));
DEBUG(3, tiramisu::str_dump("Injecting host <-> dev buffer copies...\n"));
s = inject_host_dev_buffer_copies(s, t);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting host <-> dev buffer copies:\n",
s)));
}
if (t.has_feature(Target::OpenGL))
{
DEBUG(3, tiramisu::str_dump("Injecting OpenGL texture intrinsics...\n"));
s = inject_opengl_intrinsics(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after OpenGL intrinsics:\n", s)));
}
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute))
{
DEBUG(3, tiramisu::str_dump("Injecting per-block gpu synchronization...\n"));
s = fuse_gpu_thread_loops(s);
DEBUG(4, tiramisu::str_dump(
stmt_to_string("Lowering after injecting per-block gpu synchronization:\n", s)));
}
DEBUG(3, tiramisu::str_dump("Simplifying...\n"));
s = simplify(s);
s = unify_duplicate_lets(s);
s = remove_trivial_for_loops(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after second simplifcation:\n", s)));
DEBUG(3, tiramisu::str_dump("Reduce prefetch dimension...\n"));
s = reduce_prefetch_dimension(s, t);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after reduce prefetch dimension:\n", s)));
DEBUG(3, tiramisu::str_dump("Unrolling...\n"));
s = unroll_loops(s);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after unrolling:\n", s)));
DEBUG(3, tiramisu::str_dump("Vectorizing...\n"));
s = vectorize_loops(s, t);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after vectorizing:\n", s)));
DEBUG(3, tiramisu::str_dump("Detecting vector interleavings...\n"));
s = rewrite_interleavings(s);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after rewriting vector interleavings:\n", s)));
DEBUG(3, tiramisu::str_dump("Partitioning loops to simplify boundary conditions...\n"));
s = partition_loops(s);
s = simplify(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after partitioning loops:\n", s)));
DEBUG(3, tiramisu::str_dump("Trimming loops to the region over which they do something...\n"));
s = trim_no_ops(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after loop trimming:\n", s)));
DEBUG(3, tiramisu::str_dump("Injecting early frees...\n"));
s = inject_early_frees(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting early frees:\n", s)));
if (t.has_feature(Target::FuzzFloatStores))
{
DEBUG(3, tiramisu::str_dump("Fuzzing floating point stores...\n"));
s = fuzz_float_stores(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after fuzzing floating point stores:\n", s)));
}
DEBUG(3, tiramisu::str_dump("Simplifying...\n"));
s = common_subexpression_elimination(s);
if (t.has_feature(Target::OpenGL))
{
DEBUG(3, tiramisu::str_dump("Detecting varying attributes...\n"));
s = find_linear_expressions(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after detecting varying attributes:\n", s)));
DEBUG(3, tiramisu::str_dump("Moving varying attribute expressions out of the shader...\n"));
s = setup_gpu_vertex_buffer(s);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after removing varying attributes:\n", s)));
}
s = remove_dead_allocations(s);
s = remove_trivial_for_loops(s);
s = simplify(s);
// s = loop_invariant_code_motion(s);
std::cout << "Lowering after final simplification:\n" << s << "\n";
DEBUG(3, tiramisu::str_dump("Splitting off Hexagon offload...\n"));
s = inject_hexagon_rpc(s, t, result_module);
DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after splitting off Hexagon offload:\n", s)));
vector<Argument> public_args = args;
// We're about to drop the environment and outputs vector, which
// contain the only strong refs to Functions that may still be
// pointed to by the IR. So make those refs strong.
class StrengthenRefs : public IRMutator {
using IRMutator::visit;
void visit(const Call *c) {
IRMutator::visit(c);
c = expr.as<Call>();
//internal_assert(c);
if (c->func.defined()) {
FunctionPtr ptr = c->func;
ptr.strengthen();
expr = Call::make(c->type, c->name, c->args, c->call_type,
ptr, c->value_index,
c->image, c->param);
}
}
};
s = StrengthenRefs().mutate(s);
LoweredFunc main_func(pipeline_name, public_args, s, linkage_type);
result_module.append(main_func);
// Append a wrapper for this pipeline that accepts old buffer_ts
// and upgrades them. It will use the same name, so it will
// require C++ linkage. We don't need it when jitting.
if (!t.has_feature(Target::JIT)) {
add_legacy_wrapper(result_module, main_func);
}
// Also append any wrappers for extern stages that expect the old buffer_t
wrap_legacy_extern_stages(result_module);
return result_module;
}
}
<|endoftext|> |
<commit_before>/*
* Ubitrack - Library for Ubiquitous Tracking
* Copyright 2006, Technische Universitaet Muenchen, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of individual
* contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/**
* @ingroup dataflow_components
* @file
* ApplicationPushSink implementation
*
* @author Manuel Huber <huberma@in.tum.de>
*/
#include <utDataflow/ComponentFactory.h>
#include "ApplicationPushSink.h"
namespace Ubitrack { namespace Components {
UBITRACK_REGISTER_COMPONENT( ComponentFactory* const cf ) {
cf->registerComponent< ApplicationPushSink< int > > ( "ApplicationPushSinkInt" );
cf->registerComponent< ApplicationPushSinkPose > ( "ApplicationPushSinkPose" );
cf->registerComponent< ApplicationPushSinkErrorPose > ( "ApplicationPushSinkErrorPose" );
cf->registerComponent< ApplicationPushSinkPosition > ( "ApplicationPushSinkPosition" );
cf->registerComponent< ApplicationPushSinkPosition2D > ( "ApplicationPushSinkPosition2D" );
cf->registerComponent< ApplicationPushSinkRotation > ( "ApplicationPushSinkRotation" );
cf->registerComponent< ApplicationPushSinkPositionList > ( "ApplicationPushSinkPositionList" );
cf->registerComponent< ApplicationPushSinkPositionList2 > ( "ApplicationPushSinkPosition2DList" );
cf->registerComponent< ApplicationPushSinkErrorPositionList > ( "ApplicationPushSinkErrorPositionList" );
cf->registerComponent< ApplicationPushSinkErrorPositionList2 > ( "ApplicationPushSinkErrorPosition2DList" );
cf->registerComponent< ApplicationPushSink< Measurement::Matrix3x4 > > ( "ApplicationPushSinkMatrix3x4" );
cf->registerComponent< ApplicationPushSink< Measurement::Matrix3x3 > > ( "ApplicationPushSinkMatrix3x3" );
cf->registerComponent< ApplicationPushSink< Measurement::Matrix4x4 > > ( "ApplicationPushSinkMatrix4x4" );
cf->registerComponent< ApplicationPushSink< Measurement::Distance > > ( "ApplicationPushSinkDistance" );
}
} } // namespace Ubitrack::Components
<commit_msg>add missing change for push sink button<commit_after>/*
* Ubitrack - Library for Ubiquitous Tracking
* Copyright 2006, Technische Universitaet Muenchen, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of individual
* contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/**
* @ingroup dataflow_components
* @file
* ApplicationPushSink implementation
*
* @author Manuel Huber <huberma@in.tum.de>
*/
#include <utDataflow/ComponentFactory.h>
#include "ApplicationPushSink.h"
namespace Ubitrack { namespace Components {
UBITRACK_REGISTER_COMPONENT( ComponentFactory* const cf ) {
cf->registerComponent< ApplicationPushSink< int > > ( "ApplicationPushSinkInt" );
cf->registerComponent< ApplicationPushSinkButton > ( "ApplicationPushSinkButton" );
cf->registerComponent< ApplicationPushSinkPose > ( "ApplicationPushSinkPose" );
cf->registerComponent< ApplicationPushSinkErrorPose > ( "ApplicationPushSinkErrorPose" );
cf->registerComponent< ApplicationPushSinkPosition > ( "ApplicationPushSinkPosition" );
cf->registerComponent< ApplicationPushSinkPosition2D > ( "ApplicationPushSinkPosition2D" );
cf->registerComponent< ApplicationPushSinkRotation > ( "ApplicationPushSinkRotation" );
cf->registerComponent< ApplicationPushSinkPositionList > ( "ApplicationPushSinkPositionList" );
cf->registerComponent< ApplicationPushSinkPositionList2 > ( "ApplicationPushSinkPosition2DList" );
cf->registerComponent< ApplicationPushSinkErrorPositionList > ( "ApplicationPushSinkErrorPositionList" );
cf->registerComponent< ApplicationPushSinkErrorPositionList2 > ( "ApplicationPushSinkErrorPosition2DList" );
cf->registerComponent< ApplicationPushSink< Measurement::Matrix3x4 > > ( "ApplicationPushSinkMatrix3x4" );
cf->registerComponent< ApplicationPushSink< Measurement::Matrix3x3 > > ( "ApplicationPushSinkMatrix3x3" );
cf->registerComponent< ApplicationPushSink< Measurement::Matrix4x4 > > ( "ApplicationPushSinkMatrix4x4" );
cf->registerComponent< ApplicationPushSink< Measurement::Distance > > ( "ApplicationPushSinkDistance" );
}
} } // namespace Ubitrack::Components
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "core/core.h"
#include "platform/dispatch.h"
int main(int argc, char *argv[])
{
Platform::init();
std::string file_name;
auto ram_saver = [&](const u8* data, u32 size)
{
std::ofstream to_save(file_name + "_ram", std::ios_base::trunc);
to_save.write(reinterpret_cast<const char*>(data), size * sizeof(u8));
};
auto rtc_saver = [&](std::chrono::seconds epoch, const u8* data, u32 size)
{
std::ofstream to_save(file_name + "_rtc", std::ios_base::trunc);
to_save << epoch.count();
to_save.write(reinterpret_cast<const char*>(data), size * sizeof(u8));
};
Core emu_core;
Platform::Audio audio_post;
Platform::Gui gui(3*160, 3*144, "GBE");
Platform::Renderer renderer(gui.get_display());
external_callbacks endpoints;
endpoints.save_ram = function<void(const u8*, u32)>(ram_saver);
endpoints.save_rtc = function<void(std::chrono::seconds, const u8*, u32)>(rtc_saver);
endpoints.audio_control = make_function(&Platform::Audio::dummy, &audio_post);
endpoints.swap_sample_buffer = make_function(&Platform::Audio::swap_buffers, &audio_post);
endpoints.draw_frame = make_function(&Platform::Renderer::vblank_handler, &renderer);
emu_core.attach_callbacks(endpoints);
Platform::after_attach(audio_post, renderer, gui);
#ifndef ENABLE_AUTO_TESTS
while (true)
{
std::cout << "Insert cartrige path:\n";
std::cin >> file_name;
std::ifstream rom(file_name, std::ios::binary | std::ios::in);
if (rom.is_open())
{
std::ifstream ram(file_name + "_ram"), rtc(file_name + "_rtc");
emu_core.load_cartrige(rom, ram, rtc);
std::string cart_name = emu_core.get_cart_name();
gui.set_window_title(cart_name);
std::cout << "Cartrige loaded!\n";
break;
}
std::cout << "Failed to load cartrige!\n";
}
#else
std::ifstream rom(argv[1]);
if (rom.is_open())
{
std::ifstream ram(file_name + "_ram"), rtc(file_name + "_rtc");
emu_core.load_cartrige(rom, ram, rtc);
}
#endif
while (gui.is_running())
{
gui.pump_input(emu_core);
emu_core.run_one_frame();
}
return 0;
}
<commit_msg>fixed ROM loading for auto testing<commit_after>#include "stdafx.h"
#include "core/core.h"
#include "platform/dispatch.h"
int main(int argc, char *argv[])
{
Platform::init();
std::string file_name;
auto ram_saver = [&](const u8* data, u32 size)
{
std::ofstream to_save(file_name + "_ram", std::ios_base::trunc);
to_save.write(reinterpret_cast<const char*>(data), size * sizeof(u8));
};
auto rtc_saver = [&](std::chrono::seconds epoch, const u8* data, u32 size)
{
std::ofstream to_save(file_name + "_rtc", std::ios_base::trunc);
to_save << epoch.count();
to_save.write(reinterpret_cast<const char*>(data), size * sizeof(u8));
};
Core emu_core;
Platform::Audio audio_post;
Platform::Gui gui(3*160, 3*144, "GBE");
Platform::Renderer renderer(gui.get_display());
external_callbacks endpoints;
endpoints.save_ram = function<void(const u8*, u32)>(ram_saver);
endpoints.save_rtc = function<void(std::chrono::seconds, const u8*, u32)>(rtc_saver);
endpoints.audio_control = make_function(&Platform::Audio::dummy, &audio_post);
endpoints.swap_sample_buffer = make_function(&Platform::Audio::swap_buffers, &audio_post);
endpoints.draw_frame = make_function(&Platform::Renderer::vblank_handler, &renderer);
emu_core.attach_callbacks(endpoints);
Platform::after_attach(audio_post, renderer, gui);
#ifndef ENABLE_AUTO_TESTS
while (true)
{
std::cout << "Insert cartrige path:\n";
std::cin >> file_name;
std::ifstream rom(file_name, std::ios::binary | std::ios::in);
if (rom.is_open())
{
std::ifstream ram(file_name + "_ram"), rtc(file_name + "_rtc");
emu_core.load_cartrige(rom, ram, rtc);
std::string cart_name = emu_core.get_cart_name();
gui.set_window_title(cart_name);
std::cout << "Cartrige loaded!\n";
break;
}
std::cout << "Failed to load cartrige!\n";
}
#else
std::ifstream rom(argv[1], std::ios::binary | std::ios::in);
if (rom.is_open())
{
std::ifstream ram(file_name + "_ram"), rtc(file_name + "_rtc");
emu_core.load_cartrige(rom, ram, rtc);
}
#endif
while (gui.is_running())
{
gui.pump_input(emu_core);
emu_core.run_one_frame();
}
return 0;
}
<|endoftext|> |
<commit_before>/*###############################################################
## MODULE: sparseKmeans.cpp
## VERSION: 1.0
## SINCE 2014-06-14
## AUTHOR:
## Jimmy Lin (xl5224) - JimmyLin@utexas.edu
## DESCRIPTION:
##
#################################################################
## Edited by MacVim
## Class Info auto-generated by Snippet
################################################################*/
#include "sparseClustering.h"
typedef double (* dist_func) (Instance*,Instance*,int);
double first_subproblm_obj (double ** dist_mat, double ** yone, double ** zone, double ** wone, double rho, int N) {
double ** temp = mat_init (N, N);
// sum1 = 0.5 * sum_n sum_k (w_nk * d^2_nk)
mat_times (wone, dist_mat, temp, N, N);
double sum1 = 0.5 * mat_sum (temp, N, N);
// sum2 = y_1^T dot w_1
mat_tdot (yone, wone, temp, N, N);
double sum2 = mat_sum (temp, N, N);
// sum3 = 0.5 * rho * || w_1 - z_1 ||^2
mat_sub (wone, zone, temp, N, N);
double sum3 = 0.5 * rho* mat_norm2 (temp, N, N);
mat_free (temp, N, N);
return sum1 + sum2 + sum3;
}
void frank_wolf (double ** dist_mat, double ** yone, double ** zone, double ** wone, double rho, int N) {
// STEP ONE: find s minimize <s, grad f>
// This can be computed by using corner point.
double ** gradient = mat_init (N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
gradient[i][j] = dist_mat[i][j] + yone[i][j] + rho * (wone[i][j] - zone[i][j]);
}
}
double ** s = mat_init (N, N);
mat_min_col (gradient, s, N, N);
mat_free (gradient, N, N);
// STEP TWO: apply exact or inexact line search to find solution
// TODO: refine it by using exact line search algorithm
// Here we use inexact line search
int K = 100, k = 1; // iteration number
double gamma; // step size
double penalty;
double ** tempS = mat_init(N, N);
while (k < K) {
gamma = 2.0 / (k + 2.0);
mat_dot (gamma, s, tempS, N, N);
mat_dot (1.0-gamma, wone, wone, N, N);
mat_add (wone, tempS, wone, N, N);
// compute value of objective function
first_subproblm_obj (dist_mat, yone, zone, wone, rho, N);
// report the #iter and objective function
cout << "iteration: " << k << ", objective: " << penalty << endl;
k ++;
}
mat_free (tempS, N, N);
mat_free (s, N, N);
}
double sign (int input) {
if (input >= 0) return 1.0;
else return -1.0;
}
bool pairComparator (const std::pair<int, double>& firstElem, const std::pair<int, double>& secondElem) {
// sort pairs by second element with decreasing order
return firstElem.second > secondElem.second;
}
void blockwise_closed_form (double ** ytwo, double ** ztwo, double ** wtwo, double rho, double lambda, int N) {
// STEP ONE: compute the optimal solution for truncated problem
double ** wbar = mat_init (N, N);
mat_dot (rho, ztwo, wbar, N, N); // wbar = rho * z_2
mat_sub (wbar, ytwo, wbar, N, N); // wbar = rho * z_2 - y_2
mat_dot (1.0/rho, wbar, wbar, N, N); // wbar = (rho * z_2 - y_2) / rho
// STEP TWO: find the closed-form solution for second subproblem
for (int j = 0; j < N; j ++) {
// 1. bifurcate the set of values
vector< pair<int,double> > alpha_vec;
for (int i = 0; i < N; i ++) {
double value = wbar[i][j];
alpha_vec.push_back (make_pair(i, abs(value)));
}
// 2. sorting
std::sort (alpha_vec.begin(), alpha_vec.end(), pairComparator);
// 3. find mstar
int mstar = 0; // number of elements support the sky
double separator;
double old_term = -INF, new_term;
double sum_alpha = 0.0;
for (int i = 0; i < N; i ++) {
sum_alpha += alpha_vec[i].second;
new_term = (sum_alpha - lambda) / (i + 1.0);
if ( new_term < old_term ) {
separator = alpha_vec[i].second;
break;
}
mstar ++;
old_term = new_term;
}
double max_term = old_term;
// 4. assign closed-form solution to wtwo
for (int i = 0; i < N; i ++) {
// harness vector of pair
double value = wbar[i][j];
if ( abs(value) > separator ) {
wtwo[i][j] = sign(wbar[i][j]) * max_term;
} else {
// its ranking is above m*, directly inherit the wbar
wtwo[i][j] = wbar[i][j];
}
}
}
// STEP THREE: recollect temporary variable - wbar
mat_free (wbar, N, N);
}
double L2norm (Instance * ins1, Instance * ins2, int N) {
// TODO:
// 1. refine by using hash table to restore each instance
// 2. avoid the apply memory for vec1, vec2, make it direct computation
double * vec1 = new double [N];
double * vec2 = new double [N];
for (int i = 0; i < ins1->fea.size(); i ++) {
vec1[ ins1->fea[i].first ] = ins1->fea[i].second;
}
for (int i = 0; i < ins2->fea.size(); i ++) {
vec2[ ins2->fea[i].first ] = ins2->fea[i].second;
}
double norm = 0.0;
for (int i = 0; i < N; i ++) {
norm += (vec1[i] - vec2[i]) * (vec1[i] - vec2[i]);
}
delete vec1, vec2;
return norm;
}
double opt_objective (double ** dist_mat, double lambda, int N, double ** z) {
// N is number of entities in "data", and z is N by N.
// z is current valid solution (average of w_1 and w_2)
// STEP ONE: compute loss function
double normSum = 0.0;
for (int i = 0; i < N; i ++) {
for (int j = 0; j < N; j ++) {
normSum += z[i][j] * dist_mat[i][j];
}
}
double loss = 0.5 * normSum;
// STEP TWO: compute group-lasso regularization
double * maxn = new double [N];
for (int i = 0;i < N; i ++) { // Ian: need initial
maxn[i] = -INF;
}
for (int i = 0; i < N; i ++) {
for (int j = 0; j < N; j ++) {
if (z[j][i] > maxn[i])
maxn[i] = z[j][i];
}
}
double sumk = 0.0;
for (int i = 0; i < N; i ++) {
sumk = maxn[i];
}
double reg = lambda * sumk;
return loss + reg;
}
/* Compute the mutual distance of input instances contained within "data" */
void compute_dist_mat (vector<Instance*>& data, double ** dist_mat, int N, dist_func df, bool isSym) {
for (int i = 0; i < N; i ++) {
for (int j = 0; j < N; j ++) {
if (j >= i || !isSym) { // invoke dist_func
Instance * xi = data[i];
Instance * muj = data[j];
dist_mat[i][j] = df (xi, muj, N);
} else { // by symmetry
dist_mat[i][j] = dist_mat[j][i];
}
}
}
}
void sparseClustering ( vector<Instance*>& data, int D, int N, double lambda, double ** W) {
// parameters
double alpha = 0.1;
double rho = 1;
dist_func df = L2norm;
// iterative optimization
double error = INF;
double ** wone = mat_init (N, N);
double ** wtwo = mat_init (N, N);
double ** yone = mat_init (N, N);
double ** ytwo = mat_init (N, N);
double ** z = mat_init (N, N);
double ** diffone = mat_init (N, N);
double ** difftwo = mat_init (N, N);
double ** dist_mat = mat_init (N, N);
compute_dist_mat (data, dist_mat, N, df, true);
int iter = 0; // Ian: usually we count up (instead of count down)
int max_iter = 1000;
while ( iter < max_iter ) { // stopping criteria
// STEP ONE: resolve w_1 and w_2
// frank_wolf ();
blockwise_closed_form (ytwo, z, wtwo, rho, lambda, N);
// STEP TWO: update z by w_1 and w_2
mat_add (wone, wtwo, z, N, N);
mat_dot (0.5, z, z, N, N);
// STEP THREE: update the y_1 and y_2 by w_1, w_2 and z
mat_sub (wone, z, diffone, N, N);
mat_dot (alpha, diffone, diffone, N, N);
mat_sub (yone, diffone, yone, N, N);
mat_sub (wtwo, z, difftwo, N, N);
mat_dot (alpha, difftwo, difftwo, N, N);
mat_sub (ytwo, difftwo, ytwo, N, N);
// STEP FOUR: trace the objective function
error = opt_objective (dist_mat, lambda, N, z);
cout << "iter=" << iter << ", Overall Error: " << error << endl;
iter ++;
}
// STEP FIVE: put converged solution to destination W
mat_copy(z, W, N, N);
}
// entry main function
int main (int argc, char ** argv) {
// exception control
if (argc < 3) {
cerr << "Usage: sparseClustering [dataFile] [lambda]" << endl;
cerr << "Note: dataFile must be scaled to [0,1] in advance." << endl;
exit(-1);
}
// parse arguments
char * dataFile = argv[1];
double lambda = atof(argv[2]);
// read in data
vector<Instance*> data;
read2D (dataFile, data);
// explore the data
int dimensions = -1;
int N = data.size(); // data size
for (int i = 0; i < N; i++) {
vector< pair<int,double> > * f = &(data[i]->fea);
int last_index = f->size() - 1;
if (f->at(last_index).first > dimensions) {
dimensions = f->at(last_index).first;
}
}
int D = dimensions;
cout << "D = " << D << endl; // # features
cout << "N = " << N << endl; // # instances
cout << "lambda = " << lambda << endl;
int seed = time(NULL);
srand(seed);
cout << "seed = " << seed << endl;
// Run sparse convex clustering
map<int, Cluster*> clusters;
double ** W = mat_init (N, N);
sparseClustering (data, D, N, lambda, W);
// Output results
}
<commit_msg>frank-wolf<commit_after>/*###############################################################
## MODULE: sparseKmeans.cpp
## VERSION: 1.0
## SINCE 2014-06-14
## AUTHOR:
## Jimmy Lin (xl5224) - JimmyLin@utexas.edu
## DESCRIPTION:
##
#################################################################
## Edited by MacVim
## Class Info auto-generated by Snippet
################################################################*/
#include "sparseClustering.h"
typedef double (* dist_func) (Instance*,Instance*,int);
double first_subproblm_obj (double ** dist_mat, double ** yone, double ** zone, double ** wone, double rho, int N) {
double ** temp = mat_init (N, N);
// sum1 = 0.5 * sum_n sum_k (w_nk * d^2_nk)
mat_times (wone, dist_mat, temp, N, N);
double sum1 = 0.5 * mat_sum (temp, N, N);
// sum2 = y_1^T dot w_1
mat_tdot (yone, wone, temp, N, N);
double sum2 = mat_sum (temp, N, N);
// sum3 = 0.5 * rho * || w_1 - z_1 ||^2
mat_sub (wone, zone, temp, N, N);
double sum3 = 0.5 * rho* mat_norm2 (temp, N, N);
mat_free (temp, N, N);
return sum1 + sum2 + sum3;
}
void frank_wolf (double ** dist_mat, double ** yone, double ** zone, double ** wone, double rho, int N) {
// STEP ONE: find s minimize <s, grad f>
// This can be computed by using corner point.
double ** gradient = mat_init (N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
gradient[i][j] = dist_mat[i][j] + yone[i][j] + rho * (wone[i][j] - zone[i][j]);
}
}
double ** s = mat_init (N, N);
mat_min_col (gradient, s, N, N);
mat_free (gradient, N, N);
// STEP TWO: apply exact or inexact line search to find solution
// TODO: refine it by using exact line search algorithm
// Here we use inexact line search
int K = 3, k = 1; // iteration number
double gamma; // step size
double penalty;
double ** tempS = mat_init(N, N);
while (k < K) {
gamma = 2.0 / (k + 2.0);
mat_dot (gamma, s, tempS, N, N);
mat_dot (1.0-gamma, wone, wone, N, N);
mat_add (wone, tempS, wone, N, N);
// compute value of objective function
first_subproblm_obj (dist_mat, yone, zone, wone, rho, N);
// report the #iter and objective function
cout << "iteration: " << k << ", objective: " << penalty << endl;
k ++;
}
mat_free (tempS, N, N);
mat_free (s, N, N);
}
double sign (int input) {
if (input >= 0) return 1.0;
else return -1.0;
}
bool pairComparator (const std::pair<int, double>& firstElem, const std::pair<int, double>& secondElem) {
// sort pairs by second element with decreasing order
return firstElem.second > secondElem.second;
}
void blockwise_closed_form (double ** ytwo, double ** ztwo, double ** wtwo, double rho, double lambda, int N) {
// STEP ONE: compute the optimal solution for truncated problem
double ** wbar = mat_init (N, N);
mat_dot (rho, ztwo, wbar, N, N); // wbar = rho * z_2
mat_sub (wbar, ytwo, wbar, N, N); // wbar = rho * z_2 - y_2
mat_dot (1.0/rho, wbar, wbar, N, N); // wbar = (rho * z_2 - y_2) / rho
// STEP TWO: find the closed-form solution for second subproblem
for (int j = 0; j < N; j ++) {
// 1. bifurcate the set of values
vector< pair<int,double> > alpha_vec;
for (int i = 0; i < N; i ++) {
double value = wbar[i][j];
alpha_vec.push_back (make_pair(i, abs(value)));
}
// 2. sorting
std::sort (alpha_vec.begin(), alpha_vec.end(), pairComparator);
// 3. find mstar
int mstar = 0; // number of elements support the sky
double separator;
double old_term = -INF, new_term;
double sum_alpha = 0.0;
for (int i = 0; i < N; i ++) {
sum_alpha += alpha_vec[i].second;
new_term = (sum_alpha - lambda) / (i + 1.0);
if ( new_term < old_term ) {
separator = alpha_vec[i].second;
break;
}
mstar ++;
old_term = new_term;
}
double max_term = old_term;
// 4. assign closed-form solution to wtwo
for (int i = 0; i < N; i ++) {
// harness vector of pair
double value = wbar[i][j];
if ( abs(value) > separator ) {
wtwo[i][j] = sign(wbar[i][j]) * max_term;
} else {
// its ranking is above m*, directly inherit the wbar
wtwo[i][j] = wbar[i][j];
}
}
}
// STEP THREE: recollect temporary variable - wbar
mat_free (wbar, N, N);
}
double L2norm (Instance * ins1, Instance * ins2, int N) {
// TODO:
// 1. refine by using hash table to restore each instance
// 2. avoid the apply memory for vec1, vec2, make it direct computation
double * vec1 = new double [N];
double * vec2 = new double [N];
for (int i = 0; i < ins1->fea.size(); i ++) {
vec1[ ins1->fea[i].first ] = ins1->fea[i].second;
}
for (int i = 0; i < ins2->fea.size(); i ++) {
vec2[ ins2->fea[i].first ] = ins2->fea[i].second;
}
double norm = 0.0;
for (int i = 0; i < N; i ++) {
norm += (vec1[i] - vec2[i]) * (vec1[i] - vec2[i]);
}
delete vec1, vec2;
return norm;
}
double opt_objective (double ** dist_mat, double lambda, int N, double ** z) {
// N is number of entities in "data", and z is N by N.
// z is current valid solution (average of w_1 and w_2)
// STEP ONE: compute loss function
double normSum = 0.0;
for (int i = 0; i < N; i ++) {
for (int j = 0; j < N; j ++) {
normSum += z[i][j] * dist_mat[i][j];
}
}
double loss = 0.5 * normSum;
// STEP TWO: compute group-lasso regularization
double * maxn = new double [N];
for (int i = 0;i < N; i ++) { // Ian: need initial
maxn[i] = -INF;
}
for (int i = 0; i < N; i ++) {
for (int j = 0; j < N; j ++) {
if (z[j][i] > maxn[i])
maxn[i] = z[j][i];
}
}
double sumk = 0.0;
for (int i = 0; i < N; i ++) {
sumk = maxn[i];
}
double reg = lambda * sumk;
return loss + reg;
}
/* Compute the mutual distance of input instances contained within "data" */
void compute_dist_mat (vector<Instance*>& data, double ** dist_mat, int N, dist_func df, bool isSym) {
for (int i = 0; i < N; i ++) {
for (int j = 0; j < N; j ++) {
if (j >= i || !isSym) { // invoke dist_func
Instance * xi = data[i];
Instance * muj = data[j];
dist_mat[i][j] = df (xi, muj, N);
} else { // by symmetry
dist_mat[i][j] = dist_mat[j][i];
}
}
}
}
void sparseClustering ( vector<Instance*>& data, int D, int N, double lambda, double ** W) {
// parameters
double alpha = 0.1;
double rho = 1;
dist_func df = L2norm;
// iterative optimization
double error = INF;
double ** wone = mat_init (N, N);
double ** wtwo = mat_init (N, N);
double ** yone = mat_init (N, N);
double ** ytwo = mat_init (N, N);
double ** z = mat_init (N, N);
double ** diffone = mat_init (N, N);
double ** difftwo = mat_init (N, N);
double ** dist_mat = mat_init (N, N);
compute_dist_mat (data, dist_mat, N, df, true);
int iter = 0; // Ian: usually we count up (instead of count down)
int max_iter = 1000;
while ( iter < max_iter ) { // stopping criteria
// STEP ONE: resolve w_1 and w_2
frank_wolf (dist_mat, yone, z, wone, rho, N);
blockwise_closed_form (ytwo, z, wtwo, rho, lambda, N);
// STEP TWO: update z by w_1 and w_2
mat_add (wone, wtwo, z, N, N);
mat_dot (0.5, z, z, N, N);
// STEP THREE: update the y_1 and y_2 by w_1, w_2 and z
mat_sub (wone, z, diffone, N, N);
mat_dot (alpha, diffone, diffone, N, N);
mat_sub (yone, diffone, yone, N, N);
mat_sub (wtwo, z, difftwo, N, N);
mat_dot (alpha, difftwo, difftwo, N, N);
mat_sub (ytwo, difftwo, ytwo, N, N);
// STEP FOUR: trace the objective function
error = opt_objective (dist_mat, lambda, N, z);
cout << "iter=" << iter << ", Overall Error: " << error << endl;
iter ++;
}
// STEP FIVE: put converged solution to destination W
mat_copy(z, W, N, N);
}
// entry main function
int main (int argc, char ** argv) {
// exception control
if (argc < 3) {
cerr << "Usage: sparseClustering [dataFile] [lambda]" << endl;
cerr << "Note: dataFile must be scaled to [0,1] in advance." << endl;
exit(-1);
}
// parse arguments
char * dataFile = argv[1];
double lambda = atof(argv[2]);
// read in data
vector<Instance*> data;
read2D (dataFile, data);
// explore the data
int dimensions = -1;
int N = data.size(); // data size
for (int i = 0; i < N; i++) {
vector< pair<int,double> > * f = &(data[i]->fea);
int last_index = f->size() - 1;
if (f->at(last_index).first > dimensions) {
dimensions = f->at(last_index).first;
}
}
int D = dimensions;
cout << "D = " << D << endl; // # features
cout << "N = " << N << endl; // # instances
cout << "lambda = " << lambda << endl;
int seed = time(NULL);
srand(seed);
cout << "seed = " << seed << endl;
// Run sparse convex clustering
map<int, Cluster*> clusters;
double ** W = mat_init (N, N);
sparseClustering (data, D, N, lambda, W);
// Output results
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "drivers/xml/serializablecodec_xml.h"
#include "core/enginecontext.h"
#include "core/fileaccess.h"
#include "core/resourceloader.h"
#include "core/serializable.h"
#include "core/type_traits/attributeaccessor.h"
#include "core/type_traits/objectdefinition.h"
#include "core/utils.h"
#include <cstring>
#include <logger.h>
namespace CodeHero {
// Standard parsing
bool ParseBool(const std::string& iInput) {
bool res = false;
if (iInput == "true") {
res = true;
} else if (iInput == "false") {
res = false;
} else {
LOGE << "[SerializableCodecXML]: Faile to parse bool argument: '" << iInput << "' is not valid." << std::endl;
}
return res;
}
float ParseFloat(const std::string& iInput) {
float res = 0.0f;
try {
res = std::stof(iInput);
} catch (const std::exception& e) {
LOGE << "XML: Fail to parse float argument, got: " << e.what() << std::endl;
}
return res;
}
Vector3 ParseVector3(const std::string& iInput) {
Vector3 res;
auto nums = Split(iInput, ' ');
if (nums.size() != 3) {
LOGE << "XML: Fail to parse Vector3 argument. Got " << nums.size() << " members, expected 3." << std::endl;
return res;
}
try {
res.SetX(ParseFloat(nums[0]));
res.SetY(ParseFloat(nums[1]));
res.SetZ(ParseFloat(nums[2]));
} catch (const std::exception& e) {
LOGE << "XML: Fail to parse Vector3 argument, got: " << e.what() << std::endl;
}
return res;
}
VariantArray ParseArray(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) {
VariantArray res;
for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) {
if (std::strcmp(it->name(), "subattribute") == 0) {
std::string attrVal = it->attribute("value").as_string();
res.push_back(attrVal);
} else {
LOGE << "[SerializableCodeXML]: Failed to parse array attribute with name '" << it->name() << "'" << std::endl;
}
}
return std::move(res);
}
VariantHashMap ParseHashMap(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) {
VariantHashMap res;
for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) {
if (std::strcmp(it->name(), "subattribute") == 0) {
std::string attr = it->attribute("name").as_string();
std::string attrVal = it->attribute("value").as_string();
res[attr] = attrVal;
} else {
LOGE << "[SerializableCodeXML]: Failed to parse hashmap attribute with name '" << it->name() << "'" << std::endl;
}
}
return std::move(res);
}
SerializableCodecXML::SerializableCodecXML(const std::shared_ptr<EngineContext>& iContext)
: ResourceCodec<Serializable>(iContext) {
std::vector<std::string> ext{"xml", "XML"};
for (auto& e : ext) {
_AddExtension(e);
}
}
SerializableCodecXML::~SerializableCodecXML() {}
Error SerializableCodecXML::Load(FileAccess& iF, Serializable& oObject) {
const int32_t size = iF.GetSize();
char* buffer = new char[size];
iF.Read(reinterpret_cast<uint8_t*>(buffer), size);
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_string(buffer);
if (!result) {
LOGE << "XML [" << buffer << "] parsed with errors, attr value: [" << doc.child("node").attribute("attr").value() << "]" << std::endl;
LOGE << "Error description: " << result.description() << std::endl;
LOGE << "Error offset: " << result.offset << " (error at [..." << (buffer + result.offset) << "]" << std::endl;
return ERR_PARSING_FAILED;
}
const std::string rootTypeName = oObject.GetTypeName();
pugi::xml_node root = doc.child(rootTypeName.c_str());
if (!root) {
LOGE << "Failed to find node " << rootTypeName << ". Object not imported." << std::endl;
return ERR_PARSING_FAILED;
}
auto rootDef = Object::GetDefinition(rootTypeName);
if (!rootDef) {
LOGE << "No definition was declared for object '" << rootTypeName << "'. Object not imported." << std::endl;
return ERR_INVALID_PARAMETER;
}
Error loadResult = _Load(rootDef, root, oObject);
delete [] buffer;
return loadResult;
}
Error SerializableCodecXML::_Load(const std::shared_ptr<ObjectDefinition>& iDefinition,
const pugi::xml_node& iNode,
Serializable& oObject) const {
oObject.BeginLoad();
for (pugi::xml_node_iterator it = iNode.begin(); it != iNode.end(); ++it) {
// If the current node is attribute, then it is an attribute for the current object
if (std::strcmp(it->name(), "attribute") == 0) {
// No need to check for neither if name or value exists, the GetAttribe and then the parsers will fail
// if no value where passed
std::string attr = it->attribute("name").as_string();
std::string attrVal = it->attribute("value").as_string();
auto attrInfo = iDefinition->GetAttribute(attr);
if (attrInfo.IsNull()) {
LOGE << "Attribute '" << attr << "' not registered for object '" << iDefinition->GetName()
<< "', ignored." << std::endl;
} else {
switch (attrInfo.GetType()) {
case Variant::Value::VVT_Bool:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseBool(attrVal)));
break;
case Variant::Value::VVT_Float:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseFloat(attrVal)));
break;
case Variant::Value::VVT_String:
attrInfo.GetAccessor()->Set(&oObject, Variant(std::string(attrVal)));
break;
case Variant::Value::VVT_Vector3:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseVector3(attrVal)));
break;
case Variant::Value::VVT_Array:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseArray(it->children())));
break;
case Variant::Value::VVT_HashMap:
// HashMap in variant for now does support only <string, string>
// When the type will evolve in a more complicated/complete version
// we will need to revise this parsing
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseHashMap(it->children())));
break;
case Variant::Value::VVT_SerializablePtr:
// If the tag is attribute and the type is shared_ptr<Serializable>
// we consider that we expect a collection of SerializablePtr object
// the attribute tag being a way to group those elements together
if (_ParseCollection(it->children(), attrInfo, oObject) != Error::OK) {
LOGE << "[SerializableCodeXML]: Failed to parse collection '" << attr << "'." << std::endl;
}
break;
default:
// Should not be here...
CH_ASSERT(false);
break;
}
}
} else {
auto attrInfo = iDefinition->GetAttribute(it->name());
if (attrInfo.IsNull()) {
LOGE << "Attribute '" << it->name() << "' not registered for object '" << iDefinition->GetName()
<< "', ignored." << std::endl;
continue;
}
_LoadObject(it, attrInfo, oObject);
}
}
oObject.EndLoad();
return OK;
}
Error SerializableCodecXML::_ParseCollection(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren,
const AttributeInfo& iAttrInfo,
Serializable& oObject) const {
Error ret = Error::OK;
for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) {
ret = _LoadObject(it, iAttrInfo, oObject);
if (ret != Error::OK) {
LOGE << "[SerializableCodecXML]: Failed to load object '" << it->name() << "'." << std::endl;
break;
}
}
return ret;
}
Error SerializableCodecXML::_LoadObject(const pugi::xml_node_iterator& iNode, const AttributeInfo& iAttrInfo, Serializable& oObject) const {
auto def = Object::GetDefinition(iNode->name());
if (!def) {
LOGE << "[SerializableCodecXML]: No definition was declared for object '" << iNode->name()
<< "'. Object not imported." << std::endl;
return Error::ERR_PARSING_FAILED;
}
auto attr = iNode->attribute("path");
// Whatever path we take next, we will need this object
std::shared_ptr<Serializable> obj = std::static_pointer_cast<Serializable>(def->Create());
// If it has a path to file, we use the resource loader
if (attr) {
m_pContext->GetSubsystem<ResourceLoader<Serializable>>()->Load(attr.as_string(), *obj.get());
} else { // Or we load it here
// TODO(pierre) All object here can be serializable
// but we should add a test. We can at least do a IsA (to be added soon)
Error res = _Load(def, *iNode, *obj.get());
if (res != Error::OK) {
LOGE << "[SerializableCodecXML]: Failed to import " << iNode->name() << " object. Continuing..."
<< std::endl;
return res;
}
}
iAttrInfo.GetAccessor()->Set(&oObject, Variant(obj));
return Error::OK;
}
} // namespace CodeHero
<commit_msg>Added parsing for Quat and Vec2 in serializable xml codec<commit_after>// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "drivers/xml/serializablecodec_xml.h"
#include "core/enginecontext.h"
#include "core/fileaccess.h"
#include "core/resourceloader.h"
#include "core/serializable.h"
#include "core/type_traits/attributeaccessor.h"
#include "core/type_traits/objectdefinition.h"
#include "core/utils.h"
#include <cstring>
#include <logger.h>
namespace CodeHero {
// Standard parsing
bool ParseBool(const std::string& iInput) {
bool res = false;
if (iInput == "true") {
res = true;
} else if (iInput == "false") {
res = false;
} else {
LOGE << "[SerializableCodecXML]: Faile to parse bool argument: '" << iInput << "' is not valid." << std::endl;
}
return res;
}
float ParseFloat(const std::string& iInput) {
float res = 0.0f;
try {
res = std::stof(iInput);
} catch (const std::exception& e) {
LOGE << "XML: Fail to parse float argument, got: " << e.what() << std::endl;
}
return res;
}
Vector2 ParseVector2(const std::string& iInput) {
Vector2 res;
auto nums = Split(iInput, ' ');
if (nums.size() != 2) {
LOGE << "[SerializableCodexXML]: Fail to parse Vector2 argument. Got " << nums.size() << " members, expected 2." << std::endl;
return res;
}
try {
res.SetX(ParseFloat(nums[0]));
res.SetY(ParseFloat(nums[1]));
} catch (const std::exception& e) {
LOGE << "[SerializableCodexXML]: Fail to parse Vector2 argument, got: " << e.what() << std::endl;
}
return res;
}
Vector3 ParseVector3(const std::string& iInput) {
Vector3 res;
auto nums = Split(iInput, ' ');
if (nums.size() != 3) {
LOGE << "XML: Fail to parse Vector3 argument. Got " << nums.size() << " members, expected 3." << std::endl;
return res;
}
try {
res.SetX(ParseFloat(nums[0]));
res.SetY(ParseFloat(nums[1]));
res.SetZ(ParseFloat(nums[2]));
} catch (const std::exception& e) {
LOGE << "XML: Fail to parse Vector3 argument, got: " << e.what() << std::endl;
}
return res;
}
Quaternion ParseQuaternion(const std::string& iInput) {
Quaternion res;
auto nums = Split(iInput, ' ');
if (nums.size() == 3) {
try {
res.FromEulerAngles(ParseFloat(nums[0]), ParseFloat(nums[1]), ParseFloat(nums[2]));
} catch (const std::exception& e) {
LOGE << "[SerializableCodexXML]: Fail to parse Quaternion argument, got: " << e.what() << std::endl;
}
} else {
LOGE << "[SerializableCodexXML]: Fail to parse Quaternion argument. Got " << nums.size() << " members." << std::endl;
}
return res;
}
VariantArray ParseArray(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) {
VariantArray res;
for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) {
if (std::strcmp(it->name(), "subattribute") == 0) {
std::string attrVal = it->attribute("value").as_string();
res.push_back(attrVal);
} else {
LOGE << "[SerializableCodeXML]: Failed to parse array attribute with name '" << it->name() << "'" << std::endl;
}
}
return std::move(res);
}
VariantHashMap ParseHashMap(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) {
VariantHashMap res;
for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) {
if (std::strcmp(it->name(), "subattribute") == 0) {
std::string attr = it->attribute("name").as_string();
std::string attrVal = it->attribute("value").as_string();
res[attr] = attrVal;
} else {
LOGE << "[SerializableCodeXML]: Failed to parse hashmap attribute with name '" << it->name() << "'" << std::endl;
}
}
return std::move(res);
}
SerializableCodecXML::SerializableCodecXML(const std::shared_ptr<EngineContext>& iContext)
: ResourceCodec<Serializable>(iContext) {
std::vector<std::string> ext{"xml", "XML"};
for (auto& e : ext) {
_AddExtension(e);
}
}
SerializableCodecXML::~SerializableCodecXML() {}
Error SerializableCodecXML::Load(FileAccess& iF, Serializable& oObject) {
const int32_t size = iF.GetSize();
char* buffer = new char[size];
iF.Read(reinterpret_cast<uint8_t*>(buffer), size);
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_string(buffer);
if (!result) {
LOGE << "XML [" << buffer << "] parsed with errors, attr value: [" << doc.child("node").attribute("attr").value() << "]" << std::endl;
LOGE << "Error description: " << result.description() << std::endl;
LOGE << "Error offset: " << result.offset << " (error at [..." << (buffer + result.offset) << "]" << std::endl;
return ERR_PARSING_FAILED;
}
const std::string rootTypeName = oObject.GetTypeName();
pugi::xml_node root = doc.child(rootTypeName.c_str());
if (!root) {
LOGE << "Failed to find node " << rootTypeName << ". Object not imported." << std::endl;
return ERR_PARSING_FAILED;
}
auto rootDef = Object::GetDefinition(rootTypeName);
if (!rootDef) {
LOGE << "No definition was declared for object '" << rootTypeName << "'. Object not imported." << std::endl;
return ERR_INVALID_PARAMETER;
}
Error loadResult = _Load(rootDef, root, oObject);
delete [] buffer;
return loadResult;
}
Error SerializableCodecXML::_Load(const std::shared_ptr<ObjectDefinition>& iDefinition,
const pugi::xml_node& iNode,
Serializable& oObject) const {
oObject.BeginLoad();
for (pugi::xml_node_iterator it = iNode.begin(); it != iNode.end(); ++it) {
// If the current node is attribute, then it is an attribute for the current object
if (std::strcmp(it->name(), "attribute") == 0) {
// No need to check for neither if name or value exists, the GetAttribe and then the parsers will fail
// if no value where passed
std::string attr = it->attribute("name").as_string();
std::string attrVal = it->attribute("value").as_string();
auto attrInfo = iDefinition->GetAttribute(attr);
if (attrInfo.IsNull()) {
LOGE << "Attribute '" << attr << "' not registered for object '" << iDefinition->GetName()
<< "', ignored." << std::endl;
} else {
switch (attrInfo.GetType()) {
case Variant::Value::VVT_Bool:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseBool(attrVal)));
break;
case Variant::Value::VVT_Float:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseFloat(attrVal)));
break;
case Variant::Value::VVT_String:
attrInfo.GetAccessor()->Set(&oObject, Variant(std::string(attrVal)));
break;
case Variant::Value::VVT_Vector2:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseVector2(attrVal)));
break;
case Variant::Value::VVT_Vector3:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseVector3(attrVal)));
break;
case Variant::Value::VVT_Quaternion:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseQuaternion(attrVal)));
break;
case Variant::Value::VVT_Array:
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseArray(it->children())));
break;
case Variant::Value::VVT_HashMap:
// HashMap in variant for now does support only <string, string>
// When the type will evolve in a more complicated/complete version
// we will need to revise this parsing
attrInfo.GetAccessor()->Set(&oObject, Variant(ParseHashMap(it->children())));
break;
case Variant::Value::VVT_SerializablePtr:
// If the tag is attribute and the type is shared_ptr<Serializable>
// we consider that we expect a collection of SerializablePtr object
// the attribute tag being a way to group those elements together
if (_ParseCollection(it->children(), attrInfo, oObject) != Error::OK) {
LOGE << "[SerializableCodeXML]: Failed to parse collection '" << attr << "'." << std::endl;
}
break;
default:
// Should not be here...
CH_ASSERT(false);
break;
}
}
} else {
auto attrInfo = iDefinition->GetAttribute(it->name());
if (attrInfo.IsNull()) {
LOGE << "Attribute '" << it->name() << "' not registered for object '" << iDefinition->GetName()
<< "', ignored." << std::endl;
continue;
}
_LoadObject(it, attrInfo, oObject);
}
}
oObject.EndLoad();
return OK;
}
Error SerializableCodecXML::_ParseCollection(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren,
const AttributeInfo& iAttrInfo,
Serializable& oObject) const {
Error ret = Error::OK;
for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) {
ret = _LoadObject(it, iAttrInfo, oObject);
if (ret != Error::OK) {
LOGE << "[SerializableCodecXML]: Failed to load object '" << it->name() << "'." << std::endl;
break;
}
}
return ret;
}
Error SerializableCodecXML::_LoadObject(const pugi::xml_node_iterator& iNode, const AttributeInfo& iAttrInfo, Serializable& oObject) const {
auto def = Object::GetDefinition(iNode->name());
if (!def) {
LOGE << "[SerializableCodecXML]: No definition was declared for object '" << iNode->name()
<< "'. Object not imported." << std::endl;
return Error::ERR_PARSING_FAILED;
}
auto attr = iNode->attribute("path");
// Whatever path we take next, we will need this object
std::shared_ptr<Serializable> obj = std::static_pointer_cast<Serializable>(def->Create());
// If it has a path to file, we use the resource loader
if (attr) {
m_pContext->GetSubsystem<ResourceLoader<Serializable>>()->Load(attr.as_string(), *obj.get());
} else { // Or we load it here
// TODO(pierre) All object here can be serializable
// but we should add a test. We can at least do a IsA (to be added soon)
Error res = _Load(def, *iNode, *obj.get());
if (res != Error::OK) {
LOGE << "[SerializableCodecXML]: Failed to import " << iNode->name() << " object. Continuing..."
<< std::endl;
return res;
}
}
iAttrInfo.GetAccessor()->Set(&oObject, Variant(obj));
return Error::OK;
}
} // namespace CodeHero
<|endoftext|> |
<commit_before>#include "Shader.h"
#include <iostream>
#include <Utils/File.h>
using namespace Utils;
namespace Graphics
{
std::string GetShaderCompileError(GLuint shader)
{
GLint length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
GLchar* buffer = new GLchar[length + 1];
glGetShaderInfoLog(shader, length, NULL, buffer);
std::string output(buffer, length + 1);
delete buffer;
return output;
}
Shader::Shader()
{
program = 0;
}
Shader::~Shader()
{
if (program != 0)
{
glDeleteProgram(program);
}
}
bool Shader::LoadFromFiles(std::string vertFile, std::string fragFile)
{
//Read source
auto vertContents = File::ReadAllText(vertFile);
auto fragContents = File::ReadAllText(fragFile);
return LoadFromStrings(*vertContents, *fragContents);
}
bool Shader::LoadFromStrings(std::string& vertContents, std::string& fragContents)
{
program = glCreateProgram();
auto vertexShader = glCreateShader(GL_VERTEX_SHADER);
auto fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
//Load shaders
const char* vertSource = vertContents.c_str();
const char* fragSource = fragContents.c_str();
glShaderSource(vertexShader, 1, &vertSource, NULL);
glShaderSource(fragmentShader, 1, &fragSource, NULL);
//Compile the shaders
int success;
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
std::cout << "Vertex shader failed to compile.\n";
std::cout << GetShaderCompileError(vertexShader);
goto error;
}
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
std::cout << "Fragment shader failed to compile.\n";
std::cout << GetShaderCompileError(vertexShader);
goto error;
}
//Attach shaders to program
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
//Bind the attributes to a standard location
glBindAttribLocation(program, (int)ShaderAttribute::Position, "in_position");
glBindAttribLocation(program, (int)ShaderAttribute::Normal, "in_normal");
glBindAttribLocation(program, (int)ShaderAttribute::UV, "in_uv");
//Link the program
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success)
{
std::cout << "Program failed to link.\n";
goto error;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return true;
error:
//Delete the gl objects
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glDeleteProgram(program);
return false;
}
void Shader::Start()
{
glUseProgram(program);
}
void Shader::Stop()
{
glUseProgram(0);
}
}
<commit_msg>Fixed copy-paste error.<commit_after>#include "Shader.h"
#include <iostream>
#include <Utils/File.h>
using namespace Utils;
namespace Graphics
{
std::string GetShaderCompileError(GLuint shader)
{
GLint length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
GLchar* buffer = new GLchar[length + 1];
glGetShaderInfoLog(shader, length, NULL, buffer);
std::string output(buffer, length + 1);
delete buffer;
return output;
}
Shader::Shader()
{
program = 0;
}
Shader::~Shader()
{
if (program != 0)
{
glDeleteProgram(program);
}
}
bool Shader::LoadFromFiles(std::string vertFile, std::string fragFile)
{
//Read source
auto vertContents = File::ReadAllText(vertFile);
auto fragContents = File::ReadAllText(fragFile);
return LoadFromStrings(*vertContents, *fragContents);
}
bool Shader::LoadFromStrings(std::string& vertContents, std::string& fragContents)
{
program = glCreateProgram();
auto vertexShader = glCreateShader(GL_VERTEX_SHADER);
auto fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
//Load shaders
const char* vertSource = vertContents.c_str();
const char* fragSource = fragContents.c_str();
glShaderSource(vertexShader, 1, &vertSource, NULL);
glShaderSource(fragmentShader, 1, &fragSource, NULL);
//Compile the shaders
int success;
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
std::cout << "Vertex shader failed to compile.\n";
std::cout << GetShaderCompileError(vertexShader);
goto error;
}
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
std::cout << "Fragment shader failed to compile.\n";
std::cout << GetShaderCompileError(fragmentShader);
goto error;
}
//Attach shaders to program
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
//Bind the attributes to a standard location
glBindAttribLocation(program, (int)ShaderAttribute::Position, "in_position");
glBindAttribLocation(program, (int)ShaderAttribute::Normal, "in_normal");
glBindAttribLocation(program, (int)ShaderAttribute::UV, "in_uv");
//Link the program
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success)
{
std::cout << "Program failed to link.\n";
goto error;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return true;
error:
//Delete the gl objects
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glDeleteProgram(program);
return false;
}
void Shader::Start()
{
glUseProgram(program);
}
void Shader::Stop()
{
glUseProgram(0);
}
}
<|endoftext|> |
<commit_before>// Copyright 2018 Global Phasing Ltd.
#include "gemmi/monlib.hpp"
#include "gemmi/read_cif.hpp" // for read_cif_gz
#include "common.h"
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
namespace py = pybind11;
using namespace gemmi;
using monomers_type = std::map<std::string, ChemComp>;
using links_type = std::map<std::string, ChemLink>;
using modifications_type = std::map<std::string, ChemMod>;
using residue_infos_type = std::map<std::string, ResidueInfo>;
PYBIND11_MAKE_OPAQUE(monomers_type)
PYBIND11_MAKE_OPAQUE(links_type)
PYBIND11_MAKE_OPAQUE(modifications_type)
PYBIND11_MAKE_OPAQUE(residue_infos_type)
void add_monlib(py::module& m) {
py::class_<ChemMod> chemmod(m, "ChemMod");
py::class_<ChemLink> chemlink(m, "ChemLink");
py::class_<ChemLink::Side> chemlinkside(chemlink, "Side");
py::bind_map<monomers_type>(m, "ChemCompMap");
py::bind_map<links_type>(m, "ChemLinkMap");
py::bind_map<modifications_type>(m, "ChemModMap");
py::bind_map<residue_infos_type>(m, "ResidueInfoMap");
chemlink
.def_readwrite("id", &ChemLink::id)
.def_readwrite("name", &ChemLink::name)
.def_readwrite("side1", &ChemLink::side1)
.def_readwrite("side2", &ChemLink::side2)
.def_readwrite("rt", &ChemLink::rt)
.def("__repr__", [](const ChemLink& self) {
return "<gemmi.ChemLink " + self.id + ">";
});
py::enum_<ChemLink::Group>(chemlinkside, "Group")
.value("Peptide", ChemLink::Group::Peptide)
.value("PPeptide", ChemLink::Group::PPeptide)
.value("MPeptide", ChemLink::Group::MPeptide)
.value("Pyranose", ChemLink::Group::Pyranose)
.value("DnaRna", ChemLink::Group::DnaRna)
.value("Null", ChemLink::Group::Null);
chemlinkside
.def_readwrite("comp", &ChemLink::Side::comp)
.def_readwrite("mod", &ChemLink::Side::mod)
.def_readwrite("group", &ChemLink::Side::group)
.def("__repr__", [](const ChemLink::Side& self) {
return "<gemmi.ChemLink.Side " + self.comp + "/" +
ChemLink::group_str(self.group) + ">";
});
chemmod
.def_readwrite("id", &ChemMod::id)
.def_readwrite("name", &ChemMod::name)
.def_readwrite("comp_id", &ChemMod::comp_id)
.def_readwrite("group_id", &ChemMod::group_id)
.def_readwrite("rt", &ChemMod::rt)
.def("__repr__", [](const ChemMod& self) {
return "<gemmi.ChemMod " + self.id + ">";
});
py::class_<MonLib>(m, "MonLib")
.def(py::init<>())
.def_readonly("monomers", &MonLib::monomers)
.def_readonly("links", &MonLib::links)
.def_readonly("modifications", &MonLib::modifications)
.def_readonly("residue_infos", &MonLib::residue_infos)
.def("find_link", &MonLib::find_link, py::arg("link_id"),
py::return_value_policy::reference_internal)
.def("find_mod", &MonLib::find_mod, py::arg("name"),
py::return_value_policy::reference_internal)
.def("find_residue_info", &MonLib::find_residue_info, py::arg("name"),
py::return_value_policy::reference_internal)
.def("match_link", &MonLib::match_link,
py::arg("comp1"), py::arg("atom1"),
py::arg("comp2"), py::arg("atom2"),
py::return_value_policy::reference_internal)
.def("add_monomer_if_present", &MonLib::add_monomer_if_present)
.def("add_monomers_if_present", &MonLib::add_monomers_if_present)
.def("insert_chemlinks", [](MonLib &self, const cif::Document &doc) {
insert_chemlinks(doc, self.links);
})
.def("insert_chemmods", [](MonLib &self, const cif::Document &doc) {
insert_chemmods(doc, self.modifications);
})
.def("insert_comp_list", [](MonLib &self, const cif::Document &doc) {
insert_comp_list(doc, self.residue_infos);
})
.def("path", &MonLib::path, py::arg("code")=nullptr)
.def("__repr__", [](const MonLib& self) {
return "<gemmi.MonLib with " +
std::to_string(self.monomers.size()) + " monomers, " +
std::to_string(self.links.size()) + " links, " +
std::to_string(self.modifications.size()) + " modifications>";
});
m.def("read_monomer_lib", [](const std::string& monomer_dir,
const std::vector<std::string>& resnames) {
return read_monomer_lib(monomer_dir, resnames, gemmi::read_cif_gz);
});
m.def("read_monomer_cif", [](const std::string& path) {
return read_monomer_cif(path, gemmi::read_cif_gz);
});
py::class_<BondIndex>(m, "BondIndex")
.def(py::init<const Model&>(), py::keep_alive<1, 2>())
.def("add_link", &BondIndex::add_link)
.def("add_monomer_bonds", &BondIndex::add_monomer_bonds)
.def("are_linked", &BondIndex::are_linked)
.def("graph_distance", &BondIndex::graph_distance,
py::arg("a"), py::arg("b"), py::arg("same_index"),
py::arg("max_distance")=4)
;
}
<commit_msg>python: add one more property to MonLib<commit_after>// Copyright 2018 Global Phasing Ltd.
#include "gemmi/monlib.hpp"
#include "gemmi/read_cif.hpp" // for read_cif_gz
#include "common.h"
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
namespace py = pybind11;
using namespace gemmi;
using monomers_type = std::map<std::string, ChemComp>;
using links_type = std::map<std::string, ChemLink>;
using modifications_type = std::map<std::string, ChemMod>;
using residue_infos_type = std::map<std::string, ResidueInfo>;
PYBIND11_MAKE_OPAQUE(monomers_type)
PYBIND11_MAKE_OPAQUE(links_type)
PYBIND11_MAKE_OPAQUE(modifications_type)
PYBIND11_MAKE_OPAQUE(residue_infos_type)
void add_monlib(py::module& m) {
py::class_<ChemMod> chemmod(m, "ChemMod");
py::class_<ChemLink> chemlink(m, "ChemLink");
py::class_<ChemLink::Side> chemlinkside(chemlink, "Side");
py::bind_map<monomers_type>(m, "ChemCompMap");
py::bind_map<links_type>(m, "ChemLinkMap");
py::bind_map<modifications_type>(m, "ChemModMap");
py::bind_map<residue_infos_type>(m, "ResidueInfoMap");
chemlink
.def_readwrite("id", &ChemLink::id)
.def_readwrite("name", &ChemLink::name)
.def_readwrite("side1", &ChemLink::side1)
.def_readwrite("side2", &ChemLink::side2)
.def_readwrite("rt", &ChemLink::rt)
.def("__repr__", [](const ChemLink& self) {
return "<gemmi.ChemLink " + self.id + ">";
});
py::enum_<ChemLink::Group>(chemlinkside, "Group")
.value("Peptide", ChemLink::Group::Peptide)
.value("PPeptide", ChemLink::Group::PPeptide)
.value("MPeptide", ChemLink::Group::MPeptide)
.value("Pyranose", ChemLink::Group::Pyranose)
.value("DnaRna", ChemLink::Group::DnaRna)
.value("Null", ChemLink::Group::Null);
chemlinkside
.def_readwrite("comp", &ChemLink::Side::comp)
.def_readwrite("mod", &ChemLink::Side::mod)
.def_readwrite("group", &ChemLink::Side::group)
.def("__repr__", [](const ChemLink::Side& self) {
return "<gemmi.ChemLink.Side " + self.comp + "/" +
ChemLink::group_str(self.group) + ">";
});
chemmod
.def_readwrite("id", &ChemMod::id)
.def_readwrite("name", &ChemMod::name)
.def_readwrite("comp_id", &ChemMod::comp_id)
.def_readwrite("group_id", &ChemMod::group_id)
.def_readwrite("rt", &ChemMod::rt)
.def("__repr__", [](const ChemMod& self) {
return "<gemmi.ChemMod " + self.id + ">";
});
py::class_<MonLib>(m, "MonLib")
.def(py::init<>())
.def_readonly("mon_lib_list", &MonLib::mon_lib_list)
.def_readonly("monomers", &MonLib::monomers)
.def_readonly("links", &MonLib::links)
.def_readonly("modifications", &MonLib::modifications)
.def_readonly("residue_infos", &MonLib::residue_infos)
.def("find_link", &MonLib::find_link, py::arg("link_id"),
py::return_value_policy::reference_internal)
.def("find_mod", &MonLib::find_mod, py::arg("name"),
py::return_value_policy::reference_internal)
.def("find_residue_info", &MonLib::find_residue_info, py::arg("name"),
py::return_value_policy::reference_internal)
.def("match_link", &MonLib::match_link,
py::arg("comp1"), py::arg("atom1"),
py::arg("comp2"), py::arg("atom2"),
py::return_value_policy::reference_internal)
.def("add_monomer_if_present", &MonLib::add_monomer_if_present)
.def("add_monomers_if_present", &MonLib::add_monomers_if_present)
.def("insert_chemlinks", [](MonLib &self, const cif::Document &doc) {
insert_chemlinks(doc, self.links);
})
.def("insert_chemmods", [](MonLib &self, const cif::Document &doc) {
insert_chemmods(doc, self.modifications);
})
.def("insert_comp_list", [](MonLib &self, const cif::Document &doc) {
insert_comp_list(doc, self.residue_infos);
})
.def("path", &MonLib::path, py::arg("code")=nullptr)
.def("__repr__", [](const MonLib& self) {
return "<gemmi.MonLib with " +
std::to_string(self.monomers.size()) + " monomers, " +
std::to_string(self.links.size()) + " links, " +
std::to_string(self.modifications.size()) + " modifications>";
});
m.def("read_monomer_lib", [](const std::string& monomer_dir,
const std::vector<std::string>& resnames) {
return read_monomer_lib(monomer_dir, resnames, gemmi::read_cif_gz);
});
m.def("read_monomer_cif", [](const std::string& path) {
return read_monomer_cif(path, gemmi::read_cif_gz);
});
py::class_<BondIndex>(m, "BondIndex")
.def(py::init<const Model&>(), py::keep_alive<1, 2>())
.def("add_link", &BondIndex::add_link)
.def("add_monomer_bonds", &BondIndex::add_monomer_bonds)
.def("are_linked", &BondIndex::are_linked)
.def("graph_distance", &BondIndex::graph_distance,
py::arg("a"), py::arg("b"), py::arg("same_index"),
py::arg("max_distance")=4)
;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTimeLineView.h"
/*InfoPopper constants*/
const int32 kNotify = 1000;
const int32 kInformationType = 1001;
const int32 kImportantType = 1002;
const int32 kErrorType = 1003;
const int32 kProgressType = 1004;
const int32 kAttributeIcon = 1005;
const int32 kContentsIcon = 1006;
HTGTimeLineView::HTGTimeLineView(twitCurl *twitObj, const int32 TYPE, BRect rect, const char* requestInfo) : BView(rect, "ContainerView", B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS) {
this->twitObj = twitObj;
this->TYPE = TYPE;
thread_id previousThread = B_NAME_NOT_FOUND;
searchID = 0;
/*Set view name*/
switch(TYPE) {
case TIMELINE_HOME:
SetName("Home");
break;
case TIMELINE_FRIENDS:
SetName("Friends");
break;
case TIMELINE_MENTIONS:
SetName("Mentions");
break;
case TIMELINE_PUBLIC:
SetName("Public");
break;
case TIMELINE_USER:
SetName(requestInfo);
break;
case TIMELINE_SEARCH:
SetName(requestInfo);
break;
default:
SetName("Public");
}
/*Set up listview*/
this->listView = new BListView(BRect(0, 0, 300, Bounds().Height()), "ListView", B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS);
/*Prepare the list for unhandled tweets*/
unhandledList = new BList();
/*Set up scrollview*/
theScrollView = new BScrollView("scrollView", listView, B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS, false, true);
this->AddChild(theScrollView);
/*Load infopopper settings (if supported)*/
wantsNotifications = false; //Default should be false
#ifdef INFOPOPPER_SUPPORT
wantsNotifications = _retrieveInfoPopperBoolFromSettings();
#endif
/*All done, ready to display tweets*/
waitingForUpdate = true;
updateTimeLine();
}
void HTGTimeLineView::setSearchID(int32 id) {
searchID = id;
}
int32 HTGTimeLineView::getSearchID() {
return searchID;
}
void HTGTimeLineView::AttachedToWindow() {
BView::AttachedToWindow();
if(waitingForUpdate)
updateTimeLine();
}
void HTGTimeLineView::updateTimeLine() {
bool looperLocked = listView->LockLooper();
/*Update timeline only if we can lock window looper -or we want notifications for this timeline*/
if(!looperLocked && !wantsNotifications)
waitingForUpdate = true;
else {
if(looperLocked) listView->UnlockLooper(); //Assume we can lock it later
previousThread = spawn_thread(updateTimeLineThread, "UpdateThread", 10, this);
resume_thread(previousThread);
waitingForUpdate = false;
}
}
std::string& htmlFormatedString(const char *orig) {
std::string newString(orig);
if(orig[0] == '#') {
newString = std::string(orig+1);
}
std::string *returnPtr = new std::string(newString);
return *returnPtr;
}
void HTGTimeLineView::savedSearchDestoySelf() {
/*Destroy saved search on twitter*/
std::string id;
std::stringstream out;
out << this->getSearchID(); //Converting int to string
id = out.str();
if(this->getSearchID() > 0)
twitObj->savedSearchDestroy(id);
}
void HTGTimeLineView::savedSearchCreateSelf() {
/*Save search to twitter*/
std::string query(::htmlFormatedString(Name()));
twitObj->savedSearchCreate(query);
std::string replyMsg(" ");
twitObj->getLastWebResponse(replyMsg);
/*Parse result*/
int pos = 0;
const char *idTag = "<id>";
pos = replyMsg.find(idTag, pos);
if(pos != std::string::npos) {
int start = pos+strlen(idTag);
int end = replyMsg.find("</id>", start);
std::string searchID(replyMsg.substr(start, end-start));
setSearchID(atoi(searchID.c_str()));
}
}
status_t updateTimeLineThread(void *data) {
//Could not figure out how to update a BListItem with a child view (BTextView).
//Could be a bug in Haiku API's. After hours of investigation without any
//result, I just don't care anymore. Reallocating all HTGTweetItem on update.
HTGTimeLineView *super = (HTGTimeLineView*)data;
/*Wait for previous thread to end*/
status_t junkId;
wait_for_thread(find_thread("UpdateThread"), &junkId);
BListView *listView = super->listView;
BView *containerView;
char *tabName;
int32 TYPE = super->TYPE;
twitCurl *twitObj = super->twitObj;
TimeLineParser *timeLineParser = new TimeLineParser();
SearchParser *searchParser = new SearchParser();
switch(TYPE) {
case TIMELINE_HOME:
twitObj->timelineHomeGet();
break;
case TIMELINE_FRIENDS:
twitObj->timelineFriendsGet();
break;
case TIMELINE_MENTIONS:
twitObj->mentionsGet();
break;
case TIMELINE_PUBLIC:
twitObj->timelinePublicGet();
break;
case TIMELINE_USER:
twitObj->timelineUserGet(*new std::string(super->Name()), false);
break;
case TIMELINE_SEARCH:
twitObj->search(htmlFormatedString(super->Name()));
break;
default:
twitObj->timelinePublicGet();
}
std::string replyMsg(" ");
twitObj->getLastWebResponse(replyMsg);
if(replyMsg.length() < 100) { //Length of data is less than 100 characters. Clearly,
replyMsg = "error"; //something is wrong... abort.
}
if(TYPE == TIMELINE_SEARCH) {
try {
searchParser->readData(replyMsg.c_str());
} catch( xercesc::XMLException& e ) {
std::cout << "Error while parsing data." << std::endl;
delete timeLineParser;
timeLineParser = NULL;
return B_OK;
}
timeLineParser = (TimeLineParser *)searchParser; //I'm not so sure this is a good way to go,
//so don't tell anyone;-)
}
else {
try {
timeLineParser->readData(replyMsg.c_str());
} catch( xercesc::XMLException& e ) {
std::cout << "Error while parsing data." << std::endl;
delete timeLineParser;
timeLineParser = NULL;
return B_OK;
}
}
HTGTweetItem *mostRecentItem = NULL;
HTTweet *mostRecentTweet = NULL;
HTTweet *currentTweet = NULL;
bool initialLoad = (listView->FirstItem() == NULL && super->unhandledList->FirstItem() == NULL);
if(!initialLoad && listView->FirstItem() != NULL) {
mostRecentItem = (HTGTweetItem *)listView->FirstItem();
mostRecentTweet = mostRecentItem->getTweetPtr();
currentTweet = timeLineParser->getTweets()[0];
/*If we are up to date: redraw, clean up and return*/
if(!(*mostRecentTweet < *currentTweet)) {
if(listView->LockLooper()) {
for(int i = 0; i < listView->CountItems(); i++) {
listView->InvalidateItem(i); //Update date
}
listView->UnlockLooper();
}
delete timeLineParser;
timeLineParser = NULL;
return B_OK;
}
}
/*Check to see if there is some unhandled tweets*/
if(!super->unhandledList->IsEmpty()) {
mostRecentItem = (HTGTweetItem *)super->unhandledList->FirstItem();
mostRecentTweet = mostRecentItem->getTweetPtr();
}
BList *newList = new BList();
for (int i = 0; i < timeLineParser->count(); i++) {
currentTweet = timeLineParser->getTweets()[i];
bool addItem = initialLoad;
if(!initialLoad) {
if(mostRecentTweet != NULL)
addItem = (*mostRecentTweet < *currentTweet);
else
addItem = true;
}
if(addItem) {
/*Make a copy, download bitmap and add it to newList*/
HTTweet *copiedTweet = new HTTweet(currentTweet);
copiedTweet->downloadBitmap();
newList->AddItem(new HTGTweetItem(copiedTweet));
if(!initialLoad && super->wantsNotifications) { //New tweet arrived, send notification
super->sendNotificationFor(copiedTweet);
}
}
else
break;
}
/*Try to lock listView*/
if(!listView->LockLooper()) {
/*Not active view: Copy tweetptrs to unhandledList and return*/
super->unhandledList->AddList(newList, 0); //Add new tweets to the top
super->waitingForUpdate = true;
delete timeLineParser;
timeLineParser = NULL;
if(newList->IsEmpty())
delete newList;
return B_OK;
}
/*Add the unhandled tweets to newList*/
newList->AddList(super->unhandledList);
super->unhandledList->MakeEmpty();
HTGTweetItem *currentItem;
while(!listView->IsEmpty()) {
currentItem = (HTGTweetItem *)listView->FirstItem();
currentTweet = currentItem->getTweetPtr();
listView->RemoveItem(currentItem); //Must lock looper before we do this!
if(newList->CountItems() < 20) //Only allow 20 tweets to be displayed at once... for now.
newList->AddItem(new HTGTweetItem(new HTTweet(currentTweet)));
delete currentItem;
}
/*Update the view*/
listView->AddList(newList); //Must lock looper before we do this!
/*Cleanup*/
super->waitingForUpdate = false;
listView->UnlockLooper();
delete timeLineParser;
timeLineParser = NULL;
delete newList;
return B_OK;
}
void HTGTimeLineView::sendNotificationFor(HTTweet *theTweet) {
std::string title("New tweet from ");
title.append(theTweet->getScreenName());
std::cout << title << std::endl;
#ifdef INFOPOPPER_SUPPORT
IPConnection *conn = new IPConnection;
IPMessage *msg = new IPMessage(InfoPopper::Information);
//Prepare the message
msg->Application("HaikuTwitter");
msg->Title(title.c_str());
msg->Content(theTweet->getText().c_str());
// Icon maybe in the future
/*if (strlen(fIconFile->Text()) > 0) {
entry_ref ref;
if (get_ref_for_path(fIconFile->Text(), &ref) == B_OK) {
if (fSelectedIconType == InfoPopper::Attribute) {
msg->MainIcon(ref);
msg->MainIconType(fSelectedIconType);
}
if (fSelectedIconType == InfoPopper::Contents) {
msg->OverlayIcon(ref);
msg->OverlayIconType(fSelectedIconType);
}
}
}*/
//Send the notification
conn->Send(msg);
delete msg;
delete conn;
#endif
}
bool HTGTimeLineView::_retrieveInfoPopperBoolFromSettings() {
BPath path;
infopopper_settings theSettings;
if (HTGInfoPopperSettingsWindow::_getSettingsPath(path) < B_OK) {
theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
switch(TYPE) {
case TIMELINE_FRIENDS:
return theSettings.friendsNotify;
break;
case TIMELINE_MENTIONS:
return theSettings.mentionsNotify;
break;
case TIMELINE_PUBLIC:
return theSettings.publicNotify;
break;
}
}
BFile file(path.Path(), B_READ_ONLY);
if (file.InitCheck() < B_OK) {
theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
switch(TYPE) {
case TIMELINE_FRIENDS:
return theSettings.friendsNotify;
break;
case TIMELINE_MENTIONS:
return theSettings.mentionsNotify;
break;
case TIMELINE_PUBLIC:
return theSettings.publicNotify;
break;
}
}
file.ReadAt(0, &theSettings, sizeof(infopopper_settings));
switch(TYPE) {
case TIMELINE_FRIENDS:
return theSettings.friendsNotify;
break;
case TIMELINE_MENTIONS:
return theSettings.mentionsNotify;
break;
case TIMELINE_PUBLIC:
return theSettings.publicNotify;
break;
}
return false; //Just in case nothing get's picked up... no compile error/warning without this though
}
HTGTimeLineView::~HTGTimeLineView() {
/*Kill the update thread*/
kill_thread(previousThread);
listView->RemoveSelf();
while(!listView->IsEmpty()) {
HTGTweetItem *currentItem = (HTGTweetItem *)listView->FirstItem();
listView->RemoveItem(currentItem);
delete currentItem;
}
delete listView;
delete twitObj;
theScrollView->RemoveSelf();
delete theScrollView;
}
<commit_msg>BUG FIX: UpdateThread didn't return if timelineparser didn't hold any tweets after parsing.<commit_after>/*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTimeLineView.h"
/*InfoPopper constants*/
const int32 kNotify = 1000;
const int32 kInformationType = 1001;
const int32 kImportantType = 1002;
const int32 kErrorType = 1003;
const int32 kProgressType = 1004;
const int32 kAttributeIcon = 1005;
const int32 kContentsIcon = 1006;
HTGTimeLineView::HTGTimeLineView(twitCurl *twitObj, const int32 TYPE, BRect rect, const char* requestInfo) : BView(rect, "ContainerView", B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS) {
this->twitObj = twitObj;
this->TYPE = TYPE;
thread_id previousThread = B_NAME_NOT_FOUND;
searchID = 0;
/*Set view name*/
switch(TYPE) {
case TIMELINE_HOME:
SetName("Home");
break;
case TIMELINE_FRIENDS:
SetName("Friends");
break;
case TIMELINE_MENTIONS:
SetName("Mentions");
break;
case TIMELINE_PUBLIC:
SetName("Public");
break;
case TIMELINE_USER:
SetName(requestInfo);
break;
case TIMELINE_SEARCH:
SetName(requestInfo);
break;
default:
SetName("Public");
}
/*Set up listview*/
this->listView = new BListView(BRect(0, 0, 300, Bounds().Height()), "ListView", B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS);
/*Prepare the list for unhandled tweets*/
unhandledList = new BList();
/*Set up scrollview*/
theScrollView = new BScrollView("scrollView", listView, B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS, false, true);
this->AddChild(theScrollView);
/*Load infopopper settings (if supported)*/
wantsNotifications = false; //Default should be false
#ifdef INFOPOPPER_SUPPORT
wantsNotifications = _retrieveInfoPopperBoolFromSettings();
#endif
/*All done, ready to display tweets*/
waitingForUpdate = true;
updateTimeLine();
}
void HTGTimeLineView::setSearchID(int32 id) {
searchID = id;
}
int32 HTGTimeLineView::getSearchID() {
return searchID;
}
void HTGTimeLineView::AttachedToWindow() {
BView::AttachedToWindow();
if(waitingForUpdate)
updateTimeLine();
}
void HTGTimeLineView::updateTimeLine() {
bool looperLocked = listView->LockLooper();
/*Update timeline only if we can lock window looper -or we want notifications for this timeline*/
if(!looperLocked && !wantsNotifications)
waitingForUpdate = true;
else {
if(looperLocked) listView->UnlockLooper(); //Assume we can lock it later
previousThread = spawn_thread(updateTimeLineThread, "UpdateThread", 10, this);
resume_thread(previousThread);
waitingForUpdate = false;
}
}
std::string& htmlFormatedString(const char *orig) {
std::string newString(orig);
if(orig[0] == '#') {
newString = std::string(orig+1);
}
std::string *returnPtr = new std::string(newString);
return *returnPtr;
}
void HTGTimeLineView::savedSearchDestoySelf() {
/*Destroy saved search on twitter*/
std::string id;
std::stringstream out;
out << this->getSearchID(); //Converting int to string
id = out.str();
if(this->getSearchID() > 0)
twitObj->savedSearchDestroy(id);
}
void HTGTimeLineView::savedSearchCreateSelf() {
/*Save search to twitter*/
std::string query(::htmlFormatedString(Name()));
twitObj->savedSearchCreate(query);
std::string replyMsg(" ");
twitObj->getLastWebResponse(replyMsg);
/*Parse result*/
int pos = 0;
const char *idTag = "<id>";
pos = replyMsg.find(idTag, pos);
if(pos != std::string::npos) {
int start = pos+strlen(idTag);
int end = replyMsg.find("</id>", start);
std::string searchID(replyMsg.substr(start, end-start));
setSearchID(atoi(searchID.c_str()));
}
}
status_t updateTimeLineThread(void *data) {
//Could not figure out how to update a BListItem with a child view (BTextView).
//Could be a bug in Haiku API's. After hours of investigation without any
//result, I just don't care anymore. Reallocating all HTGTweetItem on update.
HTGTimeLineView *super = (HTGTimeLineView*)data;
/*Wait for previous thread to end*/
status_t junkId;
wait_for_thread(find_thread("UpdateThread"), &junkId);
BListView *listView = super->listView;
BView *containerView;
char *tabName;
int32 TYPE = super->TYPE;
twitCurl *twitObj = super->twitObj;
TimeLineParser *timeLineParser = new TimeLineParser();
SearchParser *searchParser = new SearchParser();
switch(TYPE) {
case TIMELINE_HOME:
twitObj->timelineHomeGet();
break;
case TIMELINE_FRIENDS:
twitObj->timelineFriendsGet();
break;
case TIMELINE_MENTIONS:
twitObj->mentionsGet();
break;
case TIMELINE_PUBLIC:
twitObj->timelinePublicGet();
break;
case TIMELINE_USER:
twitObj->timelineUserGet(*new std::string(super->Name()), false);
break;
case TIMELINE_SEARCH:
twitObj->search(htmlFormatedString(super->Name()));
break;
default:
twitObj->timelinePublicGet();
}
std::string replyMsg(" ");
twitObj->getLastWebResponse(replyMsg);
if(replyMsg.length() < 100) { //Length of data is less than 100 characters. Clearly,
replyMsg = "error"; //something is wrong... abort.
}
if(TYPE == TIMELINE_SEARCH) {
try {
searchParser->readData(replyMsg.c_str());
} catch( xercesc::XMLException& e ) {
std::cout << "Error while parsing data." << std::endl;
delete timeLineParser;
timeLineParser = NULL;
return B_OK;
}
timeLineParser = (TimeLineParser *)searchParser; //I'm not so sure this is a good way to go,
//so don't tell anyone;-)
}
else {
try {
timeLineParser->readData(replyMsg.c_str());
} catch( xercesc::XMLException& e ) {
std::cout << "Error while parsing data." << std::endl;
delete timeLineParser;
timeLineParser = NULL;
return B_OK;
}
}
if(timeLineParser->count() < 1) {//timeLineParser failed, return!
std::cout << "Parser didn't find any tweets." << std::endl;
delete timeLineParser;
timeLineParser = NULL;
return B_OK;
}
HTGTweetItem *mostRecentItem = NULL;
HTTweet *mostRecentTweet = NULL;
HTTweet *currentTweet = NULL;
bool initialLoad = (listView->FirstItem() == NULL && super->unhandledList->FirstItem() == NULL);
if(!initialLoad && listView->FirstItem() != NULL) {
mostRecentItem = (HTGTweetItem *)listView->FirstItem();
mostRecentTweet = mostRecentItem->getTweetPtr();
currentTweet = timeLineParser->getTweets()[0];
/*If we are up to date: redraw, clean up and return*/
if(!(*mostRecentTweet < *currentTweet)) {
if(listView->LockLooper()) {
for(int i = 0; i < listView->CountItems(); i++) {
listView->InvalidateItem(i); //Update date
}
listView->UnlockLooper();
}
delete timeLineParser;
timeLineParser = NULL;
return B_OK;
}
}
/*Check to see if there is some unhandled tweets*/
if(!super->unhandledList->IsEmpty()) {
mostRecentItem = (HTGTweetItem *)super->unhandledList->FirstItem();
mostRecentTweet = mostRecentItem->getTweetPtr();
}
BList *newList = new BList();
for (int i = 0; i < timeLineParser->count(); i++) {
currentTweet = timeLineParser->getTweets()[i];
bool addItem = initialLoad;
if(!initialLoad) {
if(mostRecentTweet != NULL)
addItem = (*mostRecentTweet < *currentTweet);
else
addItem = true;
}
if(addItem) {
/*Make a copy, download bitmap and add it to newList*/
HTTweet *copiedTweet = new HTTweet(currentTweet);
copiedTweet->downloadBitmap();
newList->AddItem(new HTGTweetItem(copiedTweet));
if(!initialLoad && super->wantsNotifications) { //New tweet arrived, send notification
super->sendNotificationFor(copiedTweet);
}
}
else
break;
}
/*Try to lock listView*/
if(!listView->LockLooper()) {
/*Not active view: Copy tweetptrs to unhandledList and return*/
super->unhandledList->AddList(newList, 0); //Add new tweets to the top
super->waitingForUpdate = true;
delete timeLineParser;
timeLineParser = NULL;
if(newList->IsEmpty())
delete newList;
return B_OK;
}
/*Add the unhandled tweets to newList*/
newList->AddList(super->unhandledList);
super->unhandledList->MakeEmpty();
HTGTweetItem *currentItem;
while(!listView->IsEmpty()) {
currentItem = (HTGTweetItem *)listView->FirstItem();
currentTweet = currentItem->getTweetPtr();
listView->RemoveItem(currentItem); //Must lock looper before we do this!
if(newList->CountItems() < 20) //Only allow 20 tweets to be displayed at once... for now.
newList->AddItem(new HTGTweetItem(new HTTweet(currentTweet)));
delete currentItem;
}
/*Update the view*/
listView->AddList(newList); //Must lock looper before we do this!
/*Cleanup*/
super->waitingForUpdate = false;
listView->UnlockLooper();
delete timeLineParser;
timeLineParser = NULL;
delete newList;
return B_OK;
}
void HTGTimeLineView::sendNotificationFor(HTTweet *theTweet) {
std::string title("New tweet from ");
title.append(theTweet->getScreenName());
std::cout << title << std::endl;
#ifdef INFOPOPPER_SUPPORT
IPConnection *conn = new IPConnection;
IPMessage *msg = new IPMessage(InfoPopper::Information);
//Prepare the message
msg->Application("HaikuTwitter");
msg->Title(title.c_str());
msg->Content(theTweet->getText().c_str());
// Icon maybe in the future
/*if (strlen(fIconFile->Text()) > 0) {
entry_ref ref;
if (get_ref_for_path(fIconFile->Text(), &ref) == B_OK) {
if (fSelectedIconType == InfoPopper::Attribute) {
msg->MainIcon(ref);
msg->MainIconType(fSelectedIconType);
}
if (fSelectedIconType == InfoPopper::Contents) {
msg->OverlayIcon(ref);
msg->OverlayIconType(fSelectedIconType);
}
}
}*/
//Send the notification
conn->Send(msg);
delete msg;
delete conn;
#endif
}
bool HTGTimeLineView::_retrieveInfoPopperBoolFromSettings() {
BPath path;
infopopper_settings theSettings;
if (HTGInfoPopperSettingsWindow::_getSettingsPath(path) < B_OK) {
theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
switch(TYPE) {
case TIMELINE_FRIENDS:
return theSettings.friendsNotify;
break;
case TIMELINE_MENTIONS:
return theSettings.mentionsNotify;
break;
case TIMELINE_PUBLIC:
return theSettings.publicNotify;
break;
}
}
BFile file(path.Path(), B_READ_ONLY);
if (file.InitCheck() < B_OK) {
theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
switch(TYPE) {
case TIMELINE_FRIENDS:
return theSettings.friendsNotify;
break;
case TIMELINE_MENTIONS:
return theSettings.mentionsNotify;
break;
case TIMELINE_PUBLIC:
return theSettings.publicNotify;
break;
}
}
file.ReadAt(0, &theSettings, sizeof(infopopper_settings));
switch(TYPE) {
case TIMELINE_FRIENDS:
return theSettings.friendsNotify;
break;
case TIMELINE_MENTIONS:
return theSettings.mentionsNotify;
break;
case TIMELINE_PUBLIC:
return theSettings.publicNotify;
break;
}
return false; //Just in case nothing get's picked up... no compile error/warning without this though
}
HTGTimeLineView::~HTGTimeLineView() {
/*Kill the update thread*/
kill_thread(previousThread);
listView->RemoveSelf();
while(!listView->IsEmpty()) {
HTGTweetItem *currentItem = (HTGTweetItem *)listView->FirstItem();
listView->RemoveItem(currentItem);
delete currentItem;
}
delete listView;
delete twitObj;
theScrollView->RemoveSelf();
delete theScrollView;
}
<|endoftext|> |
<commit_before>#include <sstream>
#include <string>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <pybind11/stl.h>
#include <arbor/benchmark_cell.hpp>
#include <arbor/cable_cell.hpp>
#include <arbor/lif_cell.hpp>
#include <arbor/spike_source_cell.hpp>
#include <arbor/event_generator.hpp>
#include <arbor/morph/primitives.hpp>
#include <arbor/recipe.hpp>
#include "conversion.hpp"
#include "error.hpp"
#include "event_generator.hpp"
#include "strprintf.hpp"
#include "recipe.hpp"
namespace pyarb {
// Convert a cell description inside a Python object to a cell description in a
// unique_any, as required by the recipe interface.
// This helper is only to be called while holding the GIL. We require this guard
// across the lifetime of the description object `o`, since this function can be
// called without holding the GIL, ie from `simulation::init`, and `o` is a
// python object that can only be destroyed while holding the GIL. The fact that
// `cell_description` has a scoped GIL does not help with destruction as it
// happens outside that scope. `Description` needs to be extended in Python,
// inheriting from the pybind11 class.
static arb::util::unique_any convert_cell(pybind11::object o) {
using pybind11::isinstance;
using pybind11::cast;
if (isinstance<arb::spike_source_cell>(o)) {
return arb::util::unique_any(cast<arb::spike_source_cell>(o));
}
if (isinstance<arb::benchmark_cell>(o)) {
return arb::util::unique_any(cast<arb::benchmark_cell>(o));
}
if (isinstance<arb::lif_cell>(o)) {
return arb::util::unique_any(cast<arb::lif_cell>(o));
}
if (isinstance<arb::cable_cell>(o)) {
return arb::util::unique_any(cast<arb::cable_cell>(o));
}
throw pyarb_error("recipe.cell_description returned \""
+ std::string(pybind11::str(o))
+ "\" which does not describe a known Arbor cell type");
}
// The py::recipe::cell_decription returns a pybind11::object, that is
// unwrapped and copied into a arb::util::unique_any.
arb::util::unique_any py_recipe_shim::get_cell_description(arb::cell_gid_type gid) const {
return try_catch_pyexception([&](){
pybind11::gil_scoped_acquire guard;
return convert_cell(impl_->cell_description(gid));
},
"Python error already thrown");
}
// Convert global properties inside a Python object to a
// std::any, as required by the recipe interface.
// This helper is only to called while holding the GIL, see above.
static std::any convert_gprop(pybind11::object o) {
if (o.is(pybind11::none())) {
return {};
}
return pybind11::cast<arb::cable_cell_global_properties>(o);
}
// The py::recipe::global_properties returns a pybind11::object, that is
// unwrapped and copied into an std::any.
std::any py_recipe_shim::get_global_properties(arb::cell_kind kind) const {
return try_catch_pyexception([&](){
pybind11::gil_scoped_acquire guard;
return convert_gprop(impl_->global_properties(kind));
},
"Python error already thrown");
}
// This helper is only to called while holding the GIL, see above.
static std::vector<arb::event_generator> convert_gen(std::vector<pybind11::object> pygens, arb::cell_gid_type gid) {
using namespace std::string_literals;
using pybind11::isinstance;
using pybind11::cast;
std::vector<arb::event_generator> gens;
gens.reserve(pygens.size());
for (auto& g: pygens) {
// check that a valid Python event_generator was passed.
if (!isinstance<pyarb::event_generator_shim>(g)) {
throw pyarb_error(
util::pprintf(
"recipe supplied an invalid event generator for gid {}: {}", gid, pybind11::str(g)));
}
// get a reference to the python event_generator
auto& p = cast<const pyarb::event_generator_shim&>(g);
// convert the event_generator to an arb::event_generator
gens.push_back(arb::schedule_generator(p.target, p.weight, std::move(p.time_sched)));
}
return gens;
}
std::vector<arb::event_generator> py_recipe_shim::event_generators(arb::cell_gid_type gid) const {
return try_catch_pyexception([&](){
pybind11::gil_scoped_acquire guard;
return convert_gen(impl_->event_generators(gid), gid);
},
"Python error already thrown");
}
std::string con_to_string(const arb::cell_connection& c) {
return util::pprintf("<arbor.connection: source ({},{}), destination {}, delay {}, weight {}>",
c.source.gid, c.source.index, c.dest, c.delay, c.weight);
}
std::string gj_to_string(const arb::gap_junction_connection& gc) {
return util::pprintf("<arbor.gap_junction_connection: peer ({},{}), local {}, ggap {}>",
gc.peer.gid, gc.peer.index, gc.local, gc.ggap);
}
void register_recipe(pybind11::module& m) {
using namespace pybind11::literals;
// Connections
pybind11::class_<arb::cell_connection> cell_connection(m, "connection",
"Describes a connection between two cells:\n"
" Defined by source and destination end points (that is pre-synaptic and post-synaptic respectively), a connection weight and a delay time.");
cell_connection
.def(pybind11::init<arb::cell_member_type, arb::cell_lid_type, float, float>(),
"source"_a, "dest"_a, "weight"_a, "delay"_a,
"Construct a connection with arguments:\n"
" source: The source end point of the connection.\n"
" dest: The destination end point of the connection.\n"
" weight: The weight delivered to the target synapse (unit defined by the type of synapse target).\n"
" delay: The delay of the connection [ms].")
.def_readwrite("source", &arb::cell_connection::source,
"The source of the connection.")
.def_readwrite("dest", &arb::cell_connection::dest,
"The destination of the connection.")
.def_readwrite("weight", &arb::cell_connection::weight,
"The weight of the connection.")
.def_readwrite("delay", &arb::cell_connection::delay,
"The delay time of the connection [ms].")
.def("__str__", &con_to_string)
.def("__repr__", &con_to_string);
// Gap Junction Connections
pybind11::class_<arb::gap_junction_connection> gap_junction_connection(m, "gap_junction_connection",
"Describes a gap junction between two gap junction sites.");
gap_junction_connection
.def(pybind11::init<arb::cell_member_type, arb::cell_lid_type, double>(),
"local"_a, "peer"_a, "ggap"_a,
"Construct a gap junction connection with arguments:\n"
" local: One half of the gap junction connection.\n"
" peer: Other half of the gap junction connection.\n"
" ggap: Gap junction conductance [μS].")
.def_readwrite("local", &arb::gap_junction_connection::local,
"One half of the gap junction connection.")
.def_readwrite("peer", &arb::gap_junction_connection::peer,
"Other half of the gap junction connection.")
.def_readwrite("ggap", &arb::gap_junction_connection::ggap,
"Gap junction conductance [μS].")
.def("__str__", &gj_to_string)
.def("__repr__", &gj_to_string);
// Recipes
pybind11::class_<py_recipe,
py_recipe_trampoline,
std::shared_ptr<py_recipe>>
recipe(m, "recipe", pybind11::dynamic_attr(),
"A description of a model, describing the cells and the network via a cell-centric interface.");
recipe
.def(pybind11::init<>())
.def("num_cells", &py_recipe::num_cells, "The number of cells in the model.")
.def("cell_description", &py_recipe::cell_description, pybind11::return_value_policy::copy,
"gid"_a,
"High level description of the cell with global identifier gid.")
.def("cell_kind", &py_recipe::cell_kind,
"gid"_a,
"The kind of cell with global identifier gid.")
.def("num_sources", &py_recipe::num_sources,
"gid"_a,
"The number of spike sources on gid, 0 by default.")
.def("num_targets", &py_recipe::num_targets,
"gid"_a,
"The number of post-synaptic sites on gid, 0 by default.")
.def("num_gap_junction_sites", &py_recipe::num_gap_junction_sites,
"gid"_a,
"The number of gap junction sites on gid, 0 by default.")
.def("event_generators", &py_recipe::event_generators,
"gid"_a,
"A list of all the event generators that are attached to gid, [] by default.")
.def("connections_on", &py_recipe::connections_on,
"gid"_a,
"A list of all the incoming connections to gid, [] by default.")
.def("gap_junctions_on", &py_recipe::gap_junctions_on,
"gid"_a,
"A list of the gap junctions connected to gid, [] by default.")
.def("probes", &py_recipe::probes,
"gid"_a,
"The probes to allow monitoring.")
.def("global_properties", &py_recipe::global_properties,
"kind"_a,
"The default properties applied to all cells of type 'kind' in the model.")
// TODO: py_recipe::global_properties
.def("__str__", [](const py_recipe&){return "<arbor.recipe>";})
.def("__repr__", [](const py_recipe&){return "<arbor.recipe>";});
// Probes
pybind11::class_<arb::probe_info> probe(m, "probe");
probe
.def("__repr__", [](const arb::probe_info& p){return util::pprintf("<arbor.probe: tag {}>", p.tag);})
.def("__str__", [](const arb::probe_info& p){return util::pprintf("<arbor.probe: tag {}>", p.tag);});
}
} // namespace pyarb
<commit_msg>Fix gj python constructor (#1485)<commit_after>#include <sstream>
#include <string>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <pybind11/stl.h>
#include <arbor/benchmark_cell.hpp>
#include <arbor/cable_cell.hpp>
#include <arbor/lif_cell.hpp>
#include <arbor/spike_source_cell.hpp>
#include <arbor/event_generator.hpp>
#include <arbor/morph/primitives.hpp>
#include <arbor/recipe.hpp>
#include "conversion.hpp"
#include "error.hpp"
#include "event_generator.hpp"
#include "strprintf.hpp"
#include "recipe.hpp"
namespace pyarb {
// Convert a cell description inside a Python object to a cell description in a
// unique_any, as required by the recipe interface.
// This helper is only to be called while holding the GIL. We require this guard
// across the lifetime of the description object `o`, since this function can be
// called without holding the GIL, ie from `simulation::init`, and `o` is a
// python object that can only be destroyed while holding the GIL. The fact that
// `cell_description` has a scoped GIL does not help with destruction as it
// happens outside that scope. `Description` needs to be extended in Python,
// inheriting from the pybind11 class.
static arb::util::unique_any convert_cell(pybind11::object o) {
using pybind11::isinstance;
using pybind11::cast;
if (isinstance<arb::spike_source_cell>(o)) {
return arb::util::unique_any(cast<arb::spike_source_cell>(o));
}
if (isinstance<arb::benchmark_cell>(o)) {
return arb::util::unique_any(cast<arb::benchmark_cell>(o));
}
if (isinstance<arb::lif_cell>(o)) {
return arb::util::unique_any(cast<arb::lif_cell>(o));
}
if (isinstance<arb::cable_cell>(o)) {
return arb::util::unique_any(cast<arb::cable_cell>(o));
}
throw pyarb_error("recipe.cell_description returned \""
+ std::string(pybind11::str(o))
+ "\" which does not describe a known Arbor cell type");
}
// The py::recipe::cell_decription returns a pybind11::object, that is
// unwrapped and copied into a arb::util::unique_any.
arb::util::unique_any py_recipe_shim::get_cell_description(arb::cell_gid_type gid) const {
return try_catch_pyexception([&](){
pybind11::gil_scoped_acquire guard;
return convert_cell(impl_->cell_description(gid));
},
"Python error already thrown");
}
// Convert global properties inside a Python object to a
// std::any, as required by the recipe interface.
// This helper is only to called while holding the GIL, see above.
static std::any convert_gprop(pybind11::object o) {
if (o.is(pybind11::none())) {
return {};
}
return pybind11::cast<arb::cable_cell_global_properties>(o);
}
// The py::recipe::global_properties returns a pybind11::object, that is
// unwrapped and copied into an std::any.
std::any py_recipe_shim::get_global_properties(arb::cell_kind kind) const {
return try_catch_pyexception([&](){
pybind11::gil_scoped_acquire guard;
return convert_gprop(impl_->global_properties(kind));
},
"Python error already thrown");
}
// This helper is only to called while holding the GIL, see above.
static std::vector<arb::event_generator> convert_gen(std::vector<pybind11::object> pygens, arb::cell_gid_type gid) {
using namespace std::string_literals;
using pybind11::isinstance;
using pybind11::cast;
std::vector<arb::event_generator> gens;
gens.reserve(pygens.size());
for (auto& g: pygens) {
// check that a valid Python event_generator was passed.
if (!isinstance<pyarb::event_generator_shim>(g)) {
throw pyarb_error(
util::pprintf(
"recipe supplied an invalid event generator for gid {}: {}", gid, pybind11::str(g)));
}
// get a reference to the python event_generator
auto& p = cast<const pyarb::event_generator_shim&>(g);
// convert the event_generator to an arb::event_generator
gens.push_back(arb::schedule_generator(p.target, p.weight, std::move(p.time_sched)));
}
return gens;
}
std::vector<arb::event_generator> py_recipe_shim::event_generators(arb::cell_gid_type gid) const {
return try_catch_pyexception([&](){
pybind11::gil_scoped_acquire guard;
return convert_gen(impl_->event_generators(gid), gid);
},
"Python error already thrown");
}
std::string con_to_string(const arb::cell_connection& c) {
return util::pprintf("<arbor.connection: source ({},{}), destination {}, delay {}, weight {}>",
c.source.gid, c.source.index, c.dest, c.delay, c.weight);
}
std::string gj_to_string(const arb::gap_junction_connection& gc) {
return util::pprintf("<arbor.gap_junction_connection: peer ({},{}), local {}, ggap {}>",
gc.peer.gid, gc.peer.index, gc.local, gc.ggap);
}
void register_recipe(pybind11::module& m) {
using namespace pybind11::literals;
// Connections
pybind11::class_<arb::cell_connection> cell_connection(m, "connection",
"Describes a connection between two cells:\n"
" Defined by source and destination end points (that is pre-synaptic and post-synaptic respectively), a connection weight and a delay time.");
cell_connection
.def(pybind11::init<arb::cell_member_type, arb::cell_lid_type, float, float>(),
"source"_a, "dest"_a, "weight"_a, "delay"_a,
"Construct a connection with arguments:\n"
" source: The source end point of the connection.\n"
" dest: The destination end point of the connection.\n"
" weight: The weight delivered to the target synapse (unit defined by the type of synapse target).\n"
" delay: The delay of the connection [ms].")
.def_readwrite("source", &arb::cell_connection::source,
"The source of the connection.")
.def_readwrite("dest", &arb::cell_connection::dest,
"The destination of the connection.")
.def_readwrite("weight", &arb::cell_connection::weight,
"The weight of the connection.")
.def_readwrite("delay", &arb::cell_connection::delay,
"The delay time of the connection [ms].")
.def("__str__", &con_to_string)
.def("__repr__", &con_to_string);
// Gap Junction Connections
pybind11::class_<arb::gap_junction_connection> gap_junction_connection(m, "gap_junction_connection",
"Describes a gap junction between two gap junction sites.");
gap_junction_connection
.def(pybind11::init<arb::cell_member_type, arb::cell_lid_type, double>(),
"peer"_a, "local"_a, "ggap"_a,
"Construct a gap junction connection with arguments:\n"
" peer: One half of the gap junction connection.\n"
" local: Other half of the gap junction connection.\n"
" ggap: Gap junction conductance [μS].")
.def_readwrite("peer", &arb::gap_junction_connection::peer,
"Peer half of the gap junction connection.")
.def_readwrite("local", &arb::gap_junction_connection::local,
"Local half of the gap junction connection.")
.def_readwrite("ggap", &arb::gap_junction_connection::ggap,
"Gap junction conductance [μS].")
.def("__str__", &gj_to_string)
.def("__repr__", &gj_to_string);
// Recipes
pybind11::class_<py_recipe,
py_recipe_trampoline,
std::shared_ptr<py_recipe>>
recipe(m, "recipe", pybind11::dynamic_attr(),
"A description of a model, describing the cells and the network via a cell-centric interface.");
recipe
.def(pybind11::init<>())
.def("num_cells", &py_recipe::num_cells, "The number of cells in the model.")
.def("cell_description", &py_recipe::cell_description, pybind11::return_value_policy::copy,
"gid"_a,
"High level description of the cell with global identifier gid.")
.def("cell_kind", &py_recipe::cell_kind,
"gid"_a,
"The kind of cell with global identifier gid.")
.def("num_sources", &py_recipe::num_sources,
"gid"_a,
"The number of spike sources on gid, 0 by default.")
.def("num_targets", &py_recipe::num_targets,
"gid"_a,
"The number of post-synaptic sites on gid, 0 by default.")
.def("num_gap_junction_sites", &py_recipe::num_gap_junction_sites,
"gid"_a,
"The number of gap junction sites on gid, 0 by default.")
.def("event_generators", &py_recipe::event_generators,
"gid"_a,
"A list of all the event generators that are attached to gid, [] by default.")
.def("connections_on", &py_recipe::connections_on,
"gid"_a,
"A list of all the incoming connections to gid, [] by default.")
.def("gap_junctions_on", &py_recipe::gap_junctions_on,
"gid"_a,
"A list of the gap junctions connected to gid, [] by default.")
.def("probes", &py_recipe::probes,
"gid"_a,
"The probes to allow monitoring.")
.def("global_properties", &py_recipe::global_properties,
"kind"_a,
"The default properties applied to all cells of type 'kind' in the model.")
// TODO: py_recipe::global_properties
.def("__str__", [](const py_recipe&){return "<arbor.recipe>";})
.def("__repr__", [](const py_recipe&){return "<arbor.recipe>";});
// Probes
pybind11::class_<arb::probe_info> probe(m, "probe");
probe
.def("__repr__", [](const arb::probe_info& p){return util::pprintf("<arbor.probe: tag {}>", p.tag);})
.def("__str__", [](const arb::probe_info& p){return util::pprintf("<arbor.probe: tag {}>", p.tag);});
}
} // namespace pyarb
<|endoftext|> |
<commit_before>#include "enumType.h"
#include <qrutils/outFile.h>
#include "nameNormalizer.h"
bool EnumType::init(QDomElement const &element, QString const &context)
{
if (!NonGraphicType::init(element, context)) {
return false;
}
for (QDomElement valueElement = element.firstChildElement("value")
; !valueElement.isNull()
; valueElement = valueElement.nextSiblingElement("value"))
{
QString const name = valueElement.attribute("name");
QString displayedName = valueElement.attribute("displayedName");
if (displayedName.isEmpty()) {
displayedName = name;
}
mValues[name] = displayedName;
}
return true;
}
Type* EnumType::clone() const
{
EnumType *result = new EnumType();
Type::copyFields(result);
result->mValues = mValues;
return result;
}
bool EnumType::generateEnumValues(utils::OutFile &out, bool isNotFirst)
{
if (mValues.isEmpty()) {
return false;
}
generateOneCase(out, isNotFirst);
out() << "\t\treturn { ";
QStringList pairs;
for (QString const &name : mValues.keys()) {
pairs << QString("qMakePair(QString(\"%1\"), tr(\"%2\"))").arg(name, mValues[name]);
}
out() << pairs.join(", ");
out() << " };\n";
return true;
}
void EnumType::generateOneCase(utils::OutFile &out, bool isNotFirst) const
{
//QString name = NameNormalizer::normalize(qualifiedName());
if (!isNotFirst) {
out() << "\tif (name == \"" << NameNormalizer::normalize(name()) << "\")\n";
} else {
out() << "\telse if (name == \"" << NameNormalizer::normalize(name()) << "\")\n";
}
}
void EnumType::generatePropertyTypes(utils::OutFile &out)
{
Q_UNUSED(out);
}
void EnumType::generatePropertyDefaults(utils::OutFile &out)
{
Q_UNUSED(out);
}
void EnumType::generateMouseGesturesMap(utils::OutFile &out)
{
Q_UNUSED(out);
}
void EnumType::generateExplosionsMap(utils::OutFile &out)
{
Q_UNUSED(out)
}
<commit_msg>First attemp to repair build<commit_after>#include "enumType.h"
#include <QtCore/QStringList>
#include <qrutils/outFile.h>
#include "nameNormalizer.h"
bool EnumType::init(QDomElement const &element, QString const &context)
{
if (!NonGraphicType::init(element, context)) {
return false;
}
for (QDomElement valueElement = element.firstChildElement("value")
; !valueElement.isNull()
; valueElement = valueElement.nextSiblingElement("value"))
{
QString const name = valueElement.attribute("name");
QString displayedName = valueElement.attribute("displayedName");
if (displayedName.isEmpty()) {
displayedName = name;
}
mValues[name] = displayedName;
}
return true;
}
Type* EnumType::clone() const
{
EnumType *result = new EnumType();
Type::copyFields(result);
result->mValues = mValues;
return result;
}
bool EnumType::generateEnumValues(utils::OutFile &out, bool isNotFirst)
{
if (mValues.isEmpty()) {
return false;
}
generateOneCase(out, isNotFirst);
out() << "\t\treturn { ";
QStringList pairs;
for (QString const &name : mValues.keys()) {
pairs << QString("qMakePair(QString(\"%1\"), tr(\"%2\"))").arg(name, mValues[name]);
}
out() << pairs.join(", ");
out() << " };\n";
return true;
}
void EnumType::generateOneCase(utils::OutFile &out, bool isNotFirst) const
{
//QString name = NameNormalizer::normalize(qualifiedName());
if (!isNotFirst) {
out() << "\tif (name == \"" << NameNormalizer::normalize(name()) << "\")\n";
} else {
out() << "\telse if (name == \"" << NameNormalizer::normalize(name()) << "\")\n";
}
}
void EnumType::generatePropertyTypes(utils::OutFile &out)
{
Q_UNUSED(out);
}
void EnumType::generatePropertyDefaults(utils::OutFile &out)
{
Q_UNUSED(out);
}
void EnumType::generateMouseGesturesMap(utils::OutFile &out)
{
Q_UNUSED(out);
}
void EnumType::generateExplosionsMap(utils::OutFile &out)
{
Q_UNUSED(out)
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.