text stringlengths 54 60.6k |
|---|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include <QtGui/private/qt_x11_p.h>
#include <QtGui/private/qegl_p.h>
#include <QtGui/private/qeglproperties_p.h>
#include <QtGui/private/qeglcontext_p.h>
#if !defined(QT_OPENGL_ES_1)
#include <QtOpenGL/private/qpaintengineex_opengl2_p.h>
#endif
#ifndef QT_OPENGL_ES_2
#include <QtOpenGL/private/qpaintengine_opengl_p.h>
#endif
#include <QtOpenGL/private/qgl_p.h>
#include <QtOpenGL/private/qgl_egl_p.h>
#include "qpixmapdata_x11gl_p.h"
QT_BEGIN_NAMESPACE
class QX11GLSharedContexts
{
public:
QX11GLSharedContexts()
: rgbContext(0)
, argbContext(0)
, sharedQGLContext(0)
, sharePixmap(0)
{
EGLint rgbConfigId;
EGLint argbConfigId;
do {
EGLConfig rgbConfig = QEgl::defaultConfig(QInternal::Pixmap, QEgl::OpenGL, QEgl::Renderable);
EGLConfig argbConfig = QEgl::defaultConfig(QInternal::Pixmap, QEgl::OpenGL,
QEgl::Renderable | QEgl::Translucent);
eglGetConfigAttrib(QEgl::display(), rgbConfig, EGL_CONFIG_ID, &rgbConfigId);
eglGetConfigAttrib(QEgl::display(), argbConfig, EGL_CONFIG_ID, &argbConfigId);
rgbContext = new QEglContext;
rgbContext->setConfig(rgbConfig);
rgbContext->createContext();
if (!rgbContext->isValid())
break;
// If the RGB & ARGB configs are the same, use the same egl context for both:
if (rgbConfig == argbConfig)
argbContext = rgbContext;
// Otherwise, create a seperate context to be used for ARGB pixmaps:
if (!argbContext) {
argbContext = new QEglContext;
argbContext->setConfig(argbConfig);
bool success = argbContext->createContext(rgbContext);
if (!success) {
qWarning("QX11GLPixmapData - RGB & ARGB contexts aren't shared");
success = argbContext->createContext();
if (!success)
argbContext = rgbContext; // Might work, worth a shot at least.
}
}
if (!argbContext->isValid())
break;
// Create the pixmap which will be used to create the egl surface for the share QGLContext
QX11PixmapData *rgbPixmapData = new QX11PixmapData(QPixmapData::PixmapType);
rgbPixmapData->resize(8, 8);
rgbPixmapData->fill(Qt::red);
sharePixmap = new QPixmap(rgbPixmapData);
EGLSurface sharePixmapSurface = QEgl::createSurface(sharePixmap, rgbConfig);
rgbPixmapData->gl_surface = (void*)sharePixmapSurface;
// Create the actual QGLContext which will be used for sharing
sharedQGLContext = new QGLContext(QX11GLPixmapData::glFormat());
sharedQGLContext->d_func()->eglContext = rgbContext;
sharedQGLContext->d_func()->eglSurface = sharePixmapSurface;
sharedQGLContext->d_func()->valid = true;
qt_glformat_from_eglconfig(sharedQGLContext->d_func()->glFormat, rgbConfig);
valid = rgbContext->makeCurrent(sharePixmapSurface);
// If the ARGB & RGB configs are different, check ARGB works too:
if (argbConfig != rgbConfig) {
QX11PixmapData *argbPixmapData = new QX11PixmapData(QPixmapData::PixmapType);
argbPixmapData->resize(8, 8);
argbPixmapData->fill(Qt::transparent); // Force ARGB
QPixmap argbPixmap(argbPixmapData); // destroys pixmap data when goes out of scope
EGLSurface argbPixmapSurface = QEgl::createSurface(&argbPixmap, argbConfig);
valid = argbContext->makeCurrent(argbPixmapSurface);
argbContext->doneCurrent();
eglDestroySurface(QEgl::display(), argbPixmapSurface);
}
if (!valid) {
qWarning() << "Unable to make pixmap surface current:" << QEgl::errorString();
break;
}
// The pixmap surface destruction hooks are installed by QGLTextureCache, so we
// must make sure this is instanciated:
QGLTextureCache::instance();
} while(0);
if (!valid)
cleanup();
else
qDebug("Using QX11GLPixmapData with EGL config %d for ARGB and config %d for RGB", argbConfigId, rgbConfigId);
}
void cleanup() {
if (sharedQGLContext) {
delete sharedQGLContext;
sharedQGLContext = 0;
}
if (argbContext && argbContext != rgbContext)
delete argbContext;
argbContext = 0;
if (rgbContext) {
delete rgbContext;
rgbContext = 0;
}
// Deleting the QPixmap will fire the pixmap destruction cleanup hooks which in turn
// will destroy the egl surface:
if (sharePixmap) {
delete sharePixmap;
sharePixmap = 0;
}
}
bool isValid() { return valid;}
// On 16bpp systems, RGB & ARGB pixmaps are different bit-depths and therefore need
// different contexts:
QEglContext *rgbContext;
QEglContext *argbContext;
// The share context wraps the rgbContext and is used as the master of the context share
// group. As all other contexts will have the same egl context (or a shared one if rgb != argb)
// all QGLContexts will actually be sharing and can be in the same context group.
QGLContext *sharedQGLContext;
private:
QPixmap *sharePixmap;
bool valid;
};
static void qt_cleanup_x11gl_share_contexts();
Q_GLOBAL_STATIC_WITH_INITIALIZER(QX11GLSharedContexts, qt_x11gl_share_contexts,
{
qAddPostRoutine(qt_cleanup_x11gl_share_contexts);
})
static void qt_cleanup_x11gl_share_contexts()
{
qt_x11gl_share_contexts()->cleanup();
}
QX11GLSharedContexts* QX11GLPixmapData::sharedContexts()
{
return qt_x11gl_share_contexts();
}
bool QX11GLPixmapData::hasX11GLPixmaps()
{
static bool checkedForX11GLPixmaps = false;
static bool haveX11GLPixmaps = false;
if (checkedForX11GLPixmaps)
return haveX11GLPixmaps;
checkedForX11GLPixmaps = true;
haveX11GLPixmaps = sharedContexts()->isValid();
return haveX11GLPixmaps;
}
QX11GLPixmapData::QX11GLPixmapData()
: QX11PixmapData(QPixmapData::PixmapType),
ctx(0)
{
}
QX11GLPixmapData::~QX11GLPixmapData()
{
if (ctx)
delete ctx;
}
void QX11GLPixmapData::fill(const QColor &color)
{
if (ctx) {
ctx->makeCurrent();
glFinish();
eglWaitClient();
}
QX11PixmapData::fill(color);
XSync(X11->display, False);
if (ctx) {
ctx->makeCurrent();
eglWaitNative(EGL_CORE_NATIVE_ENGINE);
}
}
void QX11GLPixmapData::copy(const QPixmapData *data, const QRect &rect)
{
if (ctx) {
ctx->makeCurrent();
glFinish();
eglWaitClient();
}
QX11PixmapData::copy(data, rect);
XSync(X11->display, False);
if (ctx) {
ctx->makeCurrent();
eglWaitNative(EGL_CORE_NATIVE_ENGINE);
}
}
bool QX11GLPixmapData::scroll(int dx, int dy, const QRect &rect)
{
if (ctx) {
ctx->makeCurrent();
glFinish();
eglWaitClient();
}
bool success = QX11PixmapData::scroll(dx, dy, rect);
XSync(X11->display, False);
if (ctx) {
ctx->makeCurrent();
eglWaitNative(EGL_CORE_NATIVE_ENGINE);
}
return success;
}
#if !defined(QT_OPENGL_ES_1)
Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_pixmap_2_engine)
#endif
#ifndef QT_OPENGL_ES_2
Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_pixmap_engine)
#endif
QPaintEngine* QX11GLPixmapData::paintEngine() const
{
// We need to create the context before beginPaint - do it here:
if (!ctx) {
ctx = new QGLContext(glFormat());
Q_ASSERT(ctx->d_func()->eglContext == 0);
ctx->d_func()->eglContext = hasAlphaChannel() ? sharedContexts()->argbContext : sharedContexts()->rgbContext;
// While we use a seperate QGLContext for each pixmap, the underlying QEglContext is
// the same. So we must use a "fake" QGLContext and fool the texture cache into thinking
// each pixmap's QGLContext is sharing with this central one. The only place this is
// going to fail is where we the underlying EGL RGB and ARGB contexts aren't sharing.
ctx->d_func()->sharing = true;
QGLContextGroup::addShare(ctx, sharedContexts()->sharedQGLContext);
// Update the glFormat for the QGLContext:
qt_glformat_from_eglconfig(ctx->d_func()->glFormat, ctx->d_func()->eglContext->config());
}
QPaintEngine* engine;
#if defined(QT_OPENGL_ES_1)
engine = qt_gl_pixmap_engine();
#elif defined(QT_OPENGL_ES_2)
engine = qt_gl_pixmap_2_engine();
#else
if (qt_gl_preferGL2Engine())
engine = qt_gl_pixmap_2_engine();
else
engine = qt_gl_pixmap_engine();
#endif
// Support multiple painters on multiple pixmaps simultaniously
if (engine->isActive()) {
qWarning("Pixmap paint engine already active");
#if defined(QT_OPENGL_ES_1)
engine = new QOpenGLPaintEngine;
#elif defined(QT_OPENGL_ES_2)
engine = new QGL2PaintEngineEx;
#else
if (qt_gl_preferGL2Engine())
engine = new QGL2PaintEngineEx;
else
engine = new QOpenGLPaintEngine;
#endif
engine->setAutoDestruct(true);
return engine;
}
return engine;
}
void QX11GLPixmapData::beginPaint()
{
// qDebug("QX11GLPixmapData::beginPaint()");
// TODO: Check to see if the surface is renderable
if ((EGLSurface)gl_surface == EGL_NO_SURFACE) {
QPixmap tmpPixmap(this);
EGLConfig cfg = ctx->d_func()->eglContext->config();
Q_ASSERT(cfg != QEGL_NO_CONFIG);
// qDebug("QX11GLPixmapData - using EGL Config ID %d", ctx->d_func()->eglContext->configAttrib(EGL_CONFIG_ID));
EGLSurface surface = QEgl::createSurface(&tmpPixmap, cfg);
if (surface == EGL_NO_SURFACE) {
qWarning() << "Error creating EGL surface for pixmap:" << QEgl::errorString();
return;
}
gl_surface = (void*)surface;
ctx->d_func()->eglSurface = surface;
ctx->d_func()->valid = true;
}
QGLPaintDevice::beginPaint();
}
QGLContext* QX11GLPixmapData::context() const
{
return ctx;
}
QSize QX11GLPixmapData::size() const
{
return QSize(w, h);
}
QGLFormat QX11GLPixmapData::glFormat()
{
return QGLFormat::defaultFormat(); //###
}
QT_END_NAMESPACE
<commit_msg>Don't leak objects if QX11GLSharedContexts is instanciated twice<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include <QtGui/private/qt_x11_p.h>
#include <QtGui/private/qegl_p.h>
#include <QtGui/private/qeglproperties_p.h>
#include <QtGui/private/qeglcontext_p.h>
#if !defined(QT_OPENGL_ES_1)
#include <QtOpenGL/private/qpaintengineex_opengl2_p.h>
#endif
#ifndef QT_OPENGL_ES_2
#include <QtOpenGL/private/qpaintengine_opengl_p.h>
#endif
#include <QtOpenGL/private/qgl_p.h>
#include <QtOpenGL/private/qgl_egl_p.h>
#include "qpixmapdata_x11gl_p.h"
QT_BEGIN_NAMESPACE
class QX11GLSharedContexts
{
public:
QX11GLSharedContexts()
: rgbContext(0)
, argbContext(0)
, sharedQGLContext(0)
, sharePixmap(0)
{
EGLint rgbConfigId;
EGLint argbConfigId;
do {
EGLConfig rgbConfig = QEgl::defaultConfig(QInternal::Pixmap, QEgl::OpenGL, QEgl::Renderable);
EGLConfig argbConfig = QEgl::defaultConfig(QInternal::Pixmap, QEgl::OpenGL,
QEgl::Renderable | QEgl::Translucent);
eglGetConfigAttrib(QEgl::display(), rgbConfig, EGL_CONFIG_ID, &rgbConfigId);
eglGetConfigAttrib(QEgl::display(), argbConfig, EGL_CONFIG_ID, &argbConfigId);
rgbContext = new QEglContext;
rgbContext->setConfig(rgbConfig);
rgbContext->createContext();
if (!rgbContext->isValid())
break;
// If the RGB & ARGB configs are the same, use the same egl context for both:
if (rgbConfig == argbConfig)
argbContext = rgbContext;
// Otherwise, create a seperate context to be used for ARGB pixmaps:
if (!argbContext) {
argbContext = new QEglContext;
argbContext->setConfig(argbConfig);
bool success = argbContext->createContext(rgbContext);
if (!success) {
qWarning("QX11GLPixmapData - RGB & ARGB contexts aren't shared");
success = argbContext->createContext();
if (!success)
argbContext = rgbContext; // Might work, worth a shot at least.
}
}
if (!argbContext->isValid())
break;
// Create the pixmap which will be used to create the egl surface for the share QGLContext
QX11PixmapData *rgbPixmapData = new QX11PixmapData(QPixmapData::PixmapType);
rgbPixmapData->resize(8, 8);
rgbPixmapData->fill(Qt::red);
sharePixmap = new QPixmap(rgbPixmapData);
EGLSurface sharePixmapSurface = QEgl::createSurface(sharePixmap, rgbConfig);
rgbPixmapData->gl_surface = (void*)sharePixmapSurface;
// Create the actual QGLContext which will be used for sharing
sharedQGLContext = new QGLContext(QX11GLPixmapData::glFormat());
sharedQGLContext->d_func()->eglContext = rgbContext;
sharedQGLContext->d_func()->eglSurface = sharePixmapSurface;
sharedQGLContext->d_func()->valid = true;
qt_glformat_from_eglconfig(sharedQGLContext->d_func()->glFormat, rgbConfig);
valid = rgbContext->makeCurrent(sharePixmapSurface);
// If the ARGB & RGB configs are different, check ARGB works too:
if (argbConfig != rgbConfig) {
QX11PixmapData *argbPixmapData = new QX11PixmapData(QPixmapData::PixmapType);
argbPixmapData->resize(8, 8);
argbPixmapData->fill(Qt::transparent); // Force ARGB
QPixmap argbPixmap(argbPixmapData); // destroys pixmap data when goes out of scope
EGLSurface argbPixmapSurface = QEgl::createSurface(&argbPixmap, argbConfig);
valid = argbContext->makeCurrent(argbPixmapSurface);
argbContext->doneCurrent();
eglDestroySurface(QEgl::display(), argbPixmapSurface);
argbPixmapData->gl_surface = 0;
}
if (!valid) {
qWarning() << "Unable to make pixmap surface current:" << QEgl::errorString();
break;
}
// The pixmap surface destruction hooks are installed by QGLTextureCache, so we
// must make sure this is instanciated:
QGLTextureCache::instance();
} while(0);
if (!valid)
cleanup();
else
qDebug("Using QX11GLPixmapData with EGL config %d for ARGB and config %d for RGB", argbConfigId, rgbConfigId);
}
~QX11GLSharedContexts() {
cleanup();
}
void cleanup() {
if (sharedQGLContext) {
delete sharedQGLContext;
sharedQGLContext = 0;
}
if (argbContext && argbContext != rgbContext)
delete argbContext;
argbContext = 0;
if (rgbContext) {
delete rgbContext;
rgbContext = 0;
}
// Deleting the QPixmap will fire the pixmap destruction cleanup hooks which in turn
// will destroy the egl surface:
if (sharePixmap) {
delete sharePixmap;
sharePixmap = 0;
}
}
bool isValid() { return valid;}
// On 16bpp systems, RGB & ARGB pixmaps are different bit-depths and therefore need
// different contexts:
QEglContext *rgbContext;
QEglContext *argbContext;
// The share context wraps the rgbContext and is used as the master of the context share
// group. As all other contexts will have the same egl context (or a shared one if rgb != argb)
// all QGLContexts will actually be sharing and can be in the same context group.
QGLContext *sharedQGLContext;
private:
QPixmap *sharePixmap;
bool valid;
};
static void qt_cleanup_x11gl_share_contexts();
Q_GLOBAL_STATIC_WITH_INITIALIZER(QX11GLSharedContexts, qt_x11gl_share_contexts,
{
qAddPostRoutine(qt_cleanup_x11gl_share_contexts);
})
static void qt_cleanup_x11gl_share_contexts()
{
qt_x11gl_share_contexts()->cleanup();
}
QX11GLSharedContexts* QX11GLPixmapData::sharedContexts()
{
return qt_x11gl_share_contexts();
}
bool QX11GLPixmapData::hasX11GLPixmaps()
{
static bool checkedForX11GLPixmaps = false;
static bool haveX11GLPixmaps = false;
if (checkedForX11GLPixmaps)
return haveX11GLPixmaps;
haveX11GLPixmaps = qt_x11gl_share_contexts()->isValid();
checkedForX11GLPixmaps = true;
return haveX11GLPixmaps;
}
QX11GLPixmapData::QX11GLPixmapData()
: QX11PixmapData(QPixmapData::PixmapType),
ctx(0)
{
}
QX11GLPixmapData::~QX11GLPixmapData()
{
if (ctx)
delete ctx;
}
void QX11GLPixmapData::fill(const QColor &color)
{
if (ctx) {
ctx->makeCurrent();
glFinish();
eglWaitClient();
}
QX11PixmapData::fill(color);
XSync(X11->display, False);
if (ctx) {
ctx->makeCurrent();
eglWaitNative(EGL_CORE_NATIVE_ENGINE);
}
}
void QX11GLPixmapData::copy(const QPixmapData *data, const QRect &rect)
{
if (ctx) {
ctx->makeCurrent();
glFinish();
eglWaitClient();
}
QX11PixmapData::copy(data, rect);
XSync(X11->display, False);
if (ctx) {
ctx->makeCurrent();
eglWaitNative(EGL_CORE_NATIVE_ENGINE);
}
}
bool QX11GLPixmapData::scroll(int dx, int dy, const QRect &rect)
{
if (ctx) {
ctx->makeCurrent();
glFinish();
eglWaitClient();
}
bool success = QX11PixmapData::scroll(dx, dy, rect);
XSync(X11->display, False);
if (ctx) {
ctx->makeCurrent();
eglWaitNative(EGL_CORE_NATIVE_ENGINE);
}
return success;
}
#if !defined(QT_OPENGL_ES_1)
Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_pixmap_2_engine)
#endif
#ifndef QT_OPENGL_ES_2
Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_pixmap_engine)
#endif
QPaintEngine* QX11GLPixmapData::paintEngine() const
{
// We need to create the context before beginPaint - do it here:
if (!ctx) {
ctx = new QGLContext(glFormat());
Q_ASSERT(ctx->d_func()->eglContext == 0);
ctx->d_func()->eglContext = hasAlphaChannel() ? sharedContexts()->argbContext : sharedContexts()->rgbContext;
// While we use a seperate QGLContext for each pixmap, the underlying QEglContext is
// the same. So we must use a "fake" QGLContext and fool the texture cache into thinking
// each pixmap's QGLContext is sharing with this central one. The only place this is
// going to fail is where we the underlying EGL RGB and ARGB contexts aren't sharing.
ctx->d_func()->sharing = true;
QGLContextGroup::addShare(ctx, sharedContexts()->sharedQGLContext);
// Update the glFormat for the QGLContext:
qt_glformat_from_eglconfig(ctx->d_func()->glFormat, ctx->d_func()->eglContext->config());
}
QPaintEngine* engine;
#if defined(QT_OPENGL_ES_1)
engine = qt_gl_pixmap_engine();
#elif defined(QT_OPENGL_ES_2)
engine = qt_gl_pixmap_2_engine();
#else
if (qt_gl_preferGL2Engine())
engine = qt_gl_pixmap_2_engine();
else
engine = qt_gl_pixmap_engine();
#endif
// Support multiple painters on multiple pixmaps simultaniously
if (engine->isActive()) {
qWarning("Pixmap paint engine already active");
#if defined(QT_OPENGL_ES_1)
engine = new QOpenGLPaintEngine;
#elif defined(QT_OPENGL_ES_2)
engine = new QGL2PaintEngineEx;
#else
if (qt_gl_preferGL2Engine())
engine = new QGL2PaintEngineEx;
else
engine = new QOpenGLPaintEngine;
#endif
engine->setAutoDestruct(true);
return engine;
}
return engine;
}
void QX11GLPixmapData::beginPaint()
{
// qDebug("QX11GLPixmapData::beginPaint()");
// TODO: Check to see if the surface is renderable
if ((EGLSurface)gl_surface == EGL_NO_SURFACE) {
QPixmap tmpPixmap(this);
EGLConfig cfg = ctx->d_func()->eglContext->config();
Q_ASSERT(cfg != QEGL_NO_CONFIG);
// qDebug("QX11GLPixmapData - using EGL Config ID %d", ctx->d_func()->eglContext->configAttrib(EGL_CONFIG_ID));
EGLSurface surface = QEgl::createSurface(&tmpPixmap, cfg);
if (surface == EGL_NO_SURFACE) {
qWarning() << "Error creating EGL surface for pixmap:" << QEgl::errorString();
return;
}
gl_surface = (void*)surface;
ctx->d_func()->eglSurface = surface;
ctx->d_func()->valid = true;
}
QGLPaintDevice::beginPaint();
}
QGLContext* QX11GLPixmapData::context() const
{
return ctx;
}
QSize QX11GLPixmapData::size() const
{
return QSize(w, h);
}
QGLFormat QX11GLPixmapData::glFormat()
{
return QGLFormat::defaultFormat(); //###
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#ifndef __ENVIRE_MAPS_GRIDINTERPOLATION_HPP__
#define __ENVIRE_MAPS_GRIDINTERPOLATION_HPP__
#include "../GridMap.hpp"
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Triangulation_euclidean_traits_xy_3.h>
#include <CGAL/Delaunay_triangulation_2.h>
namespace envire {
namespace maps
{
class GridInterpolation
{
public:
GridInterpolation() {};
~GridInterpolation() {};
/**
* @brief [brief description]
* @details nore only for doubles
* (cell_value = Vector3d(x,y,1).dot( A.inverse() * b );)
* uncertanty for integral types
*
* @param grid [description]
*/
template <class T,
class = typename std::enable_if<std::is_arithmetic<T>::value>::type>
static void interpolate(GridMap<T> &grid)
{
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Triangulation_euclidean_traits_xy_3<K> Gt;
typedef CGAL::Delaunay_triangulation_2<Gt> Delaunay;
typedef K::Point_3 Point;
Delaunay dt;
size_t min_width = grid.getNumCells().x() - 1;
size_t max_width = 0;
size_t min_height = grid.getNumCells().y() - 1;
size_t max_height = 0;
T default_value = grid.getDefaultValue();
for(size_t y = 0; y < grid.getNumCells().y(); ++y)
{
for(size_t x = 0; x < grid.getNumCells().x(); ++x)
{
T const &cell_value = grid.at(x, y);
if(cell_value != default_value )
{
Point p(x, y, cell_value);
dt.insert( p );
min_width = std::min(min_width, x);
max_width = std::max(max_width, x);
min_height = std::min(min_height, y);
max_height = std::max(max_height, y);
}
}
}
for(size_t x = min_width; x < max_width; x++)
{
for(size_t y = min_height; y < max_height; y++)
{
T &cell_value = grid.at(x, y);
if(cell_value == default_value)
{
// no data point in grid, so value needs to be interpolated
// Solve linear equation system to find plane that is spanned by
// the three points
Eigen::Matrix3d A;
Eigen::Vector3d b;
Delaunay::Face_handle face = dt.locate(Point(x, y, 0));
if( face == NULL || face->vertex(0) == NULL
|| face->vertex(1) == NULL || face->vertex(2) == NULL)
continue;
for(int i = 0; i < 3; i++)
{
Point &p(face->vertex(i)->point());
A.block<1,3>(i,0) = Vector3d(p.x(), p.y(), 1);
b(i) = p.z();
}
// evaluate the point at x, y
cell_value = Vector3d(x,y,1).dot( A.inverse() * b );
}
}
}
}
private:
};
}
}
#endif // __ENVIRE_MAPS_GRIDINTERPOLATION_HPP__<commit_msg>replace the deprecated function of CGAL in GridInterpolation<commit_after>#ifndef __ENVIRE_MAPS_GRIDINTERPOLATION_HPP__
#define __ENVIRE_MAPS_GRIDINTERPOLATION_HPP__
#include "../GridMap.hpp"
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Projection_traits_xy_3.h>
#include <CGAL/Delaunay_triangulation_2.h>
namespace envire {
namespace maps
{
class GridInterpolation
{
public:
GridInterpolation() {};
~GridInterpolation() {};
/**
* @brief [brief description]
* @details nore only for doubles
* (cell_value = Vector3d(x,y,1).dot( A.inverse() * b );)
* uncertanty for integral types
*
* @param grid [description]
*/
template <class T,
class = typename std::enable_if<std::is_arithmetic<T>::value>::type>
static void interpolate(GridMap<T> &grid)
{
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Projection_traits_xy_3<K> Gt;
typedef CGAL::Delaunay_triangulation_2<Gt> Delaunay;
typedef K::Point_3 Point;
Delaunay dt;
size_t min_width = grid.getNumCells().x() - 1;
size_t max_width = 0;
size_t min_height = grid.getNumCells().y() - 1;
size_t max_height = 0;
T default_value = grid.getDefaultValue();
for(size_t y = 0; y < grid.getNumCells().y(); ++y)
{
for(size_t x = 0; x < grid.getNumCells().x(); ++x)
{
T const &cell_value = grid.at(x, y);
if(cell_value != default_value )
{
Point p(x, y, cell_value);
dt.insert( p );
min_width = std::min(min_width, x);
max_width = std::max(max_width, x);
min_height = std::min(min_height, y);
max_height = std::max(max_height, y);
}
}
}
for(size_t x = min_width; x < max_width; x++)
{
for(size_t y = min_height; y < max_height; y++)
{
T &cell_value = grid.at(x, y);
if(cell_value == default_value)
{
// no data point in grid, so value needs to be interpolated
// Solve linear equation system to find plane that is spanned by
// the three points
Eigen::Matrix3d A;
Eigen::Vector3d b;
Delaunay::Face_handle face = dt.locate(Point(x, y, 0));
if( face == NULL || face->vertex(0) == NULL
|| face->vertex(1) == NULL || face->vertex(2) == NULL)
continue;
for(int i = 0; i < 3; i++)
{
Point &p(face->vertex(i)->point());
A.block<1,3>(i,0) = Vector3d(p.x(), p.y(), 1);
b(i) = p.z();
}
// evaluate the point at x, y
cell_value = Vector3d(x,y,1).dot( A.inverse() * b );
}
}
}
}
private:
};
}
}
#endif // __ENVIRE_MAPS_GRIDINTERPOLATION_HPP__<|endoftext|> |
<commit_before>#ifndef GRAPH_HPP
#define GRAPH_HPP
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
#include "utility.h"
template<class T>
class graph_t {
private:
int num_nodes;
public:
std::unordered_map<int, std::vector<int>* > edges;
std::unordered_map<int, T> node_data;
std::unordered_map<std::pair<int, int>, T> edge_data;
graph_t() : num_nodes(0) {}
~graph_t(){
}
int get_num_nodes(){
return num_nodes;
}
int add_vertex(){
return num_nodes++;
}
std::pair<int,int> add_edge(int from, int to){
if(edges.find(from) != edges.end()){ // if from exists in edges
std::vector<int> *vect = edges[from];
(*vect).push_back(to);
}
else {
std::vector<int> *vect = new std::vector<int>();
(*vect).push_back(to);
edges.insert(std::make_pair(from, vect));
}
return std::make_pair(from, to);
}
};
#endif
<commit_msg>print edges is added.<commit_after>#ifndef GRAPH_HPP
#define GRAPH_HPP
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
#include "utility.h"
template<class T>
class graph_t {
private:
int num_nodes;
public:
std::unordered_map<int, std::vector<int>* > edges;
std::unordered_map<int, T> node_data;
std::unordered_map<std::pair<int, int>, T> edge_data;
graph_t() : num_nodes(0) {}
~graph_t(){
}
int get_num_nodes(){
return num_nodes;
}
int add_vertex(){
return num_nodes++;
}
std::pair<int,int> add_edge(int from, int to){
if(edges.find(from) != edges.end()){ // if from exists in edges
std::vector<int> *vect = edges[from];
(*vect).push_back(to);
}
else {
std::vector<int> *vect = new std::vector<int>();
(*vect).push_back(to);
edges.insert(std::make_pair(from, vect));
}
return std::make_pair(from, to);
}
void print_edges(){
//print all edges of all vertices
for(auto it = (*this).edges.begin(); it != (*this).edges.end(); ++it){
std::cout << "Edges of node " << (*it).first << " :" << std::endl;
for(auto it2 = it->second->begin(); it2 != it->second->end(); ++it2){
std::cout << "\t" << (*it).first << " -> " << *it2 << std::endl;
}
std::cout << std::endl;
}
}
void print_edges(int n){
//print edges of node n
if(edges.find(n) != edges.end()){
std::cout << "Edges of node " << n << " :" << std::endl;
for(auto it2 = edges[n]->second->begin(); it2 != edges[n]->second->end(); ++it2){
std::cout << "\t" << n << " -> " << *it2 << std::endl;
}
std::cout << std::endl;
}
else std::cout << "Node " << n << " has no edges." << std::endl;
}
};
#endif
<|endoftext|> |
<commit_before>#include "buildin.h"
#include "memory.h"
#include "vm.h"
BUILD_FUNC_SIGN(print)
{
if(argc)fputs(GET_ARGV(0).toString().c_str(),stdout);
for(int i=1;i<argc;i++)fprintf(stdout," %s",GET_ARGV(i).toString().c_str());
}
BUILD_FUNC_SIGN(println)
{
GET_BUILDIN_FUNC_NAME(print)(argc,vm);
putchar('\n');
}
BUILD_FUNC_SIGN(scani)
{
vm.reg_ret.type=T_INT;
scanf("%d",&vm.reg_ret.v_int);
}
BUILD_FUNC_SIGN(scanf)
{
vm.reg_ret.type=T_FLOAT;
scanf("%lf",&vm.reg_ret.v_float);
}
BUILD_FUNC_SIGN(scans)
{
char s[1000];
vm.reg_ret.type=T_STRING;
scanf("%s",s);
vm.reg_ret.v_string=newString();
*vm.reg_ret.v_string=s;
}
BUILD_FUNC_SIGN(exit)
{
vm.next_ip=0x7fffffff;
}
BUILD_FUNC_SIGN(len)
{
vm.reg_ret.type=T_INT;
switch(GET_ARGV(0).type)
{
case T_ARRAY:
vm.reg_ret.v_int=GET_ARGV(0).v_array->size();
break;
case T_OBJECT:
vm.reg_ret.v_int=GET_ARGV(0).v_object->size();
break;
default:
vm.reg_ret.v_int=1;
}
}
BUILD_FUNC_SIGN(push)
{
if(GET_ARGV(0).type!=T_ARRAY)return;
for(int i=1;i<argc;i++)GET_ARGV(0).v_array->push_back(GET_ARGV(i));
vm.reg_ret=GET_ARGV(0);
}
BUILD_FUNC_SIGN(clear)
{
if(GET_ARGV(0).type==T_ARRAY)GET_ARGV(0).v_array->clear();
else if(GET_ARGV(0).type==T_OBJECT)GET_ARGV(0).v_object->clear();
else return;
vm.reg_ret=GET_ARGV(0);
}
BUILD_FUNC_SIGN(resize)
{
if(GET_ARGV(0).type!=T_ARRAY)return;
GET_ARGV(0).v_array->resize(GET_ARGV(2));
vm.reg_ret=GET_ARGV(0);
}
BUILD_FUNC_SIGN(get_keys)
{
vm.reg_ret.type=T_ARRAY;
vm.reg_ret.v_array=newArray();
if(GET_ARGV(0).type==T_OBJECT)
{
int i=0;
vm.reg_ret.v_array->resize(GET_ARGV(0).v_object->size());
for(auto &x:*GET_ARGV(0).v_object)
{
(*vm.reg_ret.v_array)[i].type=T_STRING;
(*vm.reg_ret.v_array)[i].v_string=newString();
*(*vm.reg_ret.v_array)[i].v_string=x.first;
i++;
}
}
else if(GET_ARGV(0).type==T_ARRAY)
{
int size=GET_ARGV(0).v_array->size();
vm.reg_ret.v_array->resize(size);
for(int i=0;i<size;i++)
{
(*vm.reg_ret.v_array)[i].type=T_INT;
(*vm.reg_ret.v_array)[i].v_int=i;
}
}
}
BUILD_FUNC_SIGN(gc)
{
gc();
}
BUILD_FUNC_SIGN(each)
{
auto &v=vm.v_stack.top();
auto &f=vm.v_stack.top(1);
if(v.type==T_ARRAY)
{
for(int i=0;i<v.v_array->size();i++)
{
vm.push(f);
vm.push((*v.v_array)[i]);
vm.push(i);
vm.callReturn(2);
}
}
else if(v.type==T_OBJECT)
{
for(auto &x:*v.v_object)
{
vm.push(f);
vm.push(x.first);
vm.push(x.second);
vm.callReturn(2);
}
}
}
<commit_msg>system.len('string')<commit_after>#include "buildin.h"
#include "memory.h"
#include "vm.h"
BUILD_FUNC_SIGN(print)
{
if(argc)fputs(GET_ARGV(0).toString().c_str(),stdout);
for(int i=1;i<argc;i++)fprintf(stdout," %s",GET_ARGV(i).toString().c_str());
}
BUILD_FUNC_SIGN(println)
{
GET_BUILDIN_FUNC_NAME(print)(argc,vm);
putchar('\n');
}
BUILD_FUNC_SIGN(scani)
{
vm.reg_ret.type=T_INT;
scanf("%d",&vm.reg_ret.v_int);
}
BUILD_FUNC_SIGN(scanf)
{
vm.reg_ret.type=T_FLOAT;
scanf("%lf",&vm.reg_ret.v_float);
}
BUILD_FUNC_SIGN(scans)
{
char s[1000];
vm.reg_ret.type=T_STRING;
scanf("%s",s);
vm.reg_ret.v_string=newString();
*vm.reg_ret.v_string=s;
}
BUILD_FUNC_SIGN(exit)
{
vm.next_ip=0x7fffffff;
}
BUILD_FUNC_SIGN(len)
{
vm.reg_ret.type=T_INT;
switch(GET_ARGV(0).type)
{
case T_ARRAY:
vm.reg_ret.v_int=GET_ARGV(0).v_array->size();
break;
case T_OBJECT:
vm.reg_ret.v_int=GET_ARGV(0).v_object->size();
break;
case T_STRING:
vm.reg_ret.v_int=GET_ARGV(0).v_string->length();
break;
default:
vm.reg_ret.v_int=1;
}
}
BUILD_FUNC_SIGN(push)
{
if(GET_ARGV(0).type!=T_ARRAY)return;
for(int i=1;i<argc;i++)GET_ARGV(0).v_array->push_back(GET_ARGV(i));
vm.reg_ret=GET_ARGV(0);
}
BUILD_FUNC_SIGN(clear)
{
if(GET_ARGV(0).type==T_ARRAY)GET_ARGV(0).v_array->clear();
else if(GET_ARGV(0).type==T_OBJECT)GET_ARGV(0).v_object->clear();
else return;
vm.reg_ret=GET_ARGV(0);
}
BUILD_FUNC_SIGN(resize)
{
if(GET_ARGV(0).type!=T_ARRAY)return;
GET_ARGV(0).v_array->resize(GET_ARGV(2));
vm.reg_ret=GET_ARGV(0);
}
BUILD_FUNC_SIGN(get_keys)
{
vm.reg_ret.type=T_ARRAY;
vm.reg_ret.v_array=newArray();
if(GET_ARGV(0).type==T_OBJECT)
{
int i=0;
vm.reg_ret.v_array->resize(GET_ARGV(0).v_object->size());
for(auto &x:*GET_ARGV(0).v_object)
{
(*vm.reg_ret.v_array)[i].type=T_STRING;
(*vm.reg_ret.v_array)[i].v_string=newString();
*(*vm.reg_ret.v_array)[i].v_string=x.first;
i++;
}
}
else if(GET_ARGV(0).type==T_ARRAY)
{
int size=GET_ARGV(0).v_array->size();
vm.reg_ret.v_array->resize(size);
for(int i=0;i<size;i++)
{
(*vm.reg_ret.v_array)[i].type=T_INT;
(*vm.reg_ret.v_array)[i].v_int=i;
}
}
}
BUILD_FUNC_SIGN(gc)
{
gc();
}
BUILD_FUNC_SIGN(each)
{
auto &v=vm.v_stack.top();
auto &f=vm.v_stack.top(1);
if(v.type==T_ARRAY)
{
for(int i=0;i<v.v_array->size();i++)
{
vm.push(f);
vm.push((*v.v_array)[i]);
vm.push(i);
vm.callReturn(2);
}
}
else if(v.type==T_OBJECT)
{
for(auto &x:*v.v_object)
{
vm.push(f);
vm.push(x.first);
vm.push(x.second);
vm.callReturn(2);
}
}
}
<|endoftext|> |
<commit_before>/**
* Implementation of Chan's algorithm for convex hull
* computation of a set of points in the 2d space.
*/
#ifndef chan_algorithm_h
#define chan_algorithm_h
#include "angle.hpp"
#include "graham_scan.hpp"
#include "jarvis_march.hpp"
#include "point_concept.hpp"
#include "static_assert.hpp"
#include <algorithm>
#include <cmath>
#include <iterator>
#include <limits>
#include <experimental/optional>
#include <utility>
namespace hull::algorithms::details::chan {
/**
* Compute the number of elements (i.e. distance) and the number
* of partitions for the Chan's algorithm.
* @param first - forward iterator to the first element of the container of points.
* @param last - forward iterator to the one-past last point of the container.
* @return - a pair containing the number of elements and the number of partitions.
*/
template <typename ForwardIt>
auto compute_distance_and_number_of_partitions(ForwardIt first, ForwardIt last, std::size_t m) {
// Let r = ceil(n/m)
const auto n = std::distance(first, last);
const auto r = static_cast<std::size_t>(std::ceil(static_cast<double>(n) / static_cast<double>(m)));
return std::make_pair(n, r);
}
/**
* Simplified access to a partition. The Chan's algorithm requires to partition
* P into disjoint subsets P(1), P(2), ..., P(r), each of size at most m.
* We make it a no-op by taking the points in their original order, and assume
* the subsets at indices [0 ; m - 1], [m ; 2m - 1], etc.
*/
template <typename RandomIt>
class partition final {
RandomIt first;
std::size_t m;
public:
explicit partition(RandomIt first, std::size_t m): first{first}, m{m} {}
RandomIt operator()(std::size_t i) const noexcept {
return first + (i * m);
}
};
}
namespace hull::algorithms::details {
/**
* Implementation of Chan algorithm, which is theoretically
* the most performant in operational research terms.
* Reference: http://www.cs.wustl.edu/~pless/506/l3.html
*/
template <typename RandomIt, typename OutputIt>
std::experimental::optional<OutputIt> chan_impl(RandomIt first, RandomIt last, OutputIt first2, std::size_t m) {
if (first == last) {
return {};
}
auto [n, r] = chan::compute_distance_and_number_of_partitions(first, last, m);
chan::partition<RandomIt> P(first, m);
// Extra memory required to store the size of the sub-convex hulls
std::vector<RandomIt> lasts;
lasts.reserve(r);
// (2) For i = 1 to r do:
// (a) Compute Hull(P(i)) using Graham's scan and store the vertices in an ordered array.
for (std::size_t i{}; i < r - 1; i++) {
const auto convex_hull_last = graham_scan(P(i), P(i + 1));
lasts.push_back(convex_hull_last);
}
// Last subset, which may be smaller
{
const auto convex_hull_last = graham_scan(P(r - 1), last);
lasts.push_back(convex_hull_last);
}
// (3) Let point_on_hull be the bottommost point of P
const auto min_y = std::min_element(first, last, [](const auto& p1, const auto& p2) {
return y(p1) < y(p2) || (y(p1) == y(p2) && x(p1) > x(p2));
});
auto point_on_hull = *min_y;
const auto pfirst = *min_y;
// Let endpoint = (-Inf; 0)
using point_type = decltype(point_on_hull);
using coord_type = coordinate_t<point_type>;
auto endpoint = point_type{std::numeric_limits<coord_type>::lowest(), static_cast<coord_type>(0)};
// (4) For k = 1 to m do:
// (a) For i = 1 to r do:
// Compute point q in P(i) that maximizes the angle p(k-1) p(k) q
// (b) Let p(k+1) be the point q in q(1),q(2),...q(r) than maximizes the angle p(k-1) p(k) q
// (c) If p(k+1) = p(1) then return {p(1), p(2), ... p(k)}.
std::vector<point_type> q(r);
for (std::size_t k{}; k < m; k++) {
*first2++ = point_on_hull;
for (std::size_t i{}; i < r; i++) {
q[i] = max_jarvis_march(P(i), lasts[i], point_on_hull/*, endpoint*/);
}
const auto pk = details::max_jarvis_march(std::begin(q), std::end(q), point_on_hull/*, endpoint*/);
if (hull::equals(pk, pfirst)) {
return first2;
}
endpoint = point_on_hull;
point_on_hull = pk;
}
// (5) Return "m was too small, try again"
return {};
}
}
namespace hull::algorithms {
/**
*
*/
template <typename RandomIt, typename OutputIt>
OutputIt chan(RandomIt first, RandomIt last, OutputIt first2) {
static_assert_is_random_access_iterator_to_point<RandomIt>();
if (first == last) {
return first2;
}
// (1) For t = 1; 2; 3... do:
// (a) Let m = min(2^(2^t),n)
// (b) Invoke PartialHull(P, m), returning the result in L.
// (c) If L != "try again" then return L.
using point_type = typename std::iterator_traits<RandomIt>::value_type;
const std::size_t n = std::distance(first, last);
std::vector<point_type> intermediary(n);
for (std::size_t t{1}; ; t++) {
const std::size_t pow = 1 << (1 << t); // warning: may overflow
const auto m = std::min(pow, n);
const auto last_intermediary = details::chan_impl(first, last, std::begin(intermediary), m);
if (last_intermediary) {
return std::move(std::begin(intermediary), *last_intermediary, first2);
}
intermediary.clear();
}
}
}
namespace hull {
/**
* Compile-time enumeration to choose the
* algorithm thanks to a policy approach.
* @param chan_t - Chan's algorithm.
*/
struct chan_t {};
/**
* Algorithms policies to choose an overload.
* @param chan - Chan's algorithm.
*/
namespace choice {
static constexpr const chan_t chan{};
}
/**
* Overload of iterator-based convex hull computation for Chan.
* Average time complexity: O(N * log(H)) where N is the number of input
* points and H is the number of points on the convex hull.
* Average space complexity: O(3 * N).
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* destination container of points.
*/
template <typename RandomIt, typename OutputIt>
auto compute_convex_hull(chan_t policy, RandomIt first, RandomIt last, OutputIt first2) {
return algorithms::chan(first, last, first2);
}
namespace convex {
/**
* Overload of container-based convex hull computation for Chan.
* Average time complexity: O(N * log(H)) where N is the number of input
* points and H is the number of points on the convex hull.
* Average space complexity: O(4 * N).
* @param c1 - the input container.
* @param c2 - the destination container.
*/
template <typename TContainer1, typename TContainer2>
void compute(chan_t policy, TContainer1 c1, TContainer2& c2) {
hull::algorithms::chan(std::begin(c1), std::end(c1), std::back_inserter(c2));
}
}
}
#endif
<commit_msg>Continue the refactoring of Chan's algorithm.<commit_after>/**
* Implementation of Chan's algorithm for convex hull
* computation of a set of points in the 2d space.
*/
#ifndef chan_algorithm_h
#define chan_algorithm_h
#include "angle.hpp"
#include "graham_scan.hpp"
#include "jarvis_march.hpp"
#include "point_concept.hpp"
#include "static_assert.hpp"
#include <algorithm>
#include <cmath>
#include <iterator>
#include <limits>
#include <experimental/optional>
#include <utility>
namespace hull::algorithms::details::chan {
/**
* Compute the number of elements (i.e. distance) and the number
* of partitions for the Chan's algorithm.
* @param first - forward iterator to the first element of the container of points.
* @param last - forward iterator to the one-past last point of the container.
* @return - a pair containing the number of elements and the number of partitions.
*/
template <typename ForwardIt>
auto compute_distance_and_number_of_partitions(ForwardIt first, ForwardIt last, std::size_t m) {
// Let r = ceil(n/m)
const auto n = std::distance(first, last);
const auto r = static_cast<std::size_t>(std::ceil(static_cast<double>(n) / static_cast<double>(m)));
return std::make_pair(n, r);
}
/**
* Simplified access to a partition. The Chan's algorithm requires to partition
* P into disjoint subsets P(1), P(2), ..., P(r), each of size at most m.
* We make it a no-op by taking the points in their original order, and assume
* the subsets at indices [0 ; m - 1], [m ; 2m - 1], etc.
*/
template <typename RandomIt>
class partition final {
RandomIt first;
std::size_t m;
public:
explicit partition(RandomIt first, std::size_t m): first{first}, m{m} {}
RandomIt operator()(std::size_t i) const noexcept {
return first + (i * m);
}
};
/**
* For each partition P(0), P(1), ..., P(r - 1), call Graham Scan's
* algorithm. P(r - 1) may have less elements than the other partitions.
* @param P - the partitions of points.
* @param last - iterator to the one-past last point of the container.
* @param r - the number of partitions.
* @return - a vector of iterators. Graham Scan returns an iterator to the
* one-past last point forming the convex hull. For each partition,
* we need to keep track of this resulting iterator.
*/
template <typename RandomIt>
auto compute_graham_scan_for_each_partition(partition<RandomIt> P, RandomIt last, std::size_t r) {
// Extra memory required to store the size of the sub-convex hulls
std::vector<RandomIt> lasts;
lasts.reserve(r);
// For i = 1 to r do:
// Compute Hull(P(i)) using Graham's scan and store the vertices in an ordered array.
for (std::size_t i{}; i < r - 1; i++) {
const auto convex_hull_last = graham_scan(P(i), P(i + 1));
lasts.push_back(convex_hull_last);
}
// Last subset, which may be smaller
{
const auto convex_hull_last = graham_scan(P(r - 1), last);
lasts.push_back(convex_hull_last);
}
return lasts;
}
}
namespace hull::algorithms::details {
/**
* Implementation of Chan algorithm, which is theoretically
* the most performant in operational research terms.
* Reference: http://www.cs.wustl.edu/~pless/506/l3.html
*/
template <typename RandomIt, typename OutputIt>
std::experimental::optional<OutputIt> chan_impl(RandomIt first, RandomIt last, OutputIt first2, std::size_t m) {
if (first == last) {
return {};
}
const auto [n, r] = chan::compute_distance_and_number_of_partitions(first, last, m);
chan::partition<RandomIt> P(first, m);
auto lasts = compute_graham_scan_for_each_partition(P, last, r);
// (3) Let point_on_hull be the bottommost point of P
const auto min_y = std::min_element(first, last, [](const auto& p1, const auto& p2) {
return y(p1) < y(p2) || (y(p1) == y(p2) && x(p1) > x(p2));
});
auto point_on_hull = *min_y;
const auto pfirst = *min_y;
// Let endpoint = (-Inf; 0)
using point_type = decltype(point_on_hull);
using coord_type = coordinate_t<point_type>;
auto endpoint = point_type{std::numeric_limits<coord_type>::lowest(), static_cast<coord_type>(0)};
// (4) For k = 1 to m do:
// (a) For i = 1 to r do:
// Compute point q in P(i) that maximizes the angle p(k-1) p(k) q
// (b) Let p(k+1) be the point q in q(1),q(2),...q(r) than maximizes the angle p(k-1) p(k) q
// (c) If p(k+1) = p(1) then return {p(1), p(2), ... p(k)}.
std::vector<point_type> q(r);
for (std::size_t k{}; k < m; k++) {
*first2++ = point_on_hull;
for (std::size_t i{}; i < r; i++) {
q[i] = max_jarvis_march(P(i), lasts[i], point_on_hull/*, endpoint*/);
}
const auto pk = details::max_jarvis_march(std::begin(q), std::end(q), point_on_hull/*, endpoint*/);
if (hull::equals(pk, pfirst)) {
return first2;
}
endpoint = point_on_hull;
point_on_hull = pk;
}
// (5) Return "m was too small, try again"
return {};
}
}
namespace hull::algorithms {
/**
*
*/
template <typename RandomIt, typename OutputIt>
OutputIt chan(RandomIt first, RandomIt last, OutputIt first2) {
static_assert_is_random_access_iterator_to_point<RandomIt>();
if (first == last) {
return first2;
}
// (1) For t = 1; 2; 3... do:
// (a) Let m = min(2^(2^t),n)
// (b) Invoke PartialHull(P, m), returning the result in L.
// (c) If L != "try again" then return L.
using point_type = typename std::iterator_traits<RandomIt>::value_type;
const std::size_t n = std::distance(first, last);
std::vector<point_type> intermediary(n);
for (std::size_t t{1}; ; t++) {
const std::size_t pow = 1 << (1 << t); // warning: may overflow
const auto m = std::min(pow, n);
const auto last_intermediary = details::chan_impl(first, last, std::begin(intermediary), m);
if (last_intermediary) {
return std::move(std::begin(intermediary), *last_intermediary, first2);
}
intermediary.clear();
}
}
}
namespace hull {
/**
* Compile-time enumeration to choose the
* algorithm thanks to a policy approach.
* @param chan_t - Chan's algorithm.
*/
struct chan_t {};
/**
* Algorithms policies to choose an overload.
* @param chan - Chan's algorithm.
*/
namespace choice {
static constexpr const chan_t chan{};
}
/**
* Overload of iterator-based convex hull computation for Chan.
* Average time complexity: O(N * log(H)) where N is the number of input
* points and H is the number of points on the convex hull.
* Average space complexity: O(3 * N).
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* destination container of points.
*/
template <typename RandomIt, typename OutputIt>
auto compute_convex_hull(chan_t policy, RandomIt first, RandomIt last, OutputIt first2) {
return algorithms::chan(first, last, first2);
}
namespace convex {
/**
* Overload of container-based convex hull computation for Chan.
* Average time complexity: O(N * log(H)) where N is the number of input
* points and H is the number of points on the convex hull.
* Average space complexity: O(4 * N).
* @param c1 - the input container.
* @param c2 - the destination container.
*/
template <typename TContainer1, typename TContainer2>
void compute(chan_t policy, TContainer1 c1, TContainer2& c2) {
hull::algorithms::chan(std::begin(c1), std::end(c1), std::back_inserter(c2));
}
}
}
#endif
<|endoftext|> |
<commit_before>//
// Copyright 2015 Jeff Bush
//
// 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 <stdint.h>
#include <stdio.h>
// http://en.wikipedia.org/wiki/Bitonic_sorter
const vecu16_t kPermute1 = { 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 };
const vecu16_t kPermute2 = { 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13 };
const vecu16_t kPermute3 = { 4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11 };
const vecu16_t kPermute4 = { 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7 };
inline veci16_t sortStep(veci16_t items, vecu16_t shuffle, int mask)
{
veci16_t swapped = __builtin_nyuzi_shufflei(items, shuffle);
int compareResult = __builtin_nyuzi_mask_cmpi_slt(items, swapped);
return __builtin_nyuzi_vector_mixi(compareResult ^ mask, items, swapped);
}
veci16_t bitonicSort(veci16_t items)
{
items = sortStep(items, kPermute1, 0b0110011001100110);
items = sortStep(items, kPermute2, 0b0011110000111100);
items = sortStep(items, kPermute1, 0b1010010110101010);
items = sortStep(items, kPermute3, 0b0000111111110000);
items = sortStep(items, kPermute2, 0b0011001111001100);
items = sortStep(items, kPermute1, 0b1010101001010101);
items = sortStep(items, kPermute4, 0b0000000011111111);
items = sortStep(items, kPermute3, 0b0000111100001111);
items = sortStep(items, kPermute2, 0b0011001100110011);
items = sortStep(items, kPermute1, 0b0101010101010101);
return items;
}
int main()
{
veci16_t testVector = { 21, 7, 37, 23, 19, 13, 11, 27, 29, 33, 9, 25, 31, 35, 17, 15 };
veci16_t result = bitonicSort(testVector);
for (int i = 0; i < 16; i++)
printf("%u, ", result[i]);
// CHECK: 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37
return 0;
}
<commit_msg>compiler tests: oops<commit_after>//
// Copyright 2015 Jeff Bush
//
// 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 <stdint.h>
#include <stdio.h>
// http://en.wikipedia.org/wiki/Bitonic_sorter
const vecu16_t kPermute1 = { 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 };
const vecu16_t kPermute2 = { 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13 };
const vecu16_t kPermute3 = { 4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11 };
const vecu16_t kPermute4 = { 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7 };
inline veci16_t sortStep(veci16_t items, vecu16_t shuffle, int mask)
{
veci16_t swapped = __builtin_nyuzi_shufflei(items, shuffle);
int compareResult = __builtin_nyuzi_mask_cmpi_slt(items, swapped);
return __builtin_nyuzi_vector_mixi(compareResult ^ mask, items, swapped);
}
veci16_t bitonicSort(veci16_t items)
{
items = sortStep(items, kPermute1, 0b0110011001100110);
items = sortStep(items, kPermute2, 0b0011110000111100);
items = sortStep(items, kPermute1, 0b0101101001011010);
items = sortStep(items, kPermute3, 0b0000111111110000);
items = sortStep(items, kPermute2, 0b0011001111001100);
items = sortStep(items, kPermute1, 0b1010101001010101);
items = sortStep(items, kPermute4, 0b0000000011111111);
items = sortStep(items, kPermute3, 0b0000111100001111);
items = sortStep(items, kPermute2, 0b0011001100110011);
items = sortStep(items, kPermute1, 0b0101010101010101);
return items;
}
int main()
{
veci16_t testVector = { 21, 7, 37, 23, 19, 13, 11, 27, 29, 33, 9, 25, 31, 35, 17, 15 };
veci16_t result = bitonicSort(testVector);
for (int i = 0; i < 16; i++)
printf("%u, ", result[i]);
// CHECK: 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37
return 0;
}
<|endoftext|> |
<commit_before>#include "twn_config.h"
#include "FS.h"
#include "logger.h"
#include "vector.h"
#include "utils.h"
char config_file[] = "/config.txt";
Config::Config() : m_root(0){}
Config::~Config(){}
void Config::addKey(const char* key)
{
keys.push_back(key);
}
twnstd::vector<const char*> Config::getKeys()
{
return keys;
}
void Config::Read()
{
//DynamicJsonBuffer jsonBuffer;
if(SPIFFS.exists(config_file)) {
File fp = SPIFFS.open(config_file, "r");
String line = fp.readStringUntil('\n');
m_root = &jsonBuffer.parseObject( line );
fp.close();
} else {
m_root = &jsonBuffer.createObject();
LOG_WARNING("config file not exists");
}
}
void Config::Write()
{
if(!m_root) {
return;
}
String data;
m_root->printTo(data);
LOG_INFO("%s", data.c_str());
File fp = SPIFFS.open(config_file, "w");
fp.write((uint8_t*)data.c_str(), data.length());
fp.close();
}
bool Config::setValue(const char* key, const char* value)
{
if(!m_root) {
return false;
}
JsonObject* obj = m_root;
twnstd::vector<String> keys = getSubstrings(key, ".");
for(int i = 0; i < keys.length(); i++) {
if(i + 1 < keys.length() && obj->containsKey(keys[i])) {
JsonObject& newobj = obj->get<JsonVariant>(keys[i]);
obj = &newobj;
} else if(i + 1 < keys.length() && !obj->containsKey(keys[i])) {
obj = &(obj->createNestedObject(keys[i]));
} else {
return obj->set(keys[i], value);
}
}
return false;
}
const char* Config::getValue(const char* key)
{
if(!m_root) {
return "";
}
twnstd::vector<String> keys = getSubstrings(key, ".");
JsonObject* obj = m_root;
for(int i = 0; i < keys.length(); i++) {
if(i + 1 < keys.length() && obj->containsKey(keys[i])) {
JsonObject& newobj = obj->get<JsonVariant>(keys[i]);
obj = &newobj;
} else if(obj->containsKey(keys[i])){
const char* data = obj->get<const char*>(keys[i]);
return data;
} else {
LOG_INFO("absent key");
break;
}
}
return "";
}
bool Config::removeValue(const char* key)
{
if(!m_root) {
return false;
}
twnstd::vector<String> keys = getSubstrings(key, ".");
JsonObject* obj = m_root;
for(int i = 0; i < keys.length(); i++) {
if(i + 1 < keys.length() && obj->containsKey(keys[i])) {
JsonObject& newobj = obj->get<JsonVariant>(keys[i]);
obj = &newobj;
} else if(obj->containsKey(keys[i])){
obj->remove(keys[i]);
return true;
} else {
LOG_INFO("absent key");
break;
}
}
return false;
}
<commit_msg>little fix<commit_after>#include "twn_config.h"
#include "FS.h"
#include "logger.h"
#include "vector.h"
#include "utils.h"
char config_file[] = "/config.txt";
Config::Config() : m_root(0){}
Config::~Config(){}
void Config::addKey(const char* key)
{
keys.push_back(key);
}
twnstd::vector<const char*> Config::getKeys()
{
return keys;
}
void Config::Read()
{
//DynamicJsonBuffer jsonBuffer;
if(SPIFFS.exists(config_file)) {
File fp = SPIFFS.open(config_file, "r");
String line = fp.readStringUntil('\n');
m_root = &jsonBuffer.parseObject( line );
fp.close();
} else {
m_root = &jsonBuffer.createObject();
LOG_WARNING("config file not exists");
}
}
void Config::Write()
{
if(!m_root) {
return;
}
String data;
m_root->printTo(data);
LOG_INFO("%s", data.c_str());
File fp = SPIFFS.open(config_file, "w");
fp.write((uint8_t*)data.c_str(), data.length());
fp.close();
}
bool Config::setValue(const char* key, const char* value)
{
if(!m_root) {
return false;
}
JsonObject* obj = m_root;
twnstd::vector<String> keys = getSubstrings(key, ".");
for(int i = 0; i < keys.length(); i++) {
if(i + 1 < keys.length() && obj->containsKey(keys[i])) {
JsonObject& newobj = obj->get<JsonVariant>(keys[i]);
obj = &newobj;
} else if(i + 1 < keys.length() && !obj->containsKey(keys[i])) {
obj = &(obj->createNestedObject(keys[i]));
} else {
return obj->set(keys[i], String(value));
}
}
return false;
}
const char* Config::getValue(const char* key)
{
if(!m_root) {
return "";
}
twnstd::vector<String> keys = getSubstrings(key, ".");
JsonObject* obj = m_root;
for(int i = 0; i < keys.length(); i++) {
if(i + 1 < keys.length() && obj->containsKey(keys[i])) {
JsonObject& newobj = obj->get<JsonVariant>(keys[i]);
obj = &newobj;
} else if(obj->containsKey(keys[i])){
const char* data = obj->get<const char*>(keys[i]);
return data;
} else {
LOG_INFO("absent key");
break;
}
}
return "";
}
bool Config::removeValue(const char* key)
{
if(!m_root) {
return false;
}
twnstd::vector<String> keys = getSubstrings(key, ".");
JsonObject* obj = m_root;
for(int i = 0; i < keys.length(); i++) {
if(i + 1 < keys.length() && obj->containsKey(keys[i])) {
JsonObject& newobj = obj->get<JsonVariant>(keys[i]);
obj = &newobj;
} else if(obj->containsKey(keys[i])){
obj->remove(keys[i]);
return true;
} else {
LOG_INFO("absent key");
break;
}
}
return false;
}
<|endoftext|> |
<commit_before>#include <QsLog.h>
#include "dbus_fronius.h"
#include "dbus_gateway_bridge.h"
#include "dbus_inverter_bridge.h"
#include "dbus_inverter_settings_bridge.h"
#include "dbus_settings_bridge.h"
#include "inverter.h"
#include "inverter_gateway.h"
#include "inverter_settings.h"
#include "inverter_updater.h"
#include "settings.h"
DBusFronius::DBusFronius(QObject *parent) :
QObject(parent),
mSettings(new Settings(this)),
mGateway(new InverterGateway(mSettings, this)),
mSettingsBridge(new DBusSettingsBridge(mSettings, this)),
mGatewayBridge(new DBusGatewayBridge(mGateway, this))
{
// This enables us to retrieve values from QT properties via the
// QObject::property function.
qRegisterMetaType<QList<QHostAddress> >();
qRegisterMetaType<QHostAddress>();
qRegisterMetaType<InverterPosition>("Position");
qRegisterMetaType<InverterPhase>("Phase");
connect(mGateway, SIGNAL(inverterFound(Inverter *)),
this, SLOT(onInverterFound(Inverter *)));
connect(mSettingsBridge, SIGNAL(initialized()),
this, SLOT(onSettingsInitialized()));
}
void DBusFronius::onSettingsInitialized()
{
mGateway->startDetection();
}
void DBusFronius::onInverterFound(Inverter *inverter)
{
Inverter *oldInverter = findInverter(inverter->deviceType(),
inverter->uniqueId());
if (oldInverter != 0) {
oldInverter->setHostName(inverter->hostName());
oldInverter->setPort(inverter->port());
QLOG_INFO() << "Updated connection settings:" << inverter->uniqueId()
<< "@" << inverter->hostName() << ':' << inverter->id();
// inverter will be deleted by InverterGateway, because we have not
// set a new parent.
return;
}
inverter->setParent(this);
mInverters.append(inverter);
connect(inverter, SIGNAL(isConnectedChanged()),
this, SLOT(onIsConnectedChanged()));
QLOG_INFO() << "New inverter:" << inverter->uniqueId()
<< "@" << inverter->hostName() << ':' << inverter->id();
InverterSettings *settings =
new InverterSettings(inverter->deviceType(), inverter->uniqueId(),
inverter);
// The custom name we set here will be use as default (and initial) value
// of the D-Bus parameter. If the parameter already exists, this value
// will be overwritten by the current value taken from the D-Bus.
settings->setCustomName(inverter->productName());
DBusInverterSettingsBridge *bridge =
new DBusInverterSettingsBridge(settings, settings);
connect(bridge, SIGNAL(initialized()),
this, SLOT(onInverterSettingsInitialized()));
}
void DBusFronius::onInverterSettingsInitialized()
{
DBusInverterSettingsBridge *bridge =
static_cast<DBusInverterSettingsBridge *>(sender());
InverterSettings *settings =
static_cast<InverterSettings *>(bridge->parent());
Inverter *inverter =
static_cast<Inverter *>(settings->parent());
if (inverter->phaseCount() > 1) {
settings->setPhase(MultiPhase);
} else if (settings->phase() == MultiPhase) {
QLOG_ERROR() << "Inverter is single phased, but settings report"
<< "multiphase. Adjusting settings.";
settings->setPhase(PhaseL1);
}
InverterUpdater *iu = new InverterUpdater(inverter, settings, inverter);
connect(iu, SIGNAL(initialized()), this, SLOT(onInverterInitialized()));
}
void DBusFronius::onInverterInitialized()
{
InverterUpdater *ui = static_cast<InverterUpdater *>(sender());
Inverter *inverter = ui->inverter();
InverterSettings *settings = ui->settings();
new DBusInverterBridge(inverter, settings, inverter);
}
void DBusFronius::onIsConnectedChanged()
{
Inverter *inverter = static_cast<Inverter *>(sender());
if (inverter->isConnected())
return;
QLOG_INFO() << "Lost connection with: " << inverter->uniqueId();
// Start device scan, maybe the IP address of the data card has changed.
mGateway->setAutoDetect(true);
// // Do not delete the inverter here because right now a function within
// // InverterUpdater is emitting the isConnectedChanged signal. Deleting
// // the inverter will also delete the InverterUpdater
// mInverters.removeOne(inverter);
// inverter->deleteLater();
}
Inverter *DBusFronius::findInverter(int deviceType, const QString &uniqueId)
{
foreach (Inverter *inverter, mInverters)
{
if (inverter->deviceType() == deviceType &&
inverter->uniqueId() == uniqueId) {
return inverter;
}
}
return 0;
}
<commit_msg>Log warning instead of info message when connection to onverter is lost.<commit_after>#include <QsLog.h>
#include "dbus_fronius.h"
#include "dbus_gateway_bridge.h"
#include "dbus_inverter_bridge.h"
#include "dbus_inverter_settings_bridge.h"
#include "dbus_settings_bridge.h"
#include "inverter.h"
#include "inverter_gateway.h"
#include "inverter_settings.h"
#include "inverter_updater.h"
#include "settings.h"
DBusFronius::DBusFronius(QObject *parent) :
QObject(parent),
mSettings(new Settings(this)),
mGateway(new InverterGateway(mSettings, this)),
mSettingsBridge(new DBusSettingsBridge(mSettings, this)),
mGatewayBridge(new DBusGatewayBridge(mGateway, this))
{
// This enables us to retrieve values from QT properties via the
// QObject::property function.
qRegisterMetaType<QList<QHostAddress> >();
qRegisterMetaType<QHostAddress>();
qRegisterMetaType<InverterPosition>("Position");
qRegisterMetaType<InverterPhase>("Phase");
connect(mGateway, SIGNAL(inverterFound(Inverter *)),
this, SLOT(onInverterFound(Inverter *)));
connect(mSettingsBridge, SIGNAL(initialized()),
this, SLOT(onSettingsInitialized()));
}
void DBusFronius::onSettingsInitialized()
{
mGateway->startDetection();
}
void DBusFronius::onInverterFound(Inverter *inverter)
{
Inverter *oldInverter = findInverter(inverter->deviceType(),
inverter->uniqueId());
if (oldInverter != 0) {
oldInverter->setHostName(inverter->hostName());
oldInverter->setPort(inverter->port());
QLOG_INFO() << "Updated connection settings:" << inverter->uniqueId()
<< "@" << inverter->hostName() << ':' << inverter->id();
// inverter will be deleted by InverterGateway, because we have not
// set a new parent.
return;
}
inverter->setParent(this);
mInverters.append(inverter);
connect(inverter, SIGNAL(isConnectedChanged()),
this, SLOT(onIsConnectedChanged()));
QLOG_INFO() << "New inverter:" << inverter->uniqueId()
<< "@" << inverter->hostName() << ':' << inverter->id();
InverterSettings *settings =
new InverterSettings(inverter->deviceType(), inverter->uniqueId(),
inverter);
// The custom name we set here will be use as default (and initial) value
// of the D-Bus parameter. If the parameter already exists, this value
// will be overwritten by the current value taken from the D-Bus.
settings->setCustomName(inverter->productName());
DBusInverterSettingsBridge *bridge =
new DBusInverterSettingsBridge(settings, settings);
connect(bridge, SIGNAL(initialized()),
this, SLOT(onInverterSettingsInitialized()));
}
void DBusFronius::onInverterSettingsInitialized()
{
DBusInverterSettingsBridge *bridge =
static_cast<DBusInverterSettingsBridge *>(sender());
InverterSettings *settings =
static_cast<InverterSettings *>(bridge->parent());
Inverter *inverter =
static_cast<Inverter *>(settings->parent());
if (inverter->phaseCount() > 1) {
settings->setPhase(MultiPhase);
} else if (settings->phase() == MultiPhase) {
QLOG_ERROR() << "Inverter is single phased, but settings report"
<< "multiphase. Adjusting settings.";
settings->setPhase(PhaseL1);
}
InverterUpdater *iu = new InverterUpdater(inverter, settings, inverter);
connect(iu, SIGNAL(initialized()), this, SLOT(onInverterInitialized()));
}
void DBusFronius::onInverterInitialized()
{
InverterUpdater *ui = static_cast<InverterUpdater *>(sender());
Inverter *inverter = ui->inverter();
InverterSettings *settings = ui->settings();
new DBusInverterBridge(inverter, settings, inverter);
}
void DBusFronius::onIsConnectedChanged()
{
Inverter *inverter = static_cast<Inverter *>(sender());
if (inverter->isConnected())
return;
QLOG_WARN() << "Lost connection with: " << inverter->uniqueId()
<< "@ " << inverter->hostName() << ':' << inverter->port();
// Start device scan, maybe the IP address of the data card has changed.
mGateway->setAutoDetect(true);
// // Do not delete the inverter here because right now a function within
// // InverterUpdater is emitting the isConnectedChanged signal. Deleting
// // the inverter will also delete the InverterUpdater
// mInverters.removeOne(inverter);
// inverter->deleteLater();
}
Inverter *DBusFronius::findInverter(int deviceType, const QString &uniqueId)
{
foreach (Inverter *inverter, mInverters)
{
if (inverter->deviceType() == deviceType &&
inverter->uniqueId() == uniqueId) {
return inverter;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
namespace dev
{
namespace solidity
{
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, const char* _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, "abi") || argToStdout(_args, "natspec-user") || argToStdout(_args, "natspec-dev") ||
argToStdout(_args, "asm") || argToStdout(_args, "opcodes") || argToStdout(_args, "binary");
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBinary(string const& _contract)
{
auto choice = m_args["binary"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Binary: " << endl;
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".binary");
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleOpcode(string const& _contract)
{
// TODO: Figure out why the wrong operator << (from boost) is used here
auto choice = m_args["opcode"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Opcodes: " << endl;
dev::operator<<(cout, m_compiler.getBytecode(_contract));
cout << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".opcode");
dev::operator<<(outFile, m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleBytecode(string const& _contract)
{
if (m_args.count("opcodes"))
handleOpcode(_contract);
if (m_args.count("binary"))
handleBinary(_contract);
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = "abi";
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "natspec-user";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = "natspec-dev";
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
("ast", po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
("asm", po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
("opcodes", po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
("binary", po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
("abi", po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
("natspec-user", po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
("natspec-dev", po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
{
auto path = boost::filesystem::path(infile);
if (!boost::filesystem::exists(path))
{
cout << "Skipping non existant input file \"" << infile << "\"" << endl;
continue;
}
if (!boost::filesystem::is_regular_file(path))
{
cout << "\"" << infile << "\" is not a valid file. Skipping" << endl;
continue;
}
m_sourceCodes[infile] = asString(dev::contents(infile));
}
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count("ast"))
{
auto choice = m_args["ast"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count("asm"))
{
auto choice = m_args["asm"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode(contract);
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<commit_msg>Fix for unhandled solc exception with opcodes argument<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
// LTODO: Maybe some argument class pairing names with
// extensions and other attributes would be a better choice here?
#define ARG_ABI_STR "abi"
#define ARG_ASM_STR "asm"
#define ARG_AST_STR "ast"
#define ARG_BINARY_STR "binary"
#define ARG_OPCODES_STR "opcodes"
#define ARG_NATSPECDEV_STR "natspec-dev"
#define ARG_NATSPECUSER_STR "natspec-user"
namespace dev
{
namespace solidity
{
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, const char* _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, ARG_ABI_STR) || argToStdout(_args, ARG_NATSPECUSER_STR) ||
argToStdout(_args, ARG_NATSPECDEV_STR) || argToStdout(_args, ARG_ASM_STR) ||
argToStdout(_args, ARG_OPCODES_STR) || argToStdout(_args, ARG_BINARY_STR);
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBinary(string const& _contract)
{
auto choice = m_args[ARG_BINARY_STR].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Binary: " << endl;
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".binary");
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleOpcode(string const& _contract)
{
// TODO: Figure out why the wrong operator << (from boost) is used here
auto choice = m_args[ARG_OPCODES_STR].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Opcodes: " << endl;
dev::operator<<(cout, m_compiler.getBytecode(_contract));
cout << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".opcode");
dev::operator<<(outFile, m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleBytecode(string const& _contract)
{
if (m_args.count(ARG_OPCODES_STR))
handleOpcode(_contract);
if (m_args.count(ARG_BINARY_STR))
handleBinary(_contract);
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = ARG_ABI_STR;
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "ARG_NATSPECUSER_STR";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = ARG_NATSPECDEV_STR;
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
(ARG_AST_STR, po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
(ARG_ASM_STR, po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
(ARG_OPCODES_STR, po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
(ARG_BINARY_STR, po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
(ARG_ABI_STR, po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
(ARG_NATSPECUSER_STR, po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
(ARG_NATSPECDEV_STR, po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
{
auto path = boost::filesystem::path(infile);
if (!boost::filesystem::exists(path))
{
cout << "Skipping non existant input file \"" << infile << "\"" << endl;
continue;
}
if (!boost::filesystem::is_regular_file(path))
{
cout << "\"" << infile << "\" is not a valid file. Skipping" << endl;
continue;
}
m_sourceCodes[infile] = asString(dev::contents(infile));
}
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count(ARG_AST_STR))
{
auto choice = m_args[ARG_AST_STR].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count(ARG_ASM_STR))
{
auto choice = m_args[ARG_ASM_STR].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode(contract);
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<|endoftext|> |
<commit_before>#include "get_new_points.hxx"
#include "eval_weighted.hxx"
#include "poles_prefactor.hxx"
#include "power_prefactor.hxx"
#include "../sdp_solve.hxx"
#include "../ostream_set.hxx"
std::vector<El::BigFloat>
compute_optimal(const std::vector<Positive_Matrix_With_Prefactor> &matrices,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters)
{
size_t num_weights(normalization.size());
const size_t num_blocks(matrices.size());
std::vector<El::BigFloat> weights(num_weights, 1);
std::vector<std::set<El::BigFloat>> points(num_blocks);
std::vector<std::vector<El::BigFloat>> new_points(num_blocks);
// Need to have a point at zero and infinity
// GMP does not have a special infinity value, so we use max double.
const El::BigFloat infinity(std::numeric_limits<double>::max());
const El::BigFloat min_x(0), max_x(infinity);
for(size_t block(0); block < num_blocks; ++block)
{
points.at(block).emplace(min_x);
points.at(block).emplace(1);
// for(double x(min_x); x < max_x; x *= 4)
// points.at(block).emplace(x);
new_points.at(block).emplace_back(max_x);
}
bool has_new_points(true);
while(has_new_points)
{
has_new_points = false;
size_t num_constraints(0);
std::vector<size_t> matrix_dimensions;
for(size_t block(0); block != num_blocks; ++block)
{
for(auto &point : new_points.at(block))
{
points.at(block).emplace(point);
}
num_constraints += points.at(block).size();
matrix_dimensions.insert(matrix_dimensions.end(),
points.at(block).size(),
matrices[block].polynomials.size());
if(El::mpi::Rank() == 0)
{
std::cout << "points: " << block << " " << points.at(block)
<< "\n";
}
}
if(El::mpi::Rank() == 0)
{
std::cout << "num_constraints: " << num_constraints << "\n";
}
// std::cout << "matrix_dimensions: " << matrix_dimensions << "\n";
Block_Info block_info(matrix_dimensions, parameters.procs_per_node,
parameters.proc_granularity, parameters.verbosity);
El::Grid grid(block_info.mpi_comm.value);
std::vector<El::BigFloat> prefactors;
prefactors.reserve(num_constraints);
std::vector<std::vector<El::BigFloat>> primal_objective_c;
primal_objective_c.reserve(num_constraints);
std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
free_var_matrix.reserve(num_constraints);
// TODO: This is duplicated from sdp2input/write_output/write_output.cxx
auto max_normalization(normalization.begin());
for(auto n(normalization.begin()); n != normalization.end(); ++n)
{
if(Abs(*n) > Abs(*max_normalization))
{
max_normalization = n;
}
}
int64_t max_index(
std::distance(normalization.begin(), max_normalization));
for(size_t block(0); block != num_blocks; ++block)
{
for(auto &x : points.at(block))
{
if(x == infinity)
{
prefactors.push_back(1);
}
else
{
prefactors.push_back(
power_prefactor(matrices[block].damped_rational.base, x)
* poles_prefactor(matrices[block].damped_rational.poles,
x));
}
auto &prefactor(prefactors.back());
const size_t dim(matrices[block].polynomials.size());
free_var_matrix.emplace_back(
dim * (dim + 1) / 2,
matrices[block].polynomials.at(0).at(0).size() - 1);
auto &free_var(free_var_matrix.back());
primal_objective_c.emplace_back();
auto &primal(primal_objective_c.back());
size_t flattened_matrix_row(0);
for(size_t matrix_row(0); matrix_row != dim; ++matrix_row)
for(size_t matrix_column(0); matrix_column <= matrix_row;
++matrix_column)
{
if(x == infinity)
{
int64_t max_degree(0);
for(auto &poly : matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column))
max_degree = std::max(max_degree, poly.degree());
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.degree()
< max_degree)
{
primal.push_back(0);
}
else
{
primal.push_back(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.coefficients.at(max_degree)
/ normalization.at(max_index));
}
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.degree()
< max_degree)
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index);
}
else
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.coefficients.at(max_degree);
}
}
}
else
{
primal.push_back(prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)(x)
/ normalization.at(max_index));
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)(x);
}
}
++flattened_matrix_row;
}
}
}
SDP sdp(objectives, normalization, prefactors, primal_objective_c,
free_var_matrix, block_info, grid);
SDP_Solver solver(parameters, block_info, grid,
sdp.dual_objective_b.Height());
Timers timers(parameters.verbosity >= Verbosity::debug);
SDP_Solver_Terminate_Reason reason
= solver.run(parameters, block_info, sdp, grid, timers);
if(reason != SDP_Solver_Terminate_Reason::PrimalDualOptimal)
{
std::stringstream ss;
ss << "Can not find solution: " << reason;
throw std::runtime_error(ss.str());
}
// y is duplicated among cores, so only need to print out copy on
// the root node.
// THe weight at max_index is determined by the normalization condition
// dot(norm,weights)=1
weights.at(max_index) = 1;
for(int64_t block_row(0); block_row != solver.y.blocks.at(0).Height();
++block_row)
{
const int64_t index(block_row + (block_row < max_index ? 0 : 1));
weights.at(index) = solver.y.blocks.at(0).Get(block_row, 0);
weights.at(max_index) -= weights.at(index) * normalization.at(index);
}
weights.at(max_index) /= normalization.at(max_index);
if(El::mpi::Rank() == 0)
{
std::cout.precision(10);
std::cout << "weight: " << weights << "\n";
El::BigFloat optimal(0);
for(size_t index(0); index < objectives.size(); ++index)
{
optimal += objectives[index] * weights[index];
}
std::cout << "optimal: " << optimal << "\n";
}
for(size_t block(0); block != num_blocks; ++block)
{
// 0.01 should be a small enough relative error so that we are
// in the regime of convergence. Then the error estimates will
// work
// Mesh mesh(*(points.at(block).begin()), *(points.at(block).rbegin()),
Mesh mesh(*(points.at(block).begin()), El::BigFloat(100),
[&](const El::BigFloat &x) {
return eval_weighted(matrices[block], x, weights);
},
0.01);
new_points.at(block) = get_new_points(mesh);
for(auto &point : new_points.at(block))
{
has_new_points
= has_new_points || (points.at(block).count(point) == 0);
}
}
}
// if(El::mpi::Rank() == 0)
// {
// std::cout << "weights: " << weights << "\n";
// }
return weights;
}
<commit_msg>Use existing weights as an initial guess<commit_after>#include "get_new_points.hxx"
#include "eval_weighted.hxx"
#include "poles_prefactor.hxx"
#include "power_prefactor.hxx"
#include "../sdp_solve.hxx"
#include "../ostream_set.hxx"
std::vector<El::BigFloat>
compute_optimal(const std::vector<Positive_Matrix_With_Prefactor> &matrices,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters)
{
size_t num_weights(normalization.size());
const size_t num_blocks(matrices.size());
std::vector<El::BigFloat> weights(num_weights, 0);
std::vector<std::set<El::BigFloat>> points(num_blocks);
std::vector<std::vector<El::BigFloat>> new_points(num_blocks);
// Need to have a point at zero and infinity
// GMP does not have a special infinity value, so we use max double.
const El::BigFloat infinity(std::numeric_limits<double>::max());
const El::BigFloat min_x(0), max_x(infinity);
for(size_t block(0); block < num_blocks; ++block)
{
points.at(block).emplace(min_x);
points.at(block).emplace(1);
// for(double x(min_x); x < max_x; x *= 4)
// points.at(block).emplace(x);
new_points.at(block).emplace_back(max_x);
}
bool has_new_points(true);
while(has_new_points)
{
has_new_points = false;
size_t num_constraints(0);
std::vector<size_t> matrix_dimensions;
for(size_t block(0); block != num_blocks; ++block)
{
for(auto &point : new_points.at(block))
{
points.at(block).emplace(point);
}
num_constraints += points.at(block).size();
matrix_dimensions.insert(matrix_dimensions.end(),
points.at(block).size(),
matrices[block].polynomials.size());
if(El::mpi::Rank() == 0)
{
std::cout << "points: " << block << " " << points.at(block)
<< "\n";
}
}
if(El::mpi::Rank() == 0)
{
std::cout << "num_constraints: " << num_constraints << "\n";
}
// std::cout << "matrix_dimensions: " << matrix_dimensions << "\n";
Block_Info block_info(matrix_dimensions, parameters.procs_per_node,
parameters.proc_granularity, parameters.verbosity);
El::Grid grid(block_info.mpi_comm.value);
std::vector<El::BigFloat> prefactors;
prefactors.reserve(num_constraints);
std::vector<std::vector<El::BigFloat>> primal_objective_c;
primal_objective_c.reserve(num_constraints);
std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
free_var_matrix.reserve(num_constraints);
// TODO: This is duplicated from sdp2input/write_output/write_output.cxx
auto max_normalization(normalization.begin());
for(auto n(normalization.begin()); n != normalization.end(); ++n)
{
if(Abs(*n) > Abs(*max_normalization))
{
max_normalization = n;
}
}
int64_t max_index(
std::distance(normalization.begin(), max_normalization));
for(size_t block(0); block != num_blocks; ++block)
{
for(auto &x : points.at(block))
{
if(x == infinity)
{
prefactors.push_back(1);
}
else
{
prefactors.push_back(
power_prefactor(matrices[block].damped_rational.base, x)
* poles_prefactor(matrices[block].damped_rational.poles,
x));
}
auto &prefactor(prefactors.back());
const size_t dim(matrices[block].polynomials.size());
free_var_matrix.emplace_back(
dim * (dim + 1) / 2,
matrices[block].polynomials.at(0).at(0).size() - 1);
auto &free_var(free_var_matrix.back());
primal_objective_c.emplace_back();
auto &primal(primal_objective_c.back());
size_t flattened_matrix_row(0);
for(size_t matrix_row(0); matrix_row != dim; ++matrix_row)
for(size_t matrix_column(0); matrix_column <= matrix_row;
++matrix_column)
{
if(x == infinity)
{
int64_t max_degree(0);
for(auto &poly : matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column))
max_degree = std::max(max_degree, poly.degree());
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.degree()
< max_degree)
{
primal.push_back(0);
}
else
{
primal.push_back(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)
.coefficients.at(max_degree)
/ normalization.at(max_index));
}
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
if(matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.degree()
< max_degree)
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index);
}
else
{
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)
.coefficients.at(max_degree);
}
}
}
else
{
primal.push_back(prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(max_index)(x)
/ normalization.at(max_index));
auto &primal_constant(primal.back());
for(int64_t column(0); column != free_var.Width();
++column)
{
const int64_t index(
column + (column < max_index ? 0 : 1));
free_var(flattened_matrix_row, column)
= primal_constant * normalization.at(index)
- prefactor
* matrices[block]
.polynomials.at(matrix_row)
.at(matrix_column)
.at(index)(x);
}
}
++flattened_matrix_row;
}
}
}
SDP sdp(objectives, normalization, prefactors, primal_objective_c,
free_var_matrix, block_info, grid);
SDP_Solver solver(parameters, block_info, grid,
sdp.dual_objective_b.Height());
for(auto &block : solver.y.blocks)
{
if(block.GlobalCol(0) == 0)
{
for(int64_t row(0); row != block.LocalHeight(); ++row)
{
int64_t global_row(block.GlobalRow(row));
const int64_t index(global_row
+ (global_row < max_index ? 0 : 1));
block.SetLocal(row, 0, weights.at(index));
}
}
}
Timers timers(parameters.verbosity >= Verbosity::debug);
SDP_Solver_Terminate_Reason reason
= solver.run(parameters, block_info, sdp, grid, timers);
if(reason != SDP_Solver_Terminate_Reason::PrimalDualOptimal)
{
std::stringstream ss;
ss << "Can not find solution: " << reason;
throw std::runtime_error(ss.str());
}
// y is duplicated among cores, so only need to print out copy on
// the root node.
// THe weight at max_index is determined by the normalization condition
// dot(norm,weights)=1
weights.at(max_index) = 1;
for(int64_t block_row(0); block_row != solver.y.blocks.at(0).Height();
++block_row)
{
const int64_t index(block_row + (block_row < max_index ? 0 : 1));
weights.at(index) = solver.y.blocks.at(0).Get(block_row, 0);
weights.at(max_index) -= weights.at(index) * normalization.at(index);
}
weights.at(max_index) /= normalization.at(max_index);
if(El::mpi::Rank() == 0)
{
std::cout.precision(10);
std::cout << "weight: " << weights << "\n";
El::BigFloat optimal(0);
for(size_t index(0); index < objectives.size(); ++index)
{
optimal += objectives[index] * weights[index];
}
std::cout << "optimal: " << optimal << "\n";
}
for(size_t block(0); block != num_blocks; ++block)
{
// 0.01 should be a small enough relative error so that we are
// in the regime of convergence. Then the error estimates will
// work
// Mesh mesh(*(points.at(block).begin()), *(points.at(block).rbegin()),
Mesh mesh(*(points.at(block).begin()), El::BigFloat(100),
[&](const El::BigFloat &x) {
return eval_weighted(matrices[block], x, weights);
},
0.01);
new_points.at(block) = get_new_points(mesh);
for(auto &point : new_points.at(block))
{
has_new_points
= has_new_points || (points.at(block).count(point) == 0);
}
}
}
// if(El::mpi::Rank() == 0)
// {
// std::cout << "weights: " << weights << "\n";
// }
return weights;
}
<|endoftext|> |
<commit_before>#ifdef _CARTO_ROUTING_SUPPORT
#include "CartoOnlineRoutingService.h"
#include "components/Exceptions.h"
#include "projections/Projection.h"
#include "routing/RoutingProxy.h"
#include "network/HTTPClient.h"
#include "utils/Log.h"
#include "utils/PlatformUtils.h"
#include "utils/NetworkUtils.h"
#include <boost/lexical_cast.hpp>
namespace carto {
CartoOnlineRoutingService::CartoOnlineRoutingService(const std::string& source) :
_source(source)
{
}
CartoOnlineRoutingService::~CartoOnlineRoutingService() {
}
std::shared_ptr<RoutingResult> CartoOnlineRoutingService::calculateRoute(const std::shared_ptr<RoutingRequest>& request) const {
if (!request) {
throw NullArgumentException("Null request");
}
std::shared_ptr<Projection> proj = request->getProjection();
std::string baseURL = ROUTING_SERVICE_URL + NetworkUtils::URLEncode(_source) + "/1/viaroute?instructions=true&alt=false&geometry=true&output=json";
for (const MapPos& pos : request->getPoints()) {
MapPos wgsPos = proj->toWgs84(pos);
baseURL += "&loc=" + boost::lexical_cast<std::string>(wgsPos.getY()) + "," + boost::lexical_cast<std::string>(wgsPos.getX());
}
std::map<std::string, std::string> params;
// TODO: temporarly remove additional parameters from the query as OSRM barks at these
// params["appId"] = PlatformUtils::GetAppIdentifier();
// params["deviceId"] = PlatformUtils::GetDeviceId();
// params["platform"] = PlatformUtils::GetPlatformId();
// params["sdk_build"] = _CARTO_MOBILE_SDK_VERSION;
std::string url = NetworkUtils::BuildURLFromParameters(baseURL, params);
Log::Debugf("CartoOnlineRoutingService::calculateRoute: Loading %s", url.c_str());
HTTPClient httpClient(Log::IsShowDebug());
return RoutingProxy::CalculateRoute(httpClient, url, request);
}
const std::string CartoOnlineRoutingService::ROUTING_SERVICE_URL = "http://api-staging.nutiteq.com/routing/v2/";
}
#endif
<commit_msg>Include appToken when accessing OSRM service<commit_after>#ifdef _CARTO_ROUTING_SUPPORT
#include "CartoOnlineRoutingService.h"
#include "components/Exceptions.h"
#include "components/LicenseManager.h"
#include "projections/Projection.h"
#include "routing/RoutingProxy.h"
#include "network/HTTPClient.h"
#include "utils/Log.h"
#include "utils/PlatformUtils.h"
#include "utils/NetworkUtils.h"
#include <boost/lexical_cast.hpp>
namespace carto {
CartoOnlineRoutingService::CartoOnlineRoutingService(const std::string& source) :
_source(source)
{
}
CartoOnlineRoutingService::~CartoOnlineRoutingService() {
}
std::shared_ptr<RoutingResult> CartoOnlineRoutingService::calculateRoute(const std::shared_ptr<RoutingRequest>& request) const {
if (!request) {
throw NullArgumentException("Null request");
}
std::shared_ptr<Projection> proj = request->getProjection();
std::string baseURL = ROUTING_SERVICE_URL + NetworkUtils::URLEncode(_source) + "/1/viaroute?instructions=true&alt=false&geometry=true&output=json";
for (const MapPos& pos : request->getPoints()) {
MapPos wgsPos = proj->toWgs84(pos);
baseURL += "&loc=" + boost::lexical_cast<std::string>(wgsPos.getY()) + "," + boost::lexical_cast<std::string>(wgsPos.getX());
}
std::map<std::string, std::string> params;
params["appId"] = PlatformUtils::GetAppIdentifier();
params["deviceId"] = PlatformUtils::GetDeviceId();
params["platform"] = PlatformUtils::GetPlatformId();
params["sdk_build"] = _CARTO_MOBILE_SDK_VERSION;
std::string appToken;
if (LicenseManager::GetInstance().getParameter("appToken", appToken)) {
params["appToken"] = appToken;
}
std::string url = NetworkUtils::BuildURLFromParameters(baseURL, params);
Log::Debugf("CartoOnlineRoutingService::calculateRoute: Loading %s", url.c_str());
HTTPClient httpClient(Log::IsShowDebug());
return RoutingProxy::CalculateRoute(httpClient, url, request);
}
const std::string CartoOnlineRoutingService::ROUTING_SERVICE_URL = "http://api-staging.nutiteq.com/routing/v2/";
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CustomAnimationPreset.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2006-11-27 09:39:18 $
*
* 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 _SD_CUSTOMANIMATIONPRESET_HXX
#define _SD_CUSTOMANIMATIONPRESET_HXX
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_ANIMATIONNODETYPE_HPP_
#include <com/sun/star/animations/AnimationNodeType.hpp>
#endif
#ifndef _UTL_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _SD_CUSTOMANIMATIONEFFECT_HXX
#include <CustomAnimationEffect.hxx>
#endif
#include <hash_map>
namespace sd {
typedef std::hash_map<rtl::OUString, CustomAnimationEffectPtr, comphelper::UStringHash, comphelper::UStringEqual> EffectsSubTypeMap;
typedef std::hash_map<rtl::OUString, rtl::OUString, comphelper::UStringHash, comphelper::UStringEqual> UStringMap;
typedef std::vector< rtl::OUString > UStringList;
class CustomAnimationPreset
{
friend class CustomAnimationPresets;
public:
CustomAnimationPreset( CustomAnimationEffectPtr pEffect );
void add( CustomAnimationEffectPtr pEffect );
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > create( const rtl::OUString& rstrSubType );
const rtl::OUString& getPresetId() const { return maPresetId; }
const rtl::OUString& getProperty() const { return maProperty; }
const rtl::OUString& getLabel() const { return maLabel; }
sal_Int16 getPresetClass() const { return mnPresetClass; }
double getDuration() const { return mfDuration; }
UStringList getSubTypes();
UStringList getProperties() const;
bool hasProperty( const rtl::OUString& rProperty ) const;
bool isTextOnly() const { return mbIsTextOnly; }
private:
rtl::OUString maPresetId;
rtl::OUString maProperty;
sal_Int16 mnPresetClass;
rtl::OUString maLabel;
rtl::OUString maDefaultSubTyp;
double mfDuration;
bool mbIsTextOnly;
EffectsSubTypeMap maSubTypes;
};
typedef boost::shared_ptr< CustomAnimationPreset > CustomAnimationPresetPtr;
typedef std::hash_map<rtl::OUString, CustomAnimationPresetPtr, comphelper::UStringHash, comphelper::UStringEqual> EffectDescriptorMap;
typedef std::vector< CustomAnimationPresetPtr > EffectDescriptorList;
struct PresetCategory
{
rtl::OUString maLabel;
EffectDescriptorList maEffects;
PresetCategory( const rtl::OUString& rLabel, const EffectDescriptorList& rEffects )
: maLabel( rLabel ), maEffects( rEffects ) {}
};
typedef boost::shared_ptr< PresetCategory > PresetCategoryPtr;
typedef std::vector< PresetCategoryPtr > PresetCategoryList;
class CustomAnimationPresets
{
public:
CustomAnimationPresets();
virtual ~CustomAnimationPresets();
void init();
static const CustomAnimationPresets& getCustomAnimationPresets();
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > getRandomPreset( sal_Int16 nPresetClass ) const;
CustomAnimationPresetPtr getEffectDescriptor( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId, const rtl::OUString& rPresetSubType ) const;
const rtl::OUString& getUINameForPresetId( const rtl::OUString& rPresetId ) const;
const rtl::OUString& getUINameForProperty( const rtl::OUString& rProperty ) const;
const PresetCategoryList& getEntrancePresets() const { return maEntrancePresets; }
const PresetCategoryList& getEmphasisPresets() const { return maEmphasisPresets; }
const PresetCategoryList& getExitPresets() const { return maExitPresets; }
const PresetCategoryList& getMotionPathsPresets() const { return maMotionPathsPresets; }
void changePresetSubType( CustomAnimationEffectPtr pEffect, const rtl::OUString& rPresetSubType ) const;
private:
void importEffects();
void importResources();
void importPresets( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xConfigProvider, const rtl::OUString& rNodePath, PresetCategoryList& rPresetMap );
const rtl::OUString& translateName( const rtl::OUString& rId, const UStringMap& rNameMap ) const;
private:
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxRootNode;
EffectDescriptorMap maEffectDiscriptorMap;
UStringMap maEffectNameMap;
UStringMap maPropertyNameMap;
PresetCategoryList maEntrancePresets;
PresetCategoryList maEmphasisPresets;
PresetCategoryList maExitPresets;
PresetCategoryList maMotionPathsPresets;
static CustomAnimationPresets* mpCustomAnimationPresets;
};
typedef boost::shared_ptr< CustomAnimationPresets > CustomAnimationPresetsPtr;
}
#endif // _SD_CUSTOMANIMATIONEFFECTS_HXX
<commit_msg>INTEGRATION: CWS fwk56 (1.3.332); FILE MERGED 2006/12/05 11:52:22 mav 1.3.332.1: fix build problem on solaris<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CustomAnimationPreset.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2006-12-19 13:56:06 $
*
* 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 _SD_CUSTOMANIMATIONPRESET_HXX
#define _SD_CUSTOMANIMATIONPRESET_HXX
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_ANIMATIONNODETYPE_HPP_
#include <com/sun/star/animations/AnimationNodeType.hpp>
#endif
#ifndef _UTL_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _SD_CUSTOMANIMATIONEFFECT_HXX
#include <CustomAnimationEffect.hxx>
#endif
#include <hash_map>
namespace sd {
typedef std::hash_map< rtl::OUString, CustomAnimationEffectPtr, comphelper::UStringHash, comphelper::UStringEqual > EffectsSubTypeMap;
typedef std::hash_map< rtl::OUString, rtl::OUString, comphelper::UStringHash, comphelper::UStringEqual > UStringMap;
typedef std::vector< rtl::OUString > UStringList;
class CustomAnimationPreset
{
friend class CustomAnimationPresets;
public:
CustomAnimationPreset( CustomAnimationEffectPtr pEffect );
void add( CustomAnimationEffectPtr pEffect );
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > create( const rtl::OUString& rstrSubType );
const rtl::OUString& getPresetId() const { return maPresetId; }
const rtl::OUString& getProperty() const { return maProperty; }
const rtl::OUString& getLabel() const { return maLabel; }
sal_Int16 getPresetClass() const { return mnPresetClass; }
double getDuration() const { return mfDuration; }
UStringList getSubTypes();
UStringList getProperties() const;
bool hasProperty( const rtl::OUString& rProperty ) const;
bool isTextOnly() const { return mbIsTextOnly; }
private:
rtl::OUString maPresetId;
rtl::OUString maProperty;
sal_Int16 mnPresetClass;
rtl::OUString maLabel;
rtl::OUString maDefaultSubTyp;
double mfDuration;
bool mbIsTextOnly;
EffectsSubTypeMap maSubTypes;
};
typedef boost::shared_ptr< CustomAnimationPreset > CustomAnimationPresetPtr;
typedef std::hash_map<rtl::OUString, CustomAnimationPresetPtr, comphelper::UStringHash, comphelper::UStringEqual> EffectDescriptorMap;
typedef std::vector< CustomAnimationPresetPtr > EffectDescriptorList;
struct PresetCategory
{
rtl::OUString maLabel;
EffectDescriptorList maEffects;
PresetCategory( const rtl::OUString& rLabel, const EffectDescriptorList& rEffects )
: maLabel( rLabel ), maEffects( rEffects ) {}
};
typedef boost::shared_ptr< PresetCategory > PresetCategoryPtr;
typedef std::vector< PresetCategoryPtr > PresetCategoryList;
class CustomAnimationPresets
{
public:
CustomAnimationPresets();
virtual ~CustomAnimationPresets();
void init();
static const CustomAnimationPresets& getCustomAnimationPresets();
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > getRandomPreset( sal_Int16 nPresetClass ) const;
CustomAnimationPresetPtr getEffectDescriptor( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId, const rtl::OUString& rPresetSubType ) const;
const rtl::OUString& getUINameForPresetId( const rtl::OUString& rPresetId ) const;
const rtl::OUString& getUINameForProperty( const rtl::OUString& rProperty ) const;
const PresetCategoryList& getEntrancePresets() const { return maEntrancePresets; }
const PresetCategoryList& getEmphasisPresets() const { return maEmphasisPresets; }
const PresetCategoryList& getExitPresets() const { return maExitPresets; }
const PresetCategoryList& getMotionPathsPresets() const { return maMotionPathsPresets; }
void changePresetSubType( CustomAnimationEffectPtr pEffect, const rtl::OUString& rPresetSubType ) const;
private:
void importEffects();
void importResources();
void importPresets( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xConfigProvider, const rtl::OUString& rNodePath, PresetCategoryList& rPresetMap );
const rtl::OUString& translateName( const rtl::OUString& rId, const UStringMap& rNameMap ) const;
private:
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxRootNode;
EffectDescriptorMap maEffectDiscriptorMap;
UStringMap maEffectNameMap;
UStringMap maPropertyNameMap;
PresetCategoryList maEntrancePresets;
PresetCategoryList maEmphasisPresets;
PresetCategoryList maExitPresets;
PresetCategoryList maMotionPathsPresets;
static CustomAnimationPresets* mpCustomAnimationPresets;
};
typedef boost::shared_ptr< CustomAnimationPresets > CustomAnimationPresetsPtr;
}
#endif // _SD_CUSTOMANIMATIONEFFECTS_HXX
<|endoftext|> |
<commit_before>#include "Utility/Random.h"
#include <random>
#include <string>
double Random::random_laplace(double width) noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using ed = std::exponential_distribution<double>;
thread_local static auto dist = ed{};
return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0/width});
}
double Random::random_real(double min, double max) noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using urd = std::uniform_real_distribution<double>;
thread_local static auto dist = urd{};
return dist(generator, urd::param_type{min, max});
}
uint64_t Random::random_unsigned_int64() noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
thread_local static std::uniform_int_distribution<uint64_t> dist;
return dist(generator);
}
bool Random::coin_flip() noexcept
{
return random_integer(0, 1) == 1;
}
bool Random::success_probability(size_t successes, size_t attempts) noexcept
{
return random_integer({1}, attempts) <= successes;
}
std::string Random::random_string(size_t size) noexcept
{
std::string s;
while(s.size() < size)
{
s.push_back('a' + random_integer(0, 25));
}
return s;
}
<commit_msg>Make type explicit<commit_after>#include "Utility/Random.h"
#include <random>
#include <string>
double Random::random_laplace(double width) noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using ed = std::exponential_distribution<double>;
thread_local static auto dist = ed{};
return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0/width});
}
double Random::random_real(double min, double max) noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
using urd = std::uniform_real_distribution<double>;
thread_local static auto dist = urd{};
return dist(generator, urd::param_type{min, max});
}
uint64_t Random::random_unsigned_int64() noexcept
{
thread_local static std::mt19937_64 generator(std::random_device{}());
thread_local static std::uniform_int_distribution<uint64_t> dist;
return dist(generator);
}
bool Random::coin_flip() noexcept
{
return random_integer(0, 1) == 1;
}
bool Random::success_probability(size_t successes, size_t attempts) noexcept
{
return random_integer(size_t{1}, attempts) <= successes;
}
std::string Random::random_string(size_t size) noexcept
{
std::string s;
while(s.size() < size)
{
s.push_back('a' + random_integer(0, 25));
}
return s;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2022 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CaptureServiceBase/CaptureServiceBase.h"
#include <absl/time/time.h>
#include "CaptureServiceBase/CommonProducerCaptureEventBuilders.h"
#include "GrpcProtos/Constants.h"
#include "OrbitBase/Logging.h"
using orbit_grpc_protos::CaptureOptions;
using orbit_grpc_protos::ProducerCaptureEvent;
using orbit_producer_event_processor::ClientCaptureEventCollector;
using orbit_producer_event_processor::ProducerEventProcessor;
namespace orbit_capture_service_base {
void CaptureServiceBase::AddCaptureStartStopListener(CaptureStartStopListener* listener) {
bool new_insertion = capture_start_stop_listeners_.insert(listener).second;
ORBIT_CHECK(new_insertion);
}
void CaptureServiceBase::RemoveCaptureStartStopListener(CaptureStartStopListener* listener) {
bool was_removed = capture_start_stop_listeners_.erase(listener) > 0;
ORBIT_CHECK(was_removed);
}
CaptureServiceBase::CaptureInitializationResult CaptureServiceBase::InitializeCapture(
ClientCaptureEventCollector* client_capture_event_collector) {
ORBIT_CHECK(client_capture_event_collector != nullptr);
{
absl::MutexLock lock(&capture_mutex_);
if (is_capturing_) {
return CaptureInitializationResult::kAlreadyInProgress;
}
is_capturing_ = true;
}
client_capture_event_collector_ = client_capture_event_collector;
producer_event_processor_ = ProducerEventProcessor::Create(client_capture_event_collector_);
return CaptureInitializationResult::kSuccess;
}
void CaptureServiceBase::TerminateCapture() {
producer_event_processor_.reset();
client_capture_event_collector_ = nullptr;
capture_start_timestamp_ns_ = 0;
absl::MutexLock lock(&capture_mutex_);
is_capturing_ = false;
}
void CaptureServiceBase::StartEventProcessing(const CaptureOptions& capture_options) {
// These are not in precise sync but they do not have to be.
absl::Time capture_start_time = absl::Now();
capture_start_timestamp_ns_ = orbit_base::CaptureTimestampNs();
producer_event_processor_->ProcessEvent(
orbit_grpc_protos::kRootProducerId,
CreateCaptureStartedEvent(capture_options, capture_start_time, capture_start_timestamp_ns_));
producer_event_processor_->ProcessEvent(
orbit_grpc_protos::kRootProducerId,
CreateClockResolutionEvent(capture_start_timestamp_ns_, clock_resolution_ns_));
}
void CaptureServiceBase::FinalizeEventProcessing(StopCaptureReason stop_capture_reason) {
ProducerCaptureEvent capture_finished;
switch (stop_capture_reason) {
case StopCaptureReason::kClientStop:
case StopCaptureReason::kGuestOrcStop:
capture_finished = CreateSuccessfulCaptureFinishedEvent();
break;
case StopCaptureReason::kMemoryWatchdog:
capture_finished =
CreateInterruptedByServiceCaptureFinishedEvent("OrbitService was using too much memory.");
break;
case StopCaptureReason::kExceededMaxDurationLimit:
capture_finished = CreateInterruptedByServiceCaptureFinishedEvent(
"Capture duration exceeded the maximum duration limit.");
break;
case StopCaptureReason::kGuestOrcConnectionFailure:
capture_finished = CreateFailedCaptureFinishedEvent("Connection with GuestOrc failed.");
break;
}
producer_event_processor_->ProcessEvent(orbit_grpc_protos::kRootProducerId,
std::move(capture_finished));
client_capture_event_collector_->StopAndWait();
ORBIT_LOG("Finished processing CaptureFinisedEvent");
}
} // namespace orbit_capture_service_base
<commit_msg>Fix comment typo in CaptureServiceBase.cpp<commit_after>// Copyright (c) 2022 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CaptureServiceBase/CaptureServiceBase.h"
#include <absl/time/time.h>
#include "CaptureServiceBase/CommonProducerCaptureEventBuilders.h"
#include "GrpcProtos/Constants.h"
#include "OrbitBase/Logging.h"
using orbit_grpc_protos::CaptureOptions;
using orbit_grpc_protos::ProducerCaptureEvent;
using orbit_producer_event_processor::ClientCaptureEventCollector;
using orbit_producer_event_processor::ProducerEventProcessor;
namespace orbit_capture_service_base {
void CaptureServiceBase::AddCaptureStartStopListener(CaptureStartStopListener* listener) {
bool new_insertion = capture_start_stop_listeners_.insert(listener).second;
ORBIT_CHECK(new_insertion);
}
void CaptureServiceBase::RemoveCaptureStartStopListener(CaptureStartStopListener* listener) {
bool was_removed = capture_start_stop_listeners_.erase(listener) > 0;
ORBIT_CHECK(was_removed);
}
CaptureServiceBase::CaptureInitializationResult CaptureServiceBase::InitializeCapture(
ClientCaptureEventCollector* client_capture_event_collector) {
ORBIT_CHECK(client_capture_event_collector != nullptr);
{
absl::MutexLock lock(&capture_mutex_);
if (is_capturing_) {
return CaptureInitializationResult::kAlreadyInProgress;
}
is_capturing_ = true;
}
client_capture_event_collector_ = client_capture_event_collector;
producer_event_processor_ = ProducerEventProcessor::Create(client_capture_event_collector_);
return CaptureInitializationResult::kSuccess;
}
void CaptureServiceBase::TerminateCapture() {
producer_event_processor_.reset();
client_capture_event_collector_ = nullptr;
capture_start_timestamp_ns_ = 0;
absl::MutexLock lock(&capture_mutex_);
is_capturing_ = false;
}
void CaptureServiceBase::StartEventProcessing(const CaptureOptions& capture_options) {
// These are not in precise sync but they do not have to be.
absl::Time capture_start_time = absl::Now();
capture_start_timestamp_ns_ = orbit_base::CaptureTimestampNs();
producer_event_processor_->ProcessEvent(
orbit_grpc_protos::kRootProducerId,
CreateCaptureStartedEvent(capture_options, capture_start_time, capture_start_timestamp_ns_));
producer_event_processor_->ProcessEvent(
orbit_grpc_protos::kRootProducerId,
CreateClockResolutionEvent(capture_start_timestamp_ns_, clock_resolution_ns_));
}
void CaptureServiceBase::FinalizeEventProcessing(StopCaptureReason stop_capture_reason) {
ProducerCaptureEvent capture_finished;
switch (stop_capture_reason) {
case StopCaptureReason::kClientStop:
case StopCaptureReason::kGuestOrcStop:
capture_finished = CreateSuccessfulCaptureFinishedEvent();
break;
case StopCaptureReason::kMemoryWatchdog:
capture_finished =
CreateInterruptedByServiceCaptureFinishedEvent("OrbitService was using too much memory.");
break;
case StopCaptureReason::kExceededMaxDurationLimit:
capture_finished = CreateInterruptedByServiceCaptureFinishedEvent(
"Capture duration exceeded the maximum duration limit.");
break;
case StopCaptureReason::kGuestOrcConnectionFailure:
capture_finished = CreateFailedCaptureFinishedEvent("Connection with GuestOrc failed.");
break;
}
producer_event_processor_->ProcessEvent(orbit_grpc_protos::kRootProducerId,
std::move(capture_finished));
client_capture_event_collector_->StopAndWait();
ORBIT_LOG("Finished processing CaptureFinishedEvent");
}
} // namespace orbit_capture_service_base
<|endoftext|> |
<commit_before>#include "addressbookdialog.h"
#include "ui_addressbookdialog.h"
#include "addresstablemodel.h"
#include "editaddressdialog.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QDebug>
AddressBookDialog::AddressBookDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookDialog),
model(0)
{
ui->setupUi(this);
switch(mode)
{
case ForSending:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
break;
case ForEditing:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
break;
}
}
AddressBookDialog::~AddressBookDialog()
{
delete ui;
}
void AddressBookDialog::setModel(AddressTableModel *model)
{
this->model = model;
// Refresh list from core
model->updateList();
// Receive filter
QSortFilterProxyModel *receive_model = new QSortFilterProxyModel(this);
receive_model->setSourceModel(model);
receive_model->setDynamicSortFilter(true);
receive_model->setFilterRole(AddressTableModel::TypeRole);
receive_model->setFilterFixedString(AddressTableModel::Receive);
ui->receiveTableView->setModel(receive_model);
// Send filter
QSortFilterProxyModel *send_model = new QSortFilterProxyModel(this);
send_model->setSourceModel(model);
send_model->setDynamicSortFilter(true);
send_model->setFilterRole(AddressTableModel::TypeRole);
send_model->setFilterFixedString(AddressTableModel::Send);
ui->sendTableView->setModel(send_model);
// Set column widths
ui->receiveTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->receiveTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
ui->sendTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->sendTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
}
void AddressBookDialog::setTab(int tab)
{
ui->tabWidget->setCurrentIndex(tab);
}
QTableView *AddressBookDialog::getCurrentTable()
{
switch(ui->tabWidget->currentIndex())
{
case SendingTab:
return ui->sendTableView;
case ReceivingTab:
return ui->receiveTableView;
default:
return 0;
}
}
void AddressBookDialog::on_copyToClipboard_clicked()
{
// Copy currently selected address to clipboard
// (or nothing, if nothing selected)
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
QApplication::clipboard()->setText(address.toString());
}
}
void AddressBookDialog::on_editButton_clicked()
{
QModelIndexList indexes = getCurrentTable()->selectionModel()->selectedRows();
if(indexes.isEmpty())
{
return;
}
// Map selected index to source address book model
QAbstractProxyModel *proxy_model = static_cast<QAbstractProxyModel*>(getCurrentTable()->model());
QModelIndex selected = proxy_model->mapToSource(indexes.at(0));
// Double click also triggers edit button
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress);
dlg.setModel(model);
dlg.loadRow(selected.row());
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_newAddressButton_clicked()
{
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress);
dlg.setModel(model);
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_tabWidget_currentChanged(int index)
{
// Enable/disable buttons based on selected tab
switch(index)
{
case SendingTab:
ui->deleteButton->setEnabled(true);
break;
case ReceivingTab:
ui->deleteButton->setEnabled(false);
break;
}
}
void AddressBookDialog::on_deleteButton_clicked()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookDialog::on_buttonBox_accepted()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(!returnValue.isEmpty())
{
accept();
}
else
{
reject();
}
}
<commit_msg>fix issue #7<commit_after>#include "addressbookdialog.h"
#include "ui_addressbookdialog.h"
#include "addresstablemodel.h"
#include "editaddressdialog.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QDebug>
AddressBookDialog::AddressBookDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookDialog),
model(0)
{
ui->setupUi(this);
switch(mode)
{
case ForSending:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
break;
case ForEditing:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
break;
}
}
AddressBookDialog::~AddressBookDialog()
{
delete ui;
}
void AddressBookDialog::setModel(AddressTableModel *model)
{
this->model = model;
// Refresh list from core
model->updateList();
// Receive filter
QSortFilterProxyModel *receive_model = new QSortFilterProxyModel(this);
receive_model->setSourceModel(model);
receive_model->setDynamicSortFilter(true);
receive_model->setFilterRole(AddressTableModel::TypeRole);
receive_model->setFilterFixedString(AddressTableModel::Receive);
ui->receiveTableView->setModel(receive_model);
// Send filter
QSortFilterProxyModel *send_model = new QSortFilterProxyModel(this);
send_model->setSourceModel(model);
send_model->setDynamicSortFilter(true);
send_model->setFilterRole(AddressTableModel::TypeRole);
send_model->setFilterFixedString(AddressTableModel::Send);
ui->sendTableView->setModel(send_model);
// Set column widths
ui->receiveTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->receiveTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
ui->sendTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->sendTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
}
void AddressBookDialog::setTab(int tab)
{
ui->tabWidget->setCurrentIndex(tab);
on_tabWidget_currentChanged(tab);
}
QTableView *AddressBookDialog::getCurrentTable()
{
switch(ui->tabWidget->currentIndex())
{
case SendingTab:
return ui->sendTableView;
case ReceivingTab:
return ui->receiveTableView;
default:
return 0;
}
}
void AddressBookDialog::on_copyToClipboard_clicked()
{
// Copy currently selected address to clipboard
// (or nothing, if nothing selected)
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
QApplication::clipboard()->setText(address.toString());
}
}
void AddressBookDialog::on_editButton_clicked()
{
QModelIndexList indexes = getCurrentTable()->selectionModel()->selectedRows();
if(indexes.isEmpty())
{
return;
}
// Map selected index to source address book model
QAbstractProxyModel *proxy_model = static_cast<QAbstractProxyModel*>(getCurrentTable()->model());
QModelIndex selected = proxy_model->mapToSource(indexes.at(0));
// Double click also triggers edit button
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress);
dlg.setModel(model);
dlg.loadRow(selected.row());
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_newAddressButton_clicked()
{
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress);
dlg.setModel(model);
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_tabWidget_currentChanged(int index)
{
// Enable/disable buttons based on selected tab
switch(index)
{
case SendingTab:
ui->deleteButton->setEnabled(true);
break;
case ReceivingTab:
ui->deleteButton->setEnabled(false);
break;
}
}
void AddressBookDialog::on_deleteButton_clicked()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookDialog::on_buttonBox_accepted()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(!returnValue.isEmpty())
{
accept();
}
else
{
reject();
}
}
<|endoftext|> |
<commit_before>/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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.
*/
extern "C" {
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "zend_exceptions.h"
}
#include "Table.h"
#include "volttable.h"
// class entry used to instantiate the PHP table class
zend_class_entry *volttable_ce;
const zend_function_entry volttable_methods[] = {
PHP_ME(VoltTable, statusCode, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, rowCount, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, columnCount, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, hasMoreRows, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, nextRow, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END // Must be the last line
};
zend_object_handlers volttable_object_handlers;
void volttable_free(void *obj TSRMLS_CC)
{
volttable_object *table_obj = (volttable_object *)obj;
delete table_obj->table;
table_obj->table = NULL;
zend_hash_destroy(table_obj->std.properties);
FREE_HASHTABLE(table_obj->std.properties);
efree(table_obj);
}
zend_object_value volttable_create_handler(zend_class_entry *type TSRMLS_DC)
{
zval *tmp;
zend_object_value retval;
volttable_object *obj = (volttable_object *)emalloc(sizeof(volttable_object));
memset(obj, 0, sizeof(volttable_object));
obj->std.ce = type;
ALLOC_HASHTABLE(obj->std.properties);
zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_copy(obj->std.properties, &type->default_properties,
(copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));
retval.handle = zend_objects_store_put(obj, NULL,
volttable_free, NULL TSRMLS_CC);
retval.handlers = &volttable_object_handlers;
return retval;
}
void create_volttable_class(void)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "VoltTable", volttable_methods);
volttable_ce = zend_register_internal_class(&ce TSRMLS_CC);
volttable_ce->create_object = volttable_create_handler;
memcpy(&volttable_object_handlers,
zend_get_std_object_handlers(),
sizeof(zend_object_handlers));
volttable_object_handlers.clone_obj = NULL;
}
struct volttable_object *instantiate_volttable(zval *return_val, voltdb::Table &table)
{
struct volttable_object *to = NULL;
if (object_init_ex(return_val, volttable_ce) != SUCCESS) {
return NULL;
}
to = (struct volttable_object *)zend_object_store_get_object(return_val TSRMLS_CC);
assert(to != NULL);
to->table = new voltdb::Table(table);
to->it = to->table->iterator();
return to;
}
int row_to_array(zval *return_value, voltdb::Row row)
{
voltdb::errType err = voltdb::errOk;
int count = row.columnCount();
std::vector<voltdb::Column> columns = row.columns();
for (int i = 0; i < count; i++) {
std::string name = columns[i].name();
int name_len = name.length() + 1; // including the terminator
bool isNull = row.isNull(err, i);
if (!voltdb::isOk(err)) {
// TODO: Should we free the array?
return 0;
}
if (isNull) {
add_assoc_null_ex(return_value, name.c_str(), name_len);
} else {
switch (columns[i].type()) {
case voltdb::WIRE_TYPE_TINYINT:
{
int8_t value = row.getInt8(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_SMALLINT:
{
int16_t value = row.getInt16(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_INTEGER:
{
int32_t value = row.getInt32(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_BIGINT:
{
int64_t value = row.getInt64(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_FLOAT:
{
double value = row.getDouble(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_double_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_STRING:
{
std::string value = row.getString(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
/*
* necessary to dup here because the add_assoc_string_ex takes
* char*. No need to free it, PHP should take care of this when
* the refcount is decremented.
*/
char *dup_val = estrdup(value.c_str());
add_assoc_string_ex(return_value, name.c_str(), name_len, dup_val, 0);
break;
}
case voltdb::WIRE_TYPE_TIMESTAMP:
{
int64_t value = row.getTimestamp(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_DECIMAL:
{
voltdb::Decimal value = row.getDecimal(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
// TODO: get float
break;
}
case voltdb::WIRE_TYPE_VARBINARY:
{
// TODO: encode it and store it as a string?
break;
}
default:
return 0;
}
}
}
return 1;
}
PHP_METHOD(VoltTable, statusCode)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
RETURN_LONG(obj->table->getStatusCode());
}
PHP_METHOD(VoltTable, rowCount)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
RETURN_LONG(obj->table->rowCount());
}
PHP_METHOD(VoltTable, columnCount)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
RETURN_LONG(obj->table->columnCount());
}
PHP_METHOD(VoltTable, hasMoreRows)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
if (!obj->it.hasNext()) {
RETURN_FALSE;
} else {
RETURN_TRUE;
}
}
PHP_METHOD(VoltTable, nextRow)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
if (!obj->it.hasNext()) {
RETURN_NULL();
}
// Get the next row and advance the iterator
voltdb::errType err = voltdb::errOk;
voltdb::Row row = obj->it.next(err);
if (!voltdb::isOk(err)) {
zend_throw_exception(zend_exception_get_default(TSRMLS_C), NULL, err TSRMLS_CC);
RETURN_NULL();
}
// Convert the row into a PHP array
if (array_init(return_value) == FAILURE) {
zend_throw_exception(zend_exception_get_default(TSRMLS_C), NULL,
voltdb::errException TSRMLS_CC);
RETURN_NULL();
}
if (!row_to_array(return_value, row)) {
RETURN_NULL();
}
}
<commit_msg>Return decimals in result table as strings.<commit_after>/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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.
*/
extern "C" {
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "zend_exceptions.h"
}
#include "Table.h"
#include "volttable.h"
// class entry used to instantiate the PHP table class
zend_class_entry *volttable_ce;
const zend_function_entry volttable_methods[] = {
PHP_ME(VoltTable, statusCode, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, rowCount, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, columnCount, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, hasMoreRows, NULL, ZEND_ACC_PUBLIC)
PHP_ME(VoltTable, nextRow, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END // Must be the last line
};
zend_object_handlers volttable_object_handlers;
void volttable_free(void *obj TSRMLS_CC)
{
volttable_object *table_obj = (volttable_object *)obj;
delete table_obj->table;
table_obj->table = NULL;
zend_hash_destroy(table_obj->std.properties);
FREE_HASHTABLE(table_obj->std.properties);
efree(table_obj);
}
zend_object_value volttable_create_handler(zend_class_entry *type TSRMLS_DC)
{
zval *tmp;
zend_object_value retval;
volttable_object *obj = (volttable_object *)emalloc(sizeof(volttable_object));
memset(obj, 0, sizeof(volttable_object));
obj->std.ce = type;
ALLOC_HASHTABLE(obj->std.properties);
zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_copy(obj->std.properties, &type->default_properties,
(copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));
retval.handle = zend_objects_store_put(obj, NULL,
volttable_free, NULL TSRMLS_CC);
retval.handlers = &volttable_object_handlers;
return retval;
}
void create_volttable_class(void)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "VoltTable", volttable_methods);
volttable_ce = zend_register_internal_class(&ce TSRMLS_CC);
volttable_ce->create_object = volttable_create_handler;
memcpy(&volttable_object_handlers,
zend_get_std_object_handlers(),
sizeof(zend_object_handlers));
volttable_object_handlers.clone_obj = NULL;
}
struct volttable_object *instantiate_volttable(zval *return_val, voltdb::Table &table)
{
struct volttable_object *to = NULL;
if (object_init_ex(return_val, volttable_ce) != SUCCESS) {
return NULL;
}
to = (struct volttable_object *)zend_object_store_get_object(return_val TSRMLS_CC);
assert(to != NULL);
to->table = new voltdb::Table(table);
to->it = to->table->iterator();
return to;
}
int row_to_array(zval *return_value, voltdb::Row row)
{
voltdb::errType err = voltdb::errOk;
int count = row.columnCount();
std::vector<voltdb::Column> columns = row.columns();
for (int i = 0; i < count; i++) {
std::string name = columns[i].name();
int name_len = name.length() + 1; // including the terminator
bool isNull = row.isNull(err, i);
if (!voltdb::isOk(err)) {
// TODO: Should we free the array?
return 0;
}
if (isNull) {
add_assoc_null_ex(return_value, name.c_str(), name_len);
} else {
switch (columns[i].type()) {
case voltdb::WIRE_TYPE_TINYINT:
{
int8_t value = row.getInt8(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_SMALLINT:
{
int16_t value = row.getInt16(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_INTEGER:
{
int32_t value = row.getInt32(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_BIGINT:
{
int64_t value = row.getInt64(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_FLOAT:
{
double value = row.getDouble(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_double_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_STRING:
{
std::string value = row.getString(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
/*
* necessary to dup here because the add_assoc_string_ex takes
* char*. No need to free it, PHP should take care of this when
* the refcount is decremented.
*/
char *dup_val = estrdup(value.c_str());
add_assoc_string_ex(return_value, name.c_str(), name_len, dup_val, 0);
break;
}
case voltdb::WIRE_TYPE_TIMESTAMP:
{
int64_t value = row.getTimestamp(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
add_assoc_long_ex(return_value, name.c_str(), name_len, value);
break;
}
case voltdb::WIRE_TYPE_DECIMAL:
{
voltdb::Decimal value = row.getDecimal(err, i);
if (!voltdb::isOk(err)) {
return 0;
}
/*
* return decimal as a string. PHP float doesn't have enough
* precision to hold a SQL decimal
*/
char *dup_val = estrdup(value.toString().c_str());
add_assoc_string_ex(return_value, name.c_str(), name_len, dup_val, 0);
break;
}
case voltdb::WIRE_TYPE_VARBINARY:
{
// TODO: encode it and store it as a string?
break;
}
default:
return 0;
}
}
}
return 1;
}
PHP_METHOD(VoltTable, statusCode)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
RETURN_LONG(obj->table->getStatusCode());
}
PHP_METHOD(VoltTable, rowCount)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
RETURN_LONG(obj->table->rowCount());
}
PHP_METHOD(VoltTable, columnCount)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
RETURN_LONG(obj->table->columnCount());
}
PHP_METHOD(VoltTable, hasMoreRows)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
if (!obj->it.hasNext()) {
RETURN_FALSE;
} else {
RETURN_TRUE;
}
}
PHP_METHOD(VoltTable, nextRow)
{
zval *zobj = getThis();
volttable_object *obj = (volttable_object *)zend_object_store_get_object(zobj TSRMLS_CC);
if (!obj->it.hasNext()) {
RETURN_NULL();
}
// Get the next row and advance the iterator
voltdb::errType err = voltdb::errOk;
voltdb::Row row = obj->it.next(err);
if (!voltdb::isOk(err)) {
zend_throw_exception(zend_exception_get_default(TSRMLS_C), NULL, err TSRMLS_CC);
RETURN_NULL();
}
// Convert the row into a PHP array
if (array_init(return_value) == FAILURE) {
zend_throw_exception(zend_exception_get_default(TSRMLS_C), NULL,
voltdb::errException TSRMLS_CC);
RETURN_NULL();
}
if (!row_to_array(return_value, row)) {
RETURN_NULL();
}
}
<|endoftext|> |
<commit_before>#ifndef _MSP_UART_HPP
#define _MSP_UART_HPP
#include "mcu_uart.hpp"
#include "msp_periph.hpp"
#include "utilities/utilities.hpp"
#include <stdint.h>
#include <msp430.h>
#include "msp_sys.hpp"
#include "msp_gpio.hpp"
#include "utilities/circfifo.hpp"
#include <math.h>
#include "msp430/msp_periph.hpp"
namespace McuPeripheral
{
enum class UartClockSource : uint8_t { SMCLK = UCSSEL_2, ACLK = UCSSEL_1 };
template< class _rxpin, class _txpin, class _irq, uint8_t _ctl0, uint8_t _iflag, uint8_t _txflag, uint8_t _rxflag>
class UartControl
{
public:
static void queueByte(const uint8_t data)
{
if(_irq::isInterrupt()) {
while(false == _irq::mTxBuffer.push(data));
_irq::enableTxInterrupt();
}
else {
loadTxReg(data);
}
}
static bool readByte(uint8_t& data)
{
if(_irq::isInterrupt()) {
return _irq::mRxBuffer.pop(data);
}
else {
return readRxReg(data);
}
}
static const void loadTxReg(const uint8_t data)
{
//Ensure we are ready
while (!(REG_8(_iflag) & _txflag));
REG_8(txbuf) = data;
while (!(REG_8(_iflag) & _txflag));
}
static const bool readRxReg(uint8_t& data)
{
bool ret = false;
if((REG_8(_iflag) & _rxflag)) {
data = REG_8(rxbuf);
ret = true;
}
return ret;
}
static void init(const uint8_t baudRate, uint8_t mod, UartClockSource source )
{
_rxpin::input(); _rxpin::selectOn(); _rxpin::select2On();
_txpin::output(); _txpin::selectOn(); _txpin::select2On();
REG_8(ctl1) |= UCSWRST;
REG_8(ctl0) |= UCMODE_0;
REG_8(br0) = baudRate;
REG_8(mctl) = mod;
REG_8(ctl1) |= static_cast<uint8_t>(source);
REG_8(ctl1) &= ~UCSWRST;
_irq::init();
_irq::mRxBuffer.init();
_irq::mTxBuffer.init();
_irq::enableRxInterrupt();
}
private:
static constexpr uint8_t ctl0 = _ctl0;
static constexpr uint8_t ctl1 = ctl0 + 1;
static constexpr uint8_t br0 = ctl1 +1;
static constexpr uint8_t br1 = br0 +1;
static constexpr uint8_t mctl = br1 +1;
static constexpr uint8_t stat = mctl +1;
static constexpr uint8_t rxbuf = stat +1;
static constexpr uint8_t txbuf = rxbuf +1;
};
//This macro is returning the number of arguments based on the placeholder N
//example is _VA_ARGS__ is 3 arguments that takes up _1,_2_3, then _4 through _8
//are taken up by 8-4 in the arguments returning 3.
#define VA_NARGS_IMPL(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define VA_NARGS(...) VA_NARGS_IMPL(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)
#define VARARG_IMPL2(base, count, ...) base##count(__VA_ARGS__)
#define VARARG_IMPL(base, count, ...) VARARG_IMPL2(base, count, __VA_ARGS__)
#define VARARG(base, ...) VARARG_IMPL(base, VA_NARGS(__VA_ARGS__), __VA_ARGS__)
#define PRINT(...) VARARG(Print,__VA_ARGS__)
#define Print1(_1) \
uart::send(_1);
#define Print2(_1,_2) \
Print1(_1) Print1(_2)
#define Print3(_1,_2,_3) \
Print1(_1) Print2(_2,_3)
#define Print4(_1,_2,_3,_4) \
Print1(_1) Print3(_2,_3,_4)
#define Print5(_1,_2,_3,_4,_5) \
Print1(_1) Print4(_2,_3,_4,_5)
#define Print6(_1,_2,_3,_4,_5,_6) \
Print1(_1) Print5(_2,_3,_4,_5,_6)
#define Print7(_1,_2,_3,_4,_5,_6,_7) \
Print1(_1) Print6(_2,_3,_4,_5,_6,_7)
#define Print8(_1,_2,_3,_4,_5,_6,_7,_8) \
Print1(_1) Print7(_2,_3,_4,_5,_6,_7,_8)
#define ENDL "\n"
template<typename X,typename Y>
constexpr uint8_t divide(X x, Y y) { return static_cast<uint32_t>(x) / static_cast<uint32_t>(y); }
//constexpr uint8_t mod_calc(uint32_t x, uint16_t y) { return ((x * 16 / (uint16_t) y) - (x / (uint16_t) y * 16) + 1) / 2; }
template<typename X,typename Y>
constexpr uint8_t mod_calc(X x, Y y) { return (((static_cast<uint32_t>(x) / static_cast<uint32_t>(y)) - divide(x , y)) * 8) << 1; }
template<class _uart, BaudRate _rate, Speed _clock >
class McuUart
{
public:
static const uint8_t BAUDREGISTER = (_rate == BaudRate::BAUD_9600) ? 3 : divide( _clock , _rate );
static const uint8_t MODVALUE = (_rate == BaudRate::BAUD_9600) ? (UCBRS1 + UCBRS0) :mod_calc( _clock, _rate );
static const UartClockSource CLOCKSOURCE = (_rate == BaudRate::BAUD_9600) ? UartClockSource::ACLK : UartClockSource::SMCLK;
static void init() {
_uart::init(BAUDREGISTER, MODVALUE, CLOCKSOURCE);
}
template<class T>
static const void send( const T data, const Base base=Base::BASE_HEX )
{
static char buf[sizeof(T)*3 +1];
itoa(data,buf, base);
send(static_cast<const char*>(buf));
}
static const void send( float data, int precision=2)
{
//TODO implement (look into fixed point) ??
}
static const void send(uint8_t* const data,const int numOfBytes)
{
for(int i = 0; i < numOfBytes; ++i) {
_uart::queueByte(data[i]);
}
}
static const void send(const char* data)
{
int i = 0;
while(data[i] != 0) {
_uart::queueByte(data[i++]);
}
}
static const void sendLine(const char* data=0)
{
if(data != 0)
send(data);
send("\n");
}
static const bool readByte(uint8_t& data)
{
return _uart::readByte(data);
}
private:
};
}
using rx = McuPeripheral::McuPin<McuPort1,BIT1>;
using tx = McuPeripheral::McuPin<McuPort1,BIT2>;
//I hate to have to add this macro, but no other way could easily set this from config file
//and have the interrupt vector know.
//DEFAULT is interrupts off!
#ifdef UARTA0_ENABLE_INT
using UartA0_Irq = McuPeripheral::Interrupts<IE2_,UCA0TXIE, UCA0RXIE>;
#else
using UartA0_Irq = McuPeripheral::FakeInterupts<false>;
#endif
using UartA0 = McuPeripheral::UartControl<rx, tx, UartA0_Irq, UCA0CTL0_, IFG2_, UCA0TXIFG, UCA0RXIFG >;
#endif //_MSP_UART_HPP
<commit_msg>fixed memory issue with buf overrun<commit_after>#ifndef _MSP_UART_HPP
#define _MSP_UART_HPP
#include "mcu_uart.hpp"
#include "msp_periph.hpp"
#include "utilities/utilities.hpp"
#include <stdint.h>
#include <msp430.h>
#include "msp_sys.hpp"
#include "msp_gpio.hpp"
#include "utilities/circfifo.hpp"
#include <math.h>
#include "msp430/msp_periph.hpp"
namespace McuPeripheral
{
enum class UartClockSource : uint8_t { SMCLK = UCSSEL_2, ACLK = UCSSEL_1 };
template< class _rxpin, class _txpin, class _irq, uint8_t _ctl0, uint8_t _iflag, uint8_t _txflag, uint8_t _rxflag>
class UartControl
{
public:
static void queueByte(const uint8_t data)
{
if(_irq::isInterrupt()) {
while(false == _irq::mTxBuffer.push(data));
_irq::enableTxInterrupt();
}
else {
loadTxReg(data);
}
}
static bool readByte(uint8_t& data)
{
if(_irq::isInterrupt()) {
return _irq::mRxBuffer.pop(data);
}
else {
return readRxReg(data);
}
}
static const void loadTxReg(const uint8_t data)
{
//Ensure we are ready
while (!(REG_8(_iflag) & _txflag));
REG_8(txbuf) = data;
while (!(REG_8(_iflag) & _txflag));
}
static const bool readRxReg(uint8_t& data)
{
bool ret = false;
if((REG_8(_iflag) & _rxflag)) {
data = REG_8(rxbuf);
ret = true;
}
return ret;
}
static void init(const uint8_t baudRate, uint8_t mod, UartClockSource source )
{
_rxpin::input(); _rxpin::selectOn(); _rxpin::select2On();
_txpin::output(); _txpin::selectOn(); _txpin::select2On();
REG_8(ctl1) |= UCSWRST;
REG_8(ctl0) |= UCMODE_0;
REG_8(br0) = baudRate;
REG_8(mctl) = mod;
REG_8(ctl1) |= static_cast<uint8_t>(source);
REG_8(ctl1) &= ~UCSWRST;
_irq::init();
_irq::mRxBuffer.init();
_irq::mTxBuffer.init();
_irq::enableRxInterrupt();
}
private:
static constexpr uint8_t ctl0 = _ctl0;
static constexpr uint8_t ctl1 = ctl0 + 1;
static constexpr uint8_t br0 = ctl1 +1;
static constexpr uint8_t br1 = br0 +1;
static constexpr uint8_t mctl = br1 +1;
static constexpr uint8_t stat = mctl +1;
static constexpr uint8_t rxbuf = stat +1;
static constexpr uint8_t txbuf = rxbuf +1;
};
//This macro is returning the number of arguments based on the placeholder N
//example is _VA_ARGS__ is 3 arguments that takes up _1,_2_3, then _4 through _8
//are taken up by 8-4 in the arguments returning 3.
#define VA_NARGS_IMPL(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define VA_NARGS(...) VA_NARGS_IMPL(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)
#define VARARG_IMPL2(base, count, ...) base##count(__VA_ARGS__)
#define VARARG_IMPL(base, count, ...) VARARG_IMPL2(base, count, __VA_ARGS__)
#define VARARG(base, ...) VARARG_IMPL(base, VA_NARGS(__VA_ARGS__), __VA_ARGS__)
#ifndef PRINT
#define PRINT(...) VARARG(Print,__VA_ARGS__)
#endif
#define Print1(_1) \
uart::send(_1);
#define Print2(_1,_2) \
Print1(_1) Print1(_2)
#define Print3(_1,_2,_3) \
Print1(_1) Print2(_2,_3)
#define Print4(_1,_2,_3,_4) \
Print1(_1) Print3(_2,_3,_4)
#define Print5(_1,_2,_3,_4,_5) \
Print1(_1) Print4(_2,_3,_4,_5)
#define Print6(_1,_2,_3,_4,_5,_6) \
Print1(_1) Print5(_2,_3,_4,_5,_6)
#define Print7(_1,_2,_3,_4,_5,_6,_7) \
Print1(_1) Print6(_2,_3,_4,_5,_6,_7)
#define Print8(_1,_2,_3,_4,_5,_6,_7,_8) \
Print1(_1) Print7(_2,_3,_4,_5,_6,_7,_8)
#define ENDL "\n"
template<typename X,typename Y>
constexpr uint8_t divide(X x, Y y) { return static_cast<uint32_t>(x) / static_cast<uint32_t>(y); }
//constexpr uint8_t mod_calc(uint32_t x, uint16_t y) { return ((x * 16 / (uint16_t) y) - (x / (uint16_t) y * 16) + 1) / 2; }
template<typename X,typename Y>
constexpr uint8_t mod_calc(X x, Y y) { return (((static_cast<uint32_t>(x) / static_cast<uint32_t>(y)) - divide(x , y)) * 8) << 1; }
template<class _uart, BaudRate _rate, Speed _clock >
class McuUart
{
public:
static const uint8_t BAUDREGISTER = (_rate == BaudRate::BAUD_9600) ? 3 : divide( _clock , _rate );
static const uint8_t MODVALUE = (_rate == BaudRate::BAUD_9600) ? (UCBRS1 + UCBRS0) :mod_calc( _clock, _rate );
static const UartClockSource CLOCKSOURCE = (_rate == BaudRate::BAUD_9600) ? UartClockSource::ACLK : UartClockSource::SMCLK;
static void init() {
_uart::init(BAUDREGISTER, MODVALUE, CLOCKSOURCE);
}
template<class T>
static const void send( const T data, const Base base=Base::BASE_HEX )
{
static char buf[sizeof(T)*4+1];
itoa(data,buf, base);
send(static_cast<const char*>(buf));
}
static const void send( float data, int precision=2)
{
//TODO implement (look into fixed point) ??
}
static const void send(uint8_t* const data,const int numOfBytes)
{
for(int i = 0; i < numOfBytes; ++i) {
_uart::queueByte(data[i]);
}
}
static const void send(const char* data)
{
int i = 0;
while(data[i] != 0) {
_uart::queueByte(data[i++]);
}
}
static const void sendLine(const char* data=0)
{
if(data != 0)
send(data);
send("\n");
}
static const bool readByte(uint8_t& data)
{
return _uart::readByte(data);
}
private:
};
}
using rx = McuPeripheral::McuPin<McuPort1,BIT1>;
using tx = McuPeripheral::McuPin<McuPort1,BIT2>;
//I hate to have to add this macro, but no other way could easily set this from config file
//and have the interrupt vector know.
//DEFAULT is interrupts off!
#ifdef UARTA0_ENABLE_INT
using UartA0_Irq = McuPeripheral::Interrupts<IE2_,UCA0TXIE, UCA0RXIE>;
#else
using UartA0_Irq = McuPeripheral::FakeInterupts<false>;
#endif
using UartA0 = McuPeripheral::UartControl<rx, tx, UartA0_Irq, UCA0CTL0_, IFG2_, UCA0TXIFG, UCA0RXIFG >;
#endif //_MSP_UART_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2018 The Dash Core developers
// Copyright (c) 2014-2018 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <activemasternode.h>
#include <masternode.h>
#include <masternode-sync.h>
#include <masternodeman.h>
#include <protocol.h>
// Keep track of the active Masternode
CActiveMasternode activeMasternode;
void CActiveMasternode::ManageState(CConnman& connman)
{
LogPrint(MCLog::MN, "CActiveMasternode::ManageState -- Start\n");
if(!fMasterNode) {
LogPrint(MCLog::MN, "CActiveMasternode::ManageState -- Not a masternode, returning\n");
return;
}
if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus());
return;
}
if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) {
nState = ACTIVE_MASTERNODE_INITIAL;
}
LogPrint(MCLog::MN, "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
if(eType == MASTERNODE_UNKNOWN) {
ManageStateInitial(connman);
}
if(eType == MASTERNODE_REMOTE) {
ManageStateRemote();
}
SendMasternodePing(connman);
}
std::string CActiveMasternode::GetStateString() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL: return "INITIAL";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW";
case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE";
case ACTIVE_MASTERNODE_STARTED: return "STARTED";
default: return "UNKNOWN";
}
}
std::string CActiveMasternode::GetStatus() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations);
case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason;
case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started";
default: return "Unknown";
}
}
std::string CActiveMasternode::GetTypeString() const
{
std::string strType;
switch(eType) {
case MASTERNODE_REMOTE:
strType = "REMOTE";
break;
default:
strType = "UNKNOWN";
break;
}
return strType;
}
bool CActiveMasternode::SendMasternodePing(CConnman& connman)
{
if(!fPingerEnabled) {
LogPrint(MCLog::MN, "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString());
return false;
}
if(!mnodeman.Has(outpoint)) {
strNotCapableReason = "Masternode not in masternode list";
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason);
return false;
}
CMasternodePing mnp(outpoint);
mnp.nSentinelVersion = nSentinelVersion;
mnp.fSentinelIsCurrent =
(abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_WATCHDOG_MAX_SECONDS);
if(!mnp.Sign(keyMasternode, pubKeyMasternode)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n");
return false;
}
// Update lastPing for our masternode in Masternode list
if(mnodeman.IsMasternodePingedWithin(outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n");
return false;
}
mnodeman.SetMasternodeLastPing(outpoint, mnp);
LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", outpoint.ToStringShort());
mnp.Relay(connman);
return true;
}
bool CActiveMasternode::UpdateSentinelPing(int version)
{
nSentinelVersion = version;
nSentinelPingTime = GetAdjustedTime();
return true;
}
void CActiveMasternode::ManageStateInitial(CConnman& connman)
{
LogPrint(MCLog::MN, "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
// Check that our local network configuration is correct
if (!fListen) {
// listen option is probably overwritten by smth else, no good
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// First try to find whatever local address is specified by externalip option
bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);
if(!fFoundLocal) {
bool empty = true;
// If we have some peers, let's try to find our local address from one of them
connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) {
empty = false;
if (pnode->addr.IsIPv4())
fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);
return !fFoundLocal;
});
// nothing and no live connections, can't do anything for now
if (empty) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
}
if(!fFoundLocal) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
int defaultChainParams = CreateChainParams(CBaseChainParams::MAIN)->GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(service.GetPort() != mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
} else if(service.GetPort() == mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
if(!connman.ConnectNode(CAddress(service, NODE_NETWORK), NULL, false, true)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// Default to REMOTE
eType = MASTERNODE_REMOTE;
LogPrint(MCLog::MN, "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
}
void CActiveMasternode::ManageStateRemote()
{
LogPrint(MCLog::MN, "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n",
GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString());
mnodeman.CheckMasternode(pubKeyMasternode, true);
masternode_info_t infoMn;
if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) {
if(infoMn.nProtocolVersion != PROTOCOL_VERSION) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Invalid protocol version";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(service != infoMn.addr) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently.";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState));
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(nState != ACTIVE_MASTERNODE_STARTED) {
LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n");
outpoint = infoMn.vin.prevout;
service = infoMn.addr;
fPingerEnabled = true;
nState = ACTIVE_MASTERNODE_STARTED;
}
}
else {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode not in masternode list";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
}
}<commit_msg>other variable name<commit_after>// Copyright (c) 2014-2018 The Dash Core developers
// Copyright (c) 2014-2018 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <activemasternode.h>
#include <masternode.h>
#include <masternode-sync.h>
#include <masternodeman.h>
#include <protocol.h>
// Keep track of the active Masternode
CActiveMasternode activeMasternode;
void CActiveMasternode::ManageState(CConnman& connman)
{
LogPrint(MCLog::MN, "CActiveMasternode::ManageState -- Start\n");
if(!fMasterNode) {
LogPrint(MCLog::MN, "CActiveMasternode::ManageState -- Not a masternode, returning\n");
return;
}
if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus());
return;
}
if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) {
nState = ACTIVE_MASTERNODE_INITIAL;
}
LogPrint(MCLog::MN, "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
if(eType == MASTERNODE_UNKNOWN) {
ManageStateInitial(connman);
}
if(eType == MASTERNODE_REMOTE) {
ManageStateRemote();
}
SendMasternodePing(connman);
}
std::string CActiveMasternode::GetStateString() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL: return "INITIAL";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW";
case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE";
case ACTIVE_MASTERNODE_STARTED: return "STARTED";
default: return "UNKNOWN";
}
}
std::string CActiveMasternode::GetStatus() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations);
case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason;
case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started";
default: return "Unknown";
}
}
std::string CActiveMasternode::GetTypeString() const
{
std::string strType;
switch(eType) {
case MASTERNODE_REMOTE:
strType = "REMOTE";
break;
default:
strType = "UNKNOWN";
break;
}
return strType;
}
bool CActiveMasternode::SendMasternodePing(CConnman& connman)
{
if(!fPingerEnabled) {
LogPrint(MCLog::MN, "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString());
return false;
}
if(!mnodeman.Has(outpoint)) {
strNotCapableReason = "Masternode not in masternode list";
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason);
return false;
}
CMasternodePing mnp(outpoint);
mnp.nSentinelVersion = nSentinelVersion;
mnp.fSentinelIsCurrent =
(abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_WATCHDOG_MAX_SECONDS);
if(!mnp.Sign(keyMasternode, pubKeyMasternode)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n");
return false;
}
// Update lastPing for our masternode in Masternode list
if(mnodeman.IsMasternodePingedWithin(outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n");
return false;
}
mnodeman.SetMasternodeLastPing(outpoint, mnp);
LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", outpoint.ToStringShort());
mnp.Relay(connman);
return true;
}
bool CActiveMasternode::UpdateSentinelPing(int version)
{
nSentinelVersion = version;
nSentinelPingTime = GetAdjustedTime();
return true;
}
void CActiveMasternode::ManageStateInitial(CConnman& connman)
{
LogPrint(MCLog::MN, "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
// Check that our local network configuration is correct
if (!fListen) {
// listen option is probably overwritten by smth else, no good
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// First try to find whatever local address is specified by externalip option
bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);
if(!fFoundLocal) {
bool empty = true;
// If we have some peers, let's try to find our local address from one of them
connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) {
empty = false;
if (pnode->addr.IsIPv4())
fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);
return !fFoundLocal;
});
// nothing and no live connections, can't do anything for now
if (empty) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
}
if(!fFoundLocal) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
int mainnetDefaultPort = CreateChainParams(CBaseChainParams::MAIN)->GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(service.GetPort() != mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
} else if(service.GetPort() == mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
if(!connman.ConnectNode(CAddress(service, NODE_NETWORK), NULL, false, true)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// Default to REMOTE
eType = MASTERNODE_REMOTE;
LogPrint(MCLog::MN, "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
}
void CActiveMasternode::ManageStateRemote()
{
LogPrint(MCLog::MN, "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n",
GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString());
mnodeman.CheckMasternode(pubKeyMasternode, true);
masternode_info_t infoMn;
if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) {
if(infoMn.nProtocolVersion != PROTOCOL_VERSION) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Invalid protocol version";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(service != infoMn.addr) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently.";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState));
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(nState != ACTIVE_MASTERNODE_STARTED) {
LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n");
outpoint = infoMn.vin.prevout;
service = infoMn.addr;
fPingerEnabled = true;
nState = ACTIVE_MASTERNODE_STARTED;
}
}
else {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode not in masternode list";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
}
}<|endoftext|> |
<commit_before>///
/// @file FactorTable.hpp
/// @brief The FactorTable class is used to save memory. It combines
/// the lpf[n] (least prime factor) and mu[n] (Möbius function)
/// lookup tables into a single factors_[n] table which
/// furthermore only contains entries for numbers which are
/// not divisible by 2, 3, 5 and 7.
/// The factor table concept has first been devised and
/// implemented by Christian Bau in 2003.
///
/// FactorTable.lpf(index) is equal to (n = get_number(index)):
///
/// * 0 if moebius(n) = 0
/// * lpf if !is_prime(n) && moebius(n) = -1
/// * lpf-1 if !is_prime(n) && moebius(n) = 1
/// * n if is_prime(n) && n < T_MAX
/// * T_MAX if is_prime(n) && n > T_MAX
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP
#include <primecount.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <cassert>
#include <limits>
#include <stdint.h>
#include <vector>
namespace primecount {
/// AbstractFactorTable contains static FactorTable
/// data and it used to convert:
/// 1) A number into a FactorTable index.
/// 2) A FactorTable index into a number.
///
class AbstractFactorTable
{
protected:
virtual ~AbstractFactorTable() { }
public:
/// @pre number > 0
static void to_index(int64_t* number)
{
assert(*number > 0);
*number = get_index(*number);
}
/// @pre number > 0
static int64_t get_index(int64_t number)
{
assert(number > 0);
int64_t quotient = number / 210;
int64_t remainder = number % 210;
return 48 * quotient + indexes_[remainder];
}
static int64_t get_number(int64_t index)
{
int64_t quotient = index / 48;
int64_t remainder = index % 48;
return 210 * quotient + numbers_[remainder];
}
private:
static const uint8_t numbers_[48];
static const int8_t indexes_[210];
};
template <typename T>
class FactorTable : public AbstractFactorTable
{
public:
/// @param y factor numbers <= y
FactorTable(int64_t y)
{
if (y > max())
throw primecount_error("y must be <= FactorTable::max().");
y = std::max<int64_t>(8, y);
T T_MAX = std::numeric_limits<T>::max();
init_factors(y, T_MAX);
}
static int64_t max()
{
int64_t T_MAX = std::numeric_limits<T>::max();
return ipow(T_MAX - 1, 2) - 1;
}
/// Get the least prime factor (lpf) of the number get_number(index).
/// The result is different from lpf in some situations:
/// 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.
/// 2) lpf(index) returns lpf minus one if mu(index) == 1.
/// 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.
///
int64_t lpf(int64_t index) const
{
return factors_[index];
}
/// Get the Möbius function value of the number get_number(index).
/// For performance reasons mu(index) == 0 is not supported.
/// @pre mu(index) != 0 (i.e. lpf(index) != 0)
///
int64_t mu(int64_t index) const
{
assert(lpf(index) != 0);
return (factors_[index] & 1) ? -1 : 1;
}
private:
void init_factors(int64_t y, T T_MAX)
{
int64_t sqrty = isqrt(y);
factors_.resize(get_index(y) + 1, T_MAX);
factors_[0] = T_MAX - 1;
for (size_t i = 1; i < factors_.size(); i++)
{
if (factors_[i] == T_MAX)
{
int64_t prime = get_number(i);
int64_t multiple = prime * get_number(1);
if (prime < T_MAX)
factors_[i] = (T) prime;
else if (multiple > y)
break;
for (int64_t j = 2; multiple <= y; multiple = prime * get_number(j++))
{
int64_t index = get_index(multiple);
// prime is the smallest factor of multiple
if (factors_[index] == T_MAX)
factors_[index] = (T) prime;
// the least significant bit indicates whether multiple has
// an even (0) or odd (1) number of prime factors
else if (factors_[index] != 0)
factors_[index] ^= 1;
}
// Möbius function is 0 if n has a squared prime factor
if (prime <= sqrty)
{
multiple = prime * prime;
for (int64_t j = 1; multiple <= y; multiple = prime * prime * get_number(j++))
factors_[get_index(multiple)] = 0;
}
}
}
}
std::vector<T> factors_;
};
} // namespace
#endif
<commit_msg>Update FactorTable.hpp<commit_after>///
/// @file FactorTable.hpp
/// @brief The FactorTable class is used to save memory. It combines
/// the lpf[n] (least prime factor) and mu[n] (Möbius function)
/// lookup tables into a single factors_[n] table which
/// furthermore only contains entries for numbers which are
/// not divisible by 2, 3, 5 and 7.
/// The factor table concept has first been devised and
/// implemented by Christian Bau in 2003.
///
/// FactorTable.lpf(index) is equal to (n = get_number(index)):
///
/// * 0 if moebius(n) = 0
/// * lpf if !is_prime(n) && moebius(n) = -1
/// * lpf-1 if !is_prime(n) && moebius(n) = 1
/// * n if is_prime(n) && n < T_MAX
/// * T_MAX if is_prime(n) && n > T_MAX
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP
#include <primecount.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <cassert>
#include <limits>
#include <stdint.h>
#include <vector>
namespace primecount {
/// AbstractFactorTable contains static FactorTable
/// data and it used to convert:
/// 1) A number into a FactorTable index.
/// 2) A FactorTable index into a number.
///
class AbstractFactorTable
{
protected:
virtual ~AbstractFactorTable() { }
public:
/// @pre number > 0
static void to_index(int64_t* number)
{
assert(*number > 0);
*number = get_index(*number);
}
/// @pre number > 0
static int64_t get_index(int64_t number)
{
assert(number > 0);
int64_t quotient = number / 210;
int64_t remainder = number % 210;
return 48 * quotient + indexes_[remainder];
}
static int64_t get_number(int64_t index)
{
int64_t quotient = index / 48;
int64_t remainder = index % 48;
return 210 * quotient + numbers_[remainder];
}
private:
static const uint8_t numbers_[48];
static const int8_t indexes_[210];
};
template <typename T>
class FactorTable : public AbstractFactorTable
{
public:
/// @param y factor numbers <= y
FactorTable(int64_t y)
{
if (y > max())
throw primecount_error("y must be <= FactorTable::max().");
y = std::max<int64_t>(8, y);
T T_MAX = std::numeric_limits<T>::max();
init_factors(y, T_MAX);
}
static int64_t max()
{
int64_t T_MAX = std::numeric_limits<T>::max();
return ipow(T_MAX - 1, 2) - 1;
}
/// Get the least prime factor (lpf) of the number get_number(index).
/// The result is different from lpf in some situations:
/// 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.
/// 2) lpf(index) returns lpf minus one if mu(index) == 1.
/// 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.
///
int64_t lpf(int64_t index) const
{
return factors_[index];
}
/// Get the Möbius function value of the number get_number(index).
/// For performance reasons mu(index) == 0 is not supported.
/// @pre mu(index) != 0 (i.e. lpf(index) != 0)
///
int64_t mu(int64_t index) const
{
assert(lpf(index) != 0);
return (factors_[index] & 1) ? -1 : 1;
}
private:
void init_factors(int64_t y, T T_MAX)
{
int64_t sqrty = isqrt(y);
factors_.resize(get_index(y) + 1, T_MAX);
factors_[0] = T_MAX - 1;
for (std::size_t i = 1; i < factors_.size(); i++)
{
if (factors_[i] == T_MAX)
{
int64_t prime = get_number(i);
int64_t multiple = prime * get_number(1);
if (prime < T_MAX)
factors_[i] = (T) prime;
else if (multiple > y)
break;
for (int64_t j = 2; multiple <= y; multiple = prime * get_number(j++))
{
int64_t index = get_index(multiple);
// prime is the smallest factor of multiple
if (factors_[index] == T_MAX)
factors_[index] = (T) prime;
// the least significant bit indicates whether multiple has
// an even (0) or odd (1) number of prime factors
else if (factors_[index] != 0)
factors_[index] ^= 1;
}
// Möbius function is 0 if n has a squared prime factor
if (prime <= sqrty)
{
multiple = prime * prime;
for (int64_t j = 1; multiple <= y; multiple = prime * prime * get_number(j++))
factors_[get_index(multiple)] = 0;
}
}
}
}
std::vector<T> factors_;
};
} // namespace
#endif
<|endoftext|> |
<commit_before>/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "./input_parser.h"
// Helper to get optional array of coordinates.
inline coords_t parse_coordinates(const rapidjson::Value& object,
const char* key) {
if (!object[key].IsArray() or (object[key].Size() < 2) or
!object[key][0].IsNumber() or !object[key][1].IsNumber()) {
throw custom_exception("Invalid " + std::string(key) + " array.");
}
return {object[key][0].GetDouble(), object[key][1].GetDouble()};
}
inline amount_t get_amount(const rapidjson::Value& object, const char* key) {
// Default to empty amount.
amount_t amount(0);
if (!object.HasMember(key)) {
return amount;
}
if (!object[key].IsArray()) {
throw custom_exception("Invalid " + std::string(key) + " array.");
}
for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) {
if (!object[key][i].IsInt64()) {
throw custom_exception("Invalid " + std::string(key) + " value.");
}
amount.push_back(object[key][i].GetInt64());
}
return amount;
}
inline std::unordered_set<skill_t> get_skills(const rapidjson::Value& object) {
std::unordered_set<skill_t> skills;
if (object.HasMember("skills")) {
if (!object["skills"].IsArray()) {
throw custom_exception("Invalid skills object.");
}
for (rapidjson::SizeType i = 0; i < object["skills"].Size(); ++i) {
if (!object["skills"][i].IsUint()) {
throw custom_exception("Invalid skill value.");
}
skills.insert(object["skills"][i].GetUint());
}
}
return skills;
}
inline bool valid_vehicle(const rapidjson::Value& v) {
return v.IsObject() and v.HasMember("id") and v["id"].IsUint64();
}
input parse(const cl_args_t& cl_args) {
BOOST_LOG_TRIVIAL(info) << "[Loading] Parsing input.";
// Set relevant wrapper to retrieve the matrix and geometry.
std::unique_ptr<routing_io<cost_t>> routing_wrapper;
if (!cl_args.use_libosrm) {
// Use osrm-routed.
routing_wrapper = std::make_unique<routed_wrapper>(cl_args.osrm_address,
cl_args.osrm_port,
cl_args.osrm_profile);
} else {
#if LIBOSRM
// Use libosrm.
if (cl_args.osrm_profile.empty()) {
throw custom_exception("-l flag requires -m.");
}
routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);
#else
throw custom_exception("libosrm must be installed to use -l.");
#endif
}
// Custom input object embedding jobs, vehicles and matrix.
input input_data(std::move(routing_wrapper), cl_args.geometry);
// Input json object.
rapidjson::Document json_input;
// Parsing input string to populate the input object.
if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {
std::string error_msg =
std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +
" (offset: " + std::to_string(json_input.GetErrorOffset()) + ")";
throw custom_exception(error_msg);
}
// Main Checks for valid json input.
if (!json_input.HasMember("jobs") or !json_input["jobs"].IsArray() or
json_input["jobs"].Empty()) {
throw custom_exception("Invalid jobs.");
}
if (!json_input.HasMember("vehicles") or !json_input["vehicles"].IsArray() or
json_input["vehicles"].Empty()) {
throw custom_exception("Invalid vehicles.");
}
// Switch input type: explicit matrix or using OSRM.
if (json_input.HasMember("matrix")) {
if (!json_input["matrix"].IsArray()) {
throw custom_exception("Invalid matrix.");
}
// Load custom matrix while checking if it is square.
rapidjson::SizeType matrix_size = json_input["matrix"].Size();
matrix<cost_t> matrix_input(matrix_size);
for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {
if (!json_input["matrix"][i].IsArray() or
(json_input["matrix"][i].Size() != matrix_size)) {
throw custom_exception("Invalid matrix line " + std::to_string(i) +
".");
}
for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {
if (!json_input["matrix"][i][j].IsUint()) {
throw custom_exception("Invalid matrix entry (" + std::to_string(i) +
"," + std::to_string(j) + ").");
}
cost_t cost = json_input["matrix"][i][j].GetUint();
matrix_input[i][j] = cost;
}
}
input_data.set_matrix(std::move(matrix_input));
// Add all vehicles.
for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) {
auto& json_vehicle = json_input["vehicles"][i];
if (!valid_vehicle(json_vehicle)) {
throw custom_exception("Invalid vehicle at " + std::to_string(i) + ".");
}
auto v_id = json_vehicle["id"].GetUint();
// Check if vehicle has start_index or end_index.
bool has_start_index = json_vehicle.HasMember("start_index");
index_t start_index = 0; // Initial value actually never used.
if (has_start_index) {
if (!json_vehicle["start_index"].IsUint()) {
throw custom_exception("Invalid start_index for vehicle " +
std::to_string(v_id) + ".");
}
start_index = json_vehicle["start_index"].GetUint();
if (matrix_size <= start_index) {
throw custom_exception(
"start_index exceeding matrix size for vehicle" +
std::to_string(v_id) + ".");
}
}
bool has_start_coords = json_vehicle.HasMember("start");
bool has_end_index = json_vehicle.HasMember("end_index");
index_t end_index = 0; // Initial value actually never used.
if (has_end_index) {
if (!json_vehicle["end_index"].IsUint()) {
throw custom_exception("Invalid end_index for vehicle" +
std::to_string(v_id) + ".");
}
end_index = json_vehicle["end_index"].GetUint();
if (matrix_size <= end_index) {
throw custom_exception("end_index exceeding matrix size for vehicle" +
std::to_string(v_id) + ".");
}
}
bool has_end_coords = json_vehicle.HasMember("end");
// Add vehicle to input
boost::optional<location_t> start;
if (has_start_index) {
if (has_start_coords) {
start = boost::optional<location_t>(location_t(
{start_index, parse_coordinates(json_vehicle, "start")}));
} else {
start = boost::optional<location_t>(start_index);
}
}
boost::optional<location_t> end;
if (has_end_index) {
if (has_end_coords) {
end = boost::optional<location_t>(
location_t({end_index, parse_coordinates(json_vehicle, "end")}));
} else {
end = boost::optional<location_t>(end_index);
}
}
vehicle_t current_v(v_id,
start,
end,
get_amount(json_vehicle, "capacity"),
get_skills(json_vehicle));
input_data.add_vehicle(current_v);
}
// Add the jobs
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
auto& json_job = json_input["jobs"][i];
if (!json_job.IsObject()) {
throw custom_exception("Invalid job.");
}
if (!json_job.HasMember("id") or !json_job["id"].IsUint64()) {
throw custom_exception("Invalid id for job at " + std::to_string(i) +
".");
}
auto j_id = json_job["id"].GetUint64();
if (!json_job.HasMember("location_index") or
!json_job["location_index"].IsUint()) {
throw custom_exception("Invalid location_index for job " +
std::to_string(j_id) + ".");
}
if (matrix_size <= json_job["location_index"].GetUint()) {
throw custom_exception("location_index exceeding matrix size for job " +
std::to_string(j_id) + ".");
}
auto job_loc_index = json_job["location_index"].GetUint();
location_t job_loc(job_loc_index);
if (json_job.HasMember("location")) {
job_loc =
location_t(job_loc_index, parse_coordinates(json_job, "location"));
}
job_t current_job(j_id,
job_loc,
get_amount(json_job, "amount"),
get_skills(json_job));
input_data.add_job(current_job);
}
} else {
// Adding vehicles and jobs only, matrix will be computed using
// OSRM upon solving.
// All vehicles.
for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) {
auto& json_vehicle = json_input["vehicles"][i];
if (!valid_vehicle(json_vehicle)) {
throw custom_exception("Invalid vehicle at " + std::to_string(i) + ".");
}
// Start def is a ugly workaround as using plain:
//
// boost::optional<location_t> start;
//
// will raise a false positive -Wmaybe-uninitialized with gcc,
// see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47679
auto start([]() -> boost::optional<location_t> { return boost::none; }());
if (json_vehicle.HasMember("start")) {
start =
boost::optional<location_t>(parse_coordinates(json_vehicle, "start"));
}
boost::optional<location_t> end;
if (json_vehicle.HasMember("end")) {
end =
boost::optional<location_t>(parse_coordinates(json_vehicle, "end"));
}
vehicle_t current_v(json_vehicle["id"].GetUint(),
start,
end,
get_amount(json_vehicle, "capacity"),
get_skills(json_vehicle));
input_data.add_vehicle(current_v);
}
// Getting jobs.
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
auto& json_job = json_input["jobs"][i];
if (!json_job.IsObject()) {
throw custom_exception("Invalid job.");
}
if (!json_job.HasMember("id") or !json_job["id"].IsUint64()) {
throw custom_exception("Invalid id for job at " + std::to_string(i) +
".");
}
auto j_id = json_job["id"].GetUint64();
if (!json_job.HasMember("location") or !json_job["location"].IsArray()) {
throw custom_exception("Invalid location for job " +
std::to_string(j_id) + ".");
}
job_t current_job(j_id,
parse_coordinates(json_job, "location"),
get_amount(json_job, "amount"),
get_skills(json_job));
input_data.add_job(current_job);
}
}
return input_data;
}
<commit_msg>Simplify amount parsing.<commit_after>/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "./input_parser.h"
// Helper to get optional array of coordinates.
inline coords_t parse_coordinates(const rapidjson::Value& object,
const char* key) {
if (!object[key].IsArray() or (object[key].Size() < 2) or
!object[key][0].IsNumber() or !object[key][1].IsNumber()) {
throw custom_exception("Invalid " + std::string(key) + " array.");
}
return {object[key][0].GetDouble(), object[key][1].GetDouble()};
}
inline amount_t get_amount(const rapidjson::Value& object, const char* key) {
// Default to empty amount.
amount_t amount(0);
if (object.HasMember(key)) {
if (!object[key].IsArray()) {
throw custom_exception("Invalid " + std::string(key) + " array.");
}
for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) {
if (!object[key][i].IsInt64()) {
throw custom_exception("Invalid " + std::string(key) + " value.");
}
amount.push_back(object[key][i].GetInt64());
}
}
return amount;
}
inline std::unordered_set<skill_t> get_skills(const rapidjson::Value& object) {
std::unordered_set<skill_t> skills;
if (object.HasMember("skills")) {
if (!object["skills"].IsArray()) {
throw custom_exception("Invalid skills object.");
}
for (rapidjson::SizeType i = 0; i < object["skills"].Size(); ++i) {
if (!object["skills"][i].IsUint()) {
throw custom_exception("Invalid skill value.");
}
skills.insert(object["skills"][i].GetUint());
}
}
return skills;
}
inline bool valid_vehicle(const rapidjson::Value& v) {
return v.IsObject() and v.HasMember("id") and v["id"].IsUint64();
}
input parse(const cl_args_t& cl_args) {
BOOST_LOG_TRIVIAL(info) << "[Loading] Parsing input.";
// Set relevant wrapper to retrieve the matrix and geometry.
std::unique_ptr<routing_io<cost_t>> routing_wrapper;
if (!cl_args.use_libosrm) {
// Use osrm-routed.
routing_wrapper = std::make_unique<routed_wrapper>(cl_args.osrm_address,
cl_args.osrm_port,
cl_args.osrm_profile);
} else {
#if LIBOSRM
// Use libosrm.
if (cl_args.osrm_profile.empty()) {
throw custom_exception("-l flag requires -m.");
}
routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);
#else
throw custom_exception("libosrm must be installed to use -l.");
#endif
}
// Custom input object embedding jobs, vehicles and matrix.
input input_data(std::move(routing_wrapper), cl_args.geometry);
// Input json object.
rapidjson::Document json_input;
// Parsing input string to populate the input object.
if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {
std::string error_msg =
std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +
" (offset: " + std::to_string(json_input.GetErrorOffset()) + ")";
throw custom_exception(error_msg);
}
// Main Checks for valid json input.
if (!json_input.HasMember("jobs") or !json_input["jobs"].IsArray() or
json_input["jobs"].Empty()) {
throw custom_exception("Invalid jobs.");
}
if (!json_input.HasMember("vehicles") or !json_input["vehicles"].IsArray() or
json_input["vehicles"].Empty()) {
throw custom_exception("Invalid vehicles.");
}
// Switch input type: explicit matrix or using OSRM.
if (json_input.HasMember("matrix")) {
if (!json_input["matrix"].IsArray()) {
throw custom_exception("Invalid matrix.");
}
// Load custom matrix while checking if it is square.
rapidjson::SizeType matrix_size = json_input["matrix"].Size();
matrix<cost_t> matrix_input(matrix_size);
for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {
if (!json_input["matrix"][i].IsArray() or
(json_input["matrix"][i].Size() != matrix_size)) {
throw custom_exception("Invalid matrix line " + std::to_string(i) +
".");
}
for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {
if (!json_input["matrix"][i][j].IsUint()) {
throw custom_exception("Invalid matrix entry (" + std::to_string(i) +
"," + std::to_string(j) + ").");
}
cost_t cost = json_input["matrix"][i][j].GetUint();
matrix_input[i][j] = cost;
}
}
input_data.set_matrix(std::move(matrix_input));
// Add all vehicles.
for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) {
auto& json_vehicle = json_input["vehicles"][i];
if (!valid_vehicle(json_vehicle)) {
throw custom_exception("Invalid vehicle at " + std::to_string(i) + ".");
}
auto v_id = json_vehicle["id"].GetUint();
// Check if vehicle has start_index or end_index.
bool has_start_index = json_vehicle.HasMember("start_index");
index_t start_index = 0; // Initial value actually never used.
if (has_start_index) {
if (!json_vehicle["start_index"].IsUint()) {
throw custom_exception("Invalid start_index for vehicle " +
std::to_string(v_id) + ".");
}
start_index = json_vehicle["start_index"].GetUint();
if (matrix_size <= start_index) {
throw custom_exception(
"start_index exceeding matrix size for vehicle" +
std::to_string(v_id) + ".");
}
}
bool has_start_coords = json_vehicle.HasMember("start");
bool has_end_index = json_vehicle.HasMember("end_index");
index_t end_index = 0; // Initial value actually never used.
if (has_end_index) {
if (!json_vehicle["end_index"].IsUint()) {
throw custom_exception("Invalid end_index for vehicle" +
std::to_string(v_id) + ".");
}
end_index = json_vehicle["end_index"].GetUint();
if (matrix_size <= end_index) {
throw custom_exception("end_index exceeding matrix size for vehicle" +
std::to_string(v_id) + ".");
}
}
bool has_end_coords = json_vehicle.HasMember("end");
// Add vehicle to input
boost::optional<location_t> start;
if (has_start_index) {
if (has_start_coords) {
start = boost::optional<location_t>(location_t(
{start_index, parse_coordinates(json_vehicle, "start")}));
} else {
start = boost::optional<location_t>(start_index);
}
}
boost::optional<location_t> end;
if (has_end_index) {
if (has_end_coords) {
end = boost::optional<location_t>(
location_t({end_index, parse_coordinates(json_vehicle, "end")}));
} else {
end = boost::optional<location_t>(end_index);
}
}
vehicle_t current_v(v_id,
start,
end,
get_amount(json_vehicle, "capacity"),
get_skills(json_vehicle));
input_data.add_vehicle(current_v);
}
// Add the jobs
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
auto& json_job = json_input["jobs"][i];
if (!json_job.IsObject()) {
throw custom_exception("Invalid job.");
}
if (!json_job.HasMember("id") or !json_job["id"].IsUint64()) {
throw custom_exception("Invalid id for job at " + std::to_string(i) +
".");
}
auto j_id = json_job["id"].GetUint64();
if (!json_job.HasMember("location_index") or
!json_job["location_index"].IsUint()) {
throw custom_exception("Invalid location_index for job " +
std::to_string(j_id) + ".");
}
if (matrix_size <= json_job["location_index"].GetUint()) {
throw custom_exception("location_index exceeding matrix size for job " +
std::to_string(j_id) + ".");
}
auto job_loc_index = json_job["location_index"].GetUint();
location_t job_loc(job_loc_index);
if (json_job.HasMember("location")) {
job_loc =
location_t(job_loc_index, parse_coordinates(json_job, "location"));
}
job_t current_job(j_id,
job_loc,
get_amount(json_job, "amount"),
get_skills(json_job));
input_data.add_job(current_job);
}
} else {
// Adding vehicles and jobs only, matrix will be computed using
// OSRM upon solving.
// All vehicles.
for (rapidjson::SizeType i = 0; i < json_input["vehicles"].Size(); ++i) {
auto& json_vehicle = json_input["vehicles"][i];
if (!valid_vehicle(json_vehicle)) {
throw custom_exception("Invalid vehicle at " + std::to_string(i) + ".");
}
// Start def is a ugly workaround as using plain:
//
// boost::optional<location_t> start;
//
// will raise a false positive -Wmaybe-uninitialized with gcc,
// see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47679
auto start([]() -> boost::optional<location_t> { return boost::none; }());
if (json_vehicle.HasMember("start")) {
start =
boost::optional<location_t>(parse_coordinates(json_vehicle, "start"));
}
boost::optional<location_t> end;
if (json_vehicle.HasMember("end")) {
end =
boost::optional<location_t>(parse_coordinates(json_vehicle, "end"));
}
vehicle_t current_v(json_vehicle["id"].GetUint(),
start,
end,
get_amount(json_vehicle, "capacity"),
get_skills(json_vehicle));
input_data.add_vehicle(current_v);
}
// Getting jobs.
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
auto& json_job = json_input["jobs"][i];
if (!json_job.IsObject()) {
throw custom_exception("Invalid job.");
}
if (!json_job.HasMember("id") or !json_job["id"].IsUint64()) {
throw custom_exception("Invalid id for job at " + std::to_string(i) +
".");
}
auto j_id = json_job["id"].GetUint64();
if (!json_job.HasMember("location") or !json_job["location"].IsArray()) {
throw custom_exception("Invalid location for job " +
std::to_string(j_id) + ".");
}
job_t current_job(j_id,
parse_coordinates(json_job, "location"),
get_amount(json_job, "amount"),
get_skills(json_job));
input_data.add_job(current_job);
}
}
return input_data;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 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.
*/
/*
* Checksum abstraction functions.
*
* ForestDB evolved to support a software CRC and platform's CRC32-C.
* This module provides an API for checking and creating checksums
* utilising the correct method based upon the callers crc_mode.
*/
#include "checksum.h"
#include "common.h"
#include "crc32.h"
#ifdef _CRC32C
// Linking with platform for crc32c
#include <platform/crc32c.h>
#else
// Define a crc32c which does nothing but fdb_assert.
uint32_t crc32c(const uint8_t* buf,
size_t buf_len,
uint32_t pre) {
// Non couchbase builds are configured to never turn on crc32c.
fdb_assert(false, false, false);
}
#endif
/*
* Get a checksum of buf for buf_len bytes.
*
* mode = UNKNOWN is an invalid input (triggers assert).
*/
uint32_t get_checksum(const uint8_t* buf,
size_t buf_len,
uint32_t pre,
crc_mode_e mode) {
if (mode == CRC32C) {
return crc32c(buf, buf_len, pre);
} else {
fdb_assert(mode == CRC32, mode, CRC32);
return crc32_8(buf, buf_len, pre);
}
}
/*
* Get a checksum of buf for buf_len bytes.
*
* The pre value is set to 0.
*
* mode = UNKNOWN is an invalid input (triggers assert).
*/
uint32_t get_checksum(const uint8_t* buf,
size_t buf_len,
crc_mode_e mode) {
return get_checksum(buf, buf_len, 0, mode);
}
/*
* Perform an integrity check of buf for buf_len bytes.
*
* A checksum of buf is created and compared against checksum argument.
*
* mode = UNKNOWN is an acceptable input. All modes are tried before failing.
*
*
* Returns true success (checksums match), false for failure.
*/
bool perform_integrity_check(const uint8_t* buf,
size_t buf_len,
uint32_t checksum,
crc_mode_e mode) {
bool success = false;
#ifdef _CRC32C
if (mode == CRC_UNKNOWN || mode == CRC32C) {
success = checksum == crc32c(buf, buf_len, 0);
if (!success && mode == CRC_UNKNOWN) {
success = checksum == crc32_8(buf, buf_len, 0);
}
} else
#endif
{
success = checksum == crc32_8(buf, buf_len, 0);
}
return success;
}
/*
* Detect the CRC mode by performing an integrity check against the
* two CRC functions ForestDB files could be written with.
*
* Returns true if a match is found and sets mode to the correct mode.
* Returns false if no match and sets mode to CRC_UNKNOWN.
*/
bool detect_and_check_crc(const uint8_t* buf,
size_t buf_len,
uint32_t checksum,
crc_mode_e* mode) {
*mode = CRC_UNKNOWN;
#ifdef _CRC32C
if (perform_integrity_check(buf, buf_len, checksum, CRC32C)) {
*mode = CRC32C;
return true;
} else
#endif
if (perform_integrity_check(buf, buf_len, checksum, CRC32)) {
*mode = CRC32;
return true;
}
return false;
}
<commit_msg>build fix: when including platform skip all other header files<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 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.
*/
/*
* Checksum abstraction functions.
*
* ForestDB evolved to support a software CRC and platform's CRC32-C.
* This module provides an API for checking and creating checksums
* utilising the correct method based upon the callers crc_mode.
*/
#include <stdlib.h>
#include <assert.h>
#ifdef _CRC32C
// Linking with platform for crc32c
# include <platform/crc32c.h>
#else
#include <stdint.h>
// Define a crc32c which does nothing but assert.
uint32_t crc32c(const uint8_t* buf,
size_t buf_len,
uint32_t pre) {
// Non couchbase builds are configured to never turn on crc32c.
assert(false);
return 0;
}
#endif
# include "checksum.h"
#include "crc32.h"
/*
* Get a checksum of buf for buf_len bytes.
*
* mode = UNKNOWN is an invalid input (triggers assert).
*/
uint32_t get_checksum(const uint8_t* buf,
size_t buf_len,
uint32_t pre,
crc_mode_e mode) {
if (mode == CRC32C) {
return crc32c(buf, buf_len, pre);
} else {
assert(mode == CRC32);
return crc32_8(buf, buf_len, pre);
}
}
/*
* Get a checksum of buf for buf_len bytes.
*
* The pre value is set to 0.
*
* mode = UNKNOWN is an invalid input (triggers assert).
*/
uint32_t get_checksum(const uint8_t* buf,
size_t buf_len,
crc_mode_e mode) {
return get_checksum(buf, buf_len, 0, mode);
}
/*
* Perform an integrity check of buf for buf_len bytes.
*
* A checksum of buf is created and compared against checksum argument.
*
* mode = UNKNOWN is an acceptable input. All modes are tried before failing.
*
*
* Returns true success (checksums match), false for failure.
*/
bool perform_integrity_check(const uint8_t* buf,
size_t buf_len,
uint32_t checksum,
crc_mode_e mode) {
bool success = false;
#ifdef _CRC32C
if (mode == CRC_UNKNOWN || mode == CRC32C) {
success = checksum == crc32c(buf, buf_len, 0);
if (!success && mode == CRC_UNKNOWN) {
success = checksum == crc32_8(buf, buf_len, 0);
}
} else
#endif
{
success = checksum == crc32_8(buf, buf_len, 0);
}
return success;
}
/*
* Detect the CRC mode by performing an integrity check against the
* two CRC functions ForestDB files could be written with.
*
* Returns true if a match is found and sets mode to the correct mode.
* Returns false if no match and sets mode to CRC_UNKNOWN.
*/
bool detect_and_check_crc(const uint8_t* buf,
size_t buf_len,
uint32_t checksum,
crc_mode_e* mode) {
*mode = CRC_UNKNOWN;
#ifdef _CRC32C
if (perform_integrity_check(buf, buf_len, checksum, CRC32C)) {
*mode = CRC32C;
return true;
} else
#endif
if (perform_integrity_check(buf, buf_len, checksum, CRC32)) {
*mode = CRC32;
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/exception.h>
#include <af/device.h>
#include <err_common.hpp>
#include <type_util.hpp>
#include <util.hpp>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
#include <graphics_common.hpp>
#endif
using std::string;
using std::stringstream;
AfError::AfError(const char * const func,
const char * const file,
const int line,
const char * const message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
AfError::AfError(string func,
string file,
const int line,
string message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
const string&
AfError::getFunctionName() const
{
return functionName;
}
const string&
AfError::getFileName() const
{
return fileName;
}
int
AfError::getLine() const
{
return lineNumber;
}
af_err
AfError::getError() const
{
return error;
}
AfError::~AfError() throw() {}
TypeError::TypeError(const char * const func,
const char * const file,
const int line,
const int index, const af_dtype type)
: AfError (func, file, line, "Invalid data type", AF_ERR_TYPE),
argIndex(index),
errTypeName(getName(type))
{}
const string& TypeError::getTypeName() const
{
return errTypeName;
}
int TypeError::getArgIndex() const
{
return argIndex;
}
ArgumentError::ArgumentError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid argument", AF_ERR_ARG),
argIndex(index),
expected(expectString)
{
}
const string& ArgumentError::getExpectedCondition() const
{
return expected;
}
int ArgumentError::getArgIndex() const
{
return argIndex;
}
SupportError::SupportError(const char * const func,
const char * const file,
const int line,
const char * const back)
: AfError(func, file, line, "Unsupported Error", AF_ERR_NOT_SUPPORTED),
backend(back)
{}
const string& SupportError::getBackendName() const
{
return backend;
}
DimensionError::DimensionError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid size", AF_ERR_SIZE),
argIndex(index),
expected(expectString)
{
}
const string& DimensionError::getExpectedCondition() const
{
return expected;
}
int DimensionError::getArgIndex() const
{
return argIndex;
}
static const int MAX_ERR_SIZE = 1024;
static std::string global_err_string;
void
print_error(const string &msg)
{
std::string perr = getEnvVar("AF_PRINT_ERRORS");
if(!perr.empty()) {
if(perr != "0")
fprintf(stderr, "%s\n", msg.c_str());
}
global_err_string = msg;
}
void af_get_last_error(char **str, dim_t *len)
{
*len = std::min(MAX_ERR_SIZE, (int)global_err_string.size());
if (*len == 0) {
*str = NULL;
}
af_alloc_host((void**)str, sizeof(char) * (*len + 1));
global_err_string.copy(*str, *len);
(*str)[*len] = '\0';
global_err_string = std::string("");
}
const char *af_err_to_string(const af_err err)
{
switch (err) {
case AF_SUCCESS: return "Success";
case AF_ERR_NO_MEM: return "Device out of memory";
case AF_ERR_DRIVER: return "Driver not available or incompatible";
case AF_ERR_RUNTIME: return "Runtime error ";
case AF_ERR_INVALID_ARRAY: return "Invalid array";
case AF_ERR_ARG: return "Invalid input argument";
case AF_ERR_SIZE: return "Invalid input size";
case AF_ERR_TYPE: return "Function does not support this data type";
case AF_ERR_DIFF_TYPE: return "Input types are not the same";
case AF_ERR_BATCH: return "Invalid batch configuration";
case AF_ERR_NOT_SUPPORTED: return "Function not supported";
case AF_ERR_NOT_CONFIGURED: return "Function not configured to build";
case AF_ERR_NONFREE: return "Function unavailable."
"ArrayFire compiled without Non-Free algorithms support";
case AF_ERR_NO_DBL: return "Double precision not supported for this device";
case AF_ERR_NO_GFX: return "Graphics functionality unavailable."
"ArrayFire compiled without Graphics support";
case AF_ERR_LOAD_LIB: return "Failed to load dynamic library."
"See http://www.arrayfire.com/docs/unifiedbackend.htm"
"for instructions to set up environment for Unified backend";
case AF_ERR_LOAD_SYM: return "Failed to load symbol";
case AF_ERR_ARR_BKND_MISMATCH: return "There was a mismatch between an array and the current backend";
case AF_ERR_INTERNAL: return "Internal error";
case AF_ERR_UNKNOWN:
default: return "Unknown error";
}
}
af_err processException()
{
stringstream ss;
af_err err= AF_ERR_INTERNAL;
try {
throw;
} catch (const DimensionError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid dimension for argument " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_SIZE;
} catch (const ArgumentError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid argument at index " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_ARG;
} catch (const SupportError &ex) {
ss << ex.getFunctionName()
<< " not supported for " << ex.getBackendName()
<< " backend\n";
print_error(ss.str());
err = AF_ERR_NOT_SUPPORTED;
} catch (const TypeError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid type for argument " << ex.getArgIndex() << "\n";
print_error(ss.str());
err = AF_ERR_TYPE;
} catch (const AfError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< ex.what() << "\n";
print_error(ss.str());
err = ex.getError();
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
} catch (const fg::Error &ex) {
ss << ex << "\n";
print_error(ss.str());
err = AF_ERR_INTERNAL;
#endif
} catch (...) {
print_error(ss.str());
err = AF_ERR_UNKNOWN;
}
return err;
}
<commit_msg>af_get_last_error supports NULL as valid argument for len<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/exception.h>
#include <af/device.h>
#include <err_common.hpp>
#include <type_util.hpp>
#include <util.hpp>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
#include <graphics_common.hpp>
#endif
using std::string;
using std::stringstream;
AfError::AfError(const char * const func,
const char * const file,
const int line,
const char * const message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
AfError::AfError(string func,
string file,
const int line,
string message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
const string&
AfError::getFunctionName() const
{
return functionName;
}
const string&
AfError::getFileName() const
{
return fileName;
}
int
AfError::getLine() const
{
return lineNumber;
}
af_err
AfError::getError() const
{
return error;
}
AfError::~AfError() throw() {}
TypeError::TypeError(const char * const func,
const char * const file,
const int line,
const int index, const af_dtype type)
: AfError (func, file, line, "Invalid data type", AF_ERR_TYPE),
argIndex(index),
errTypeName(getName(type))
{}
const string& TypeError::getTypeName() const
{
return errTypeName;
}
int TypeError::getArgIndex() const
{
return argIndex;
}
ArgumentError::ArgumentError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid argument", AF_ERR_ARG),
argIndex(index),
expected(expectString)
{
}
const string& ArgumentError::getExpectedCondition() const
{
return expected;
}
int ArgumentError::getArgIndex() const
{
return argIndex;
}
SupportError::SupportError(const char * const func,
const char * const file,
const int line,
const char * const back)
: AfError(func, file, line, "Unsupported Error", AF_ERR_NOT_SUPPORTED),
backend(back)
{}
const string& SupportError::getBackendName() const
{
return backend;
}
DimensionError::DimensionError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid size", AF_ERR_SIZE),
argIndex(index),
expected(expectString)
{
}
const string& DimensionError::getExpectedCondition() const
{
return expected;
}
int DimensionError::getArgIndex() const
{
return argIndex;
}
static const int MAX_ERR_SIZE = 1024;
static std::string global_err_string;
void
print_error(const string &msg)
{
std::string perr = getEnvVar("AF_PRINT_ERRORS");
if(!perr.empty()) {
if(perr != "0")
fprintf(stderr, "%s\n", msg.c_str());
}
global_err_string = msg;
}
void af_get_last_error(char **str, dim_t *len)
{
dim_t slen = std::min(MAX_ERR_SIZE, (int)global_err_string.size());
if (len && slen == 0) {
*len = 0;
*str = NULL;
return;
}
af_alloc_host((void**)str, sizeof(char) * (slen + 1));
global_err_string.copy(*str, slen);
(*str)[slen] = '\0';
global_err_string = std::string("");
if(len) *len = slen;
}
const char *af_err_to_string(const af_err err)
{
switch (err) {
case AF_SUCCESS: return "Success";
case AF_ERR_NO_MEM: return "Device out of memory";
case AF_ERR_DRIVER: return "Driver not available or incompatible";
case AF_ERR_RUNTIME: return "Runtime error ";
case AF_ERR_INVALID_ARRAY: return "Invalid array";
case AF_ERR_ARG: return "Invalid input argument";
case AF_ERR_SIZE: return "Invalid input size";
case AF_ERR_TYPE: return "Function does not support this data type";
case AF_ERR_DIFF_TYPE: return "Input types are not the same";
case AF_ERR_BATCH: return "Invalid batch configuration";
case AF_ERR_NOT_SUPPORTED: return "Function not supported";
case AF_ERR_NOT_CONFIGURED: return "Function not configured to build";
case AF_ERR_NONFREE: return "Function unavailable."
"ArrayFire compiled without Non-Free algorithms support";
case AF_ERR_NO_DBL: return "Double precision not supported for this device";
case AF_ERR_NO_GFX: return "Graphics functionality unavailable."
"ArrayFire compiled without Graphics support";
case AF_ERR_LOAD_LIB: return "Failed to load dynamic library."
"See http://www.arrayfire.com/docs/unifiedbackend.htm"
"for instructions to set up environment for Unified backend";
case AF_ERR_LOAD_SYM: return "Failed to load symbol";
case AF_ERR_ARR_BKND_MISMATCH: return "There was a mismatch between an array and the current backend";
case AF_ERR_INTERNAL: return "Internal error";
case AF_ERR_UNKNOWN:
default: return "Unknown error";
}
}
af_err processException()
{
stringstream ss;
af_err err= AF_ERR_INTERNAL;
try {
throw;
} catch (const DimensionError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid dimension for argument " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_SIZE;
} catch (const ArgumentError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid argument at index " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_ARG;
} catch (const SupportError &ex) {
ss << ex.getFunctionName()
<< " not supported for " << ex.getBackendName()
<< " backend\n";
print_error(ss.str());
err = AF_ERR_NOT_SUPPORTED;
} catch (const TypeError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid type for argument " << ex.getArgIndex() << "\n";
print_error(ss.str());
err = AF_ERR_TYPE;
} catch (const AfError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< ex.what() << "\n";
print_error(ss.str());
err = ex.getError();
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
} catch (const fg::Error &ex) {
ss << ex << "\n";
print_error(ss.str());
err = AF_ERR_INTERNAL;
#endif
} catch (...) {
print_error(ss.str());
err = AF_ERR_UNKNOWN;
}
return err;
}
<|endoftext|> |
<commit_before>#include "rust_box.h"
#include "rust_gc.h"
#include "rust_internal.h"
#include "rust_unwind.h"
#include "rust_upcall.h"
#include <stdint.h>
// Upcalls.
#ifdef __i386__
void
check_stack(rust_task *task) {
void *esp;
asm volatile("movl %%esp,%0" : "=r" (esp));
if (esp < task->stk->data)
task->kernel->fatal("Out of stack space, sorry");
}
#else
#warning "Stack checks are not supported on this architecture"
void
check_stack(rust_task *task) {
// TODO
}
#endif
// Copy elements from one vector to another,
// dealing with reference counts
static inline void
copy_elements(rust_task *task, type_desc *elem_t,
void *pdst, void *psrc, size_t n)
{
char *dst = (char *)pdst, *src = (char *)psrc;
memmove(dst, src, n);
// increment the refcount of each element of the vector
if (elem_t->take_glue) {
glue_fn *take_glue = elem_t->take_glue;
size_t elem_size = elem_t->size;
const type_desc **tydescs = elem_t->first_param;
for (char *p = dst; p < dst+n; p += elem_size) {
take_glue(NULL, task, NULL, tydescs, p);
}
}
}
extern "C" CDECL void
upcall_fail(rust_task *task,
char const *expr,
char const *file,
size_t line) {
LOG_UPCALL_ENTRY(task);
LOG_ERR(task, upcall, "upcall fail '%s', %s:%" PRIdPTR, expr, file, line);
task->fail();
}
extern "C" CDECL uintptr_t
upcall_malloc(rust_task *task, size_t nbytes, type_desc *td) {
LOG_UPCALL_ENTRY(task);
LOG(task, mem,
"upcall malloc(%" PRIdPTR ", 0x%" PRIxPTR ")"
" with gc-chain head = 0x%" PRIxPTR,
nbytes, td, task->gc_alloc_chain);
gc::maybe_gc(task);
// TODO: Maybe use dladdr here to find a more useful name for the
// type_desc.
void *p = task->malloc(nbytes, "tdesc", td);
LOG(task, mem,
"upcall malloc(%" PRIdPTR ", 0x%" PRIxPTR
") = 0x%" PRIxPTR
" with gc-chain head = 0x%" PRIxPTR,
nbytes, td, (uintptr_t)p, task->gc_alloc_chain);
return (uintptr_t) p;
}
/**
* Called whenever an object's ref count drops to zero.
*/
extern "C" CDECL void
upcall_free(rust_task *task, void* ptr, uintptr_t is_gc) {
LOG_UPCALL_ENTRY(task);
rust_scheduler *sched = task->sched;
DLOG(sched, mem,
"upcall free(0x%" PRIxPTR ", is_gc=%" PRIdPTR ")",
(uintptr_t)ptr, is_gc);
task->free(ptr, (bool) is_gc);
}
extern "C" CDECL uintptr_t
upcall_shared_malloc(rust_task *task, size_t nbytes, type_desc *td) {
LOG_UPCALL_ENTRY(task);
LOG(task, mem,
"upcall shared_malloc(%" PRIdPTR ", 0x%" PRIxPTR ")",
nbytes, td);
void *p = task->kernel->malloc(nbytes, "shared malloc");
LOG(task, mem,
"upcall shared_malloc(%" PRIdPTR ", 0x%" PRIxPTR
") = 0x%" PRIxPTR,
nbytes, td, (uintptr_t)p);
return (uintptr_t) p;
}
/**
* Called whenever an object's ref count drops to zero.
*/
extern "C" CDECL void
upcall_shared_free(rust_task *task, void* ptr) {
LOG_UPCALL_ENTRY(task);
rust_scheduler *sched = task->sched;
DLOG(sched, mem,
"upcall shared_free(0x%" PRIxPTR")",
(uintptr_t)ptr);
task->kernel->free(ptr);
}
extern "C" CDECL type_desc *
upcall_get_type_desc(rust_task *task,
void *curr_crate, // ignored, legacy compat.
size_t size,
size_t align,
size_t n_descs,
type_desc const **descs,
uintptr_t n_obj_params) {
check_stack(task);
LOG_UPCALL_ENTRY(task);
LOG(task, cache, "upcall get_type_desc with size=%" PRIdPTR
", align=%" PRIdPTR ", %" PRIdPTR " descs", size, align,
n_descs);
rust_crate_cache *cache = task->get_crate_cache();
type_desc *td = cache->get_type_desc(size, align, n_descs, descs,
n_obj_params);
LOG(task, cache, "returning tydesc 0x%" PRIxPTR, td);
return td;
}
extern "C" CDECL void
upcall_vec_grow(rust_task* task, rust_vec** vp, size_t new_sz) {
LOG_UPCALL_ENTRY(task);
reserve_vec(task, vp, new_sz);
(*vp)->fill = new_sz;
}
extern "C" CDECL void
upcall_vec_push(rust_task* task, rust_vec** vp, type_desc* elt_ty,
void* elt) {
LOG_UPCALL_ENTRY(task);
size_t new_sz = (*vp)->fill + elt_ty->size;
reserve_vec(task, vp, new_sz);
rust_vec* v = *vp;
copy_elements(task, elt_ty, &v->data[0] + v->fill, elt, elt_ty->size);
v->fill += elt_ty->size;
}
/**
* Returns a token that can be used to deallocate all of the allocated space
* space in the dynamic stack.
*/
extern "C" CDECL void *
upcall_dynastack_mark(rust_task *task) {
return task->dynastack.mark();
}
/**
* Allocates space in the dynamic stack and returns it.
*
* FIXME: Deprecated since dynamic stacks need to be self-describing for GC.
*/
extern "C" CDECL void *
upcall_dynastack_alloc(rust_task *task, size_t sz) {
return sz ? task->dynastack.alloc(sz, NULL) : NULL;
}
/**
* Allocates space associated with a type descriptor in the dynamic stack and
* returns it.
*/
extern "C" CDECL void *
upcall_dynastack_alloc_2(rust_task *task, size_t sz, type_desc *ty) {
return sz ? task->dynastack.alloc(sz, ty) : NULL;
}
/** Frees space in the dynamic stack. */
extern "C" CDECL void
upcall_dynastack_free(rust_task *task, void *ptr) {
return task->dynastack.free(ptr);
}
extern "C" _Unwind_Reason_Code
__gxx_personality_v0(int version,
_Unwind_Action actions,
uint64_t exception_class,
_Unwind_Exception *ue_header,
_Unwind_Context *context);
extern "C" _Unwind_Reason_Code
upcall_rust_personality(int version,
_Unwind_Action actions,
uint64_t exception_class,
_Unwind_Exception *ue_header,
_Unwind_Context *context) {
return __gxx_personality_v0(version,
actions,
exception_class,
ue_header,
context);
}
//
// Local Variables:
// mode: C++
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<commit_msg>rt: Remove #include "rust_box.h"<commit_after>#include "rust_gc.h"
#include "rust_internal.h"
#include "rust_unwind.h"
#include "rust_upcall.h"
#include <stdint.h>
// Upcalls.
#ifdef __i386__
void
check_stack(rust_task *task) {
void *esp;
asm volatile("movl %%esp,%0" : "=r" (esp));
if (esp < task->stk->data)
task->kernel->fatal("Out of stack space, sorry");
}
#else
#warning "Stack checks are not supported on this architecture"
void
check_stack(rust_task *task) {
// TODO
}
#endif
// Copy elements from one vector to another,
// dealing with reference counts
static inline void
copy_elements(rust_task *task, type_desc *elem_t,
void *pdst, void *psrc, size_t n)
{
char *dst = (char *)pdst, *src = (char *)psrc;
memmove(dst, src, n);
// increment the refcount of each element of the vector
if (elem_t->take_glue) {
glue_fn *take_glue = elem_t->take_glue;
size_t elem_size = elem_t->size;
const type_desc **tydescs = elem_t->first_param;
for (char *p = dst; p < dst+n; p += elem_size) {
take_glue(NULL, task, NULL, tydescs, p);
}
}
}
extern "C" CDECL void
upcall_fail(rust_task *task,
char const *expr,
char const *file,
size_t line) {
LOG_UPCALL_ENTRY(task);
LOG_ERR(task, upcall, "upcall fail '%s', %s:%" PRIdPTR, expr, file, line);
task->fail();
}
extern "C" CDECL uintptr_t
upcall_malloc(rust_task *task, size_t nbytes, type_desc *td) {
LOG_UPCALL_ENTRY(task);
LOG(task, mem,
"upcall malloc(%" PRIdPTR ", 0x%" PRIxPTR ")"
" with gc-chain head = 0x%" PRIxPTR,
nbytes, td, task->gc_alloc_chain);
gc::maybe_gc(task);
// TODO: Maybe use dladdr here to find a more useful name for the
// type_desc.
void *p = task->malloc(nbytes, "tdesc", td);
LOG(task, mem,
"upcall malloc(%" PRIdPTR ", 0x%" PRIxPTR
") = 0x%" PRIxPTR
" with gc-chain head = 0x%" PRIxPTR,
nbytes, td, (uintptr_t)p, task->gc_alloc_chain);
return (uintptr_t) p;
}
/**
* Called whenever an object's ref count drops to zero.
*/
extern "C" CDECL void
upcall_free(rust_task *task, void* ptr, uintptr_t is_gc) {
LOG_UPCALL_ENTRY(task);
rust_scheduler *sched = task->sched;
DLOG(sched, mem,
"upcall free(0x%" PRIxPTR ", is_gc=%" PRIdPTR ")",
(uintptr_t)ptr, is_gc);
task->free(ptr, (bool) is_gc);
}
extern "C" CDECL uintptr_t
upcall_shared_malloc(rust_task *task, size_t nbytes, type_desc *td) {
LOG_UPCALL_ENTRY(task);
LOG(task, mem,
"upcall shared_malloc(%" PRIdPTR ", 0x%" PRIxPTR ")",
nbytes, td);
void *p = task->kernel->malloc(nbytes, "shared malloc");
LOG(task, mem,
"upcall shared_malloc(%" PRIdPTR ", 0x%" PRIxPTR
") = 0x%" PRIxPTR,
nbytes, td, (uintptr_t)p);
return (uintptr_t) p;
}
/**
* Called whenever an object's ref count drops to zero.
*/
extern "C" CDECL void
upcall_shared_free(rust_task *task, void* ptr) {
LOG_UPCALL_ENTRY(task);
rust_scheduler *sched = task->sched;
DLOG(sched, mem,
"upcall shared_free(0x%" PRIxPTR")",
(uintptr_t)ptr);
task->kernel->free(ptr);
}
extern "C" CDECL type_desc *
upcall_get_type_desc(rust_task *task,
void *curr_crate, // ignored, legacy compat.
size_t size,
size_t align,
size_t n_descs,
type_desc const **descs,
uintptr_t n_obj_params) {
check_stack(task);
LOG_UPCALL_ENTRY(task);
LOG(task, cache, "upcall get_type_desc with size=%" PRIdPTR
", align=%" PRIdPTR ", %" PRIdPTR " descs", size, align,
n_descs);
rust_crate_cache *cache = task->get_crate_cache();
type_desc *td = cache->get_type_desc(size, align, n_descs, descs,
n_obj_params);
LOG(task, cache, "returning tydesc 0x%" PRIxPTR, td);
return td;
}
extern "C" CDECL void
upcall_vec_grow(rust_task* task, rust_vec** vp, size_t new_sz) {
LOG_UPCALL_ENTRY(task);
reserve_vec(task, vp, new_sz);
(*vp)->fill = new_sz;
}
extern "C" CDECL void
upcall_vec_push(rust_task* task, rust_vec** vp, type_desc* elt_ty,
void* elt) {
LOG_UPCALL_ENTRY(task);
size_t new_sz = (*vp)->fill + elt_ty->size;
reserve_vec(task, vp, new_sz);
rust_vec* v = *vp;
copy_elements(task, elt_ty, &v->data[0] + v->fill, elt, elt_ty->size);
v->fill += elt_ty->size;
}
/**
* Returns a token that can be used to deallocate all of the allocated space
* space in the dynamic stack.
*/
extern "C" CDECL void *
upcall_dynastack_mark(rust_task *task) {
return task->dynastack.mark();
}
/**
* Allocates space in the dynamic stack and returns it.
*
* FIXME: Deprecated since dynamic stacks need to be self-describing for GC.
*/
extern "C" CDECL void *
upcall_dynastack_alloc(rust_task *task, size_t sz) {
return sz ? task->dynastack.alloc(sz, NULL) : NULL;
}
/**
* Allocates space associated with a type descriptor in the dynamic stack and
* returns it.
*/
extern "C" CDECL void *
upcall_dynastack_alloc_2(rust_task *task, size_t sz, type_desc *ty) {
return sz ? task->dynastack.alloc(sz, ty) : NULL;
}
/** Frees space in the dynamic stack. */
extern "C" CDECL void
upcall_dynastack_free(rust_task *task, void *ptr) {
return task->dynastack.free(ptr);
}
extern "C" _Unwind_Reason_Code
__gxx_personality_v0(int version,
_Unwind_Action actions,
uint64_t exception_class,
_Unwind_Exception *ue_header,
_Unwind_Context *context);
extern "C" _Unwind_Reason_Code
upcall_rust_personality(int version,
_Unwind_Action actions,
uint64_t exception_class,
_Unwind_Exception *ue_header,
_Unwind_Context *context) {
return __gxx_personality_v0(version,
actions,
exception_class,
ue_header,
context);
}
//
// Local Variables:
// mode: C++
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<|endoftext|> |
<commit_before>#ifndef JSON_INTERNAL_HH
#define JSON_INTERNAL_HH
#include "nlohmann/json.hpp"
#include "package.hh"
namespace aur {
// NB: We only really need the Package overload of from_json here. All known
// overloads of from_json are listed anyways for consistency.
void from_json(const nlohmann::json& j, Package& p);
template <typename T>
void from_json(const nlohmann::json& j, T& s) {
if (j.is_null()) {
return;
}
s = j.get<T>();
}
template <typename T>
void from_json(const nlohmann::json& j, std::vector<T>& vs) {
if (j.is_null()) {
return;
}
vs.reserve(j.size());
for (auto iter = j.begin(); iter != j.end(); iter++) {
vs.emplace_back(iter->get<T>());
}
}
} // namespace aur
#endif // JSON_INTERNAL_HH
<commit_msg>Drop inaccurate comment<commit_after>#ifndef JSON_INTERNAL_HH
#define JSON_INTERNAL_HH
#include "nlohmann/json.hpp"
#include "package.hh"
namespace aur {
void from_json(const nlohmann::json& j, Package& p);
template <typename T>
void from_json(const nlohmann::json& j, T& s) {
if (j.is_null()) {
return;
}
s = j.get<T>();
}
template <typename T>
void from_json(const nlohmann::json& j, std::vector<T>& vs) {
if (j.is_null()) {
return;
}
vs.reserve(j.size());
for (auto iter = j.begin(); iter != j.end(); iter++) {
vs.emplace_back(iter->get<T>());
}
}
} // namespace aur
#endif // JSON_INTERNAL_HH
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <functional>
#include "source.h"
#include "sync.h"
#include "proc/synthetic-stream.h"
#include "proc/syncer-processing-block.h"
namespace librealsense
{
syncer_process_unit::syncer_process_unit( std::initializer_list< bool_option::ptr > enable_opts,
bool log )
: processing_block( "syncer" )
, _enable_opts( enable_opts.begin(), enable_opts.end() )
{
// This callback gets called by the previous processing block when it is done with a frame. We
// call the matchers with the frame and eventually call the next callback in the list using frame_ready().
// This callback can get called from multiple threads, one thread per stream -- but always in the correct
// frame order per stream.
auto f = [this, log]( frame_holder frame, synthetic_source_interface * source ) {
// if the syncer is disabled passthrough the frame
bool enabled = false;
size_t n_opts = 0;
for( auto & wopt : _enable_opts )
{
auto opt = wopt.lock();
if( opt )
{
++n_opts;
if( opt->is_true() )
{
enabled = true;
break;
}
}
}
if( n_opts && ! enabled )
{
get_source().frame_ready( std::move( frame ) );
return;
}
{
std::lock_guard< std::mutex > lock( _mutex );
if( !_matcher )
{
if(!create_matcher( frame ))
get_source().frame_ready(std::move(frame));
}
else
{
auto env = syncronization_environment{ source, _matches, log };
_matcher->dispatch(std::move(frame), env);
}
}
frame_holder f;
{
// Another thread has the lock, meaning will get into the following loop and dequeue all
// the frames. So there's nothing for us to do...
std::unique_lock< std::mutex > lock(_callback_mutex, std::try_to_lock);
if (!lock.owns_lock())
return;
while( _matches.try_dequeue( &f ) )
{
get_source().frame_ready( std::move( f ) );
}
}
};
set_processing_callback( std::shared_ptr< rs2_frame_processor_callback >(
new internal_frame_processor_callback< decltype( f ) >( f ) ) );
}
bool syncer_process_unit::create_matcher( const frame_holder & frame )
{
try
{
auto sensor = frame.frame->get_sensor().get();
if (!sensor)
{
LOG_DEBUG("Sensor is not exist any more cannot create matcher the frame will passthrough ");
return false;
}
const device_interface * dev = nullptr;
dev = sensor->get_device().shared_from_this().get();
if (dev)
{
_matcher = dev->create_matcher(frame);
_matcher->set_callback([this](frame_holder f, const syncronization_environment& env) {
if (env.log)
{
LOG_DEBUG("SYNCED: " << frame_to_string(f));
}
// We get here from within a dispatch() call, already protected by a mutex -- so only one thread can enqueue!
env.matches.enqueue(std::move(f));
});
}
else
{
LOG_DEBUG("Device is not exist any more cannot create matcher, the frame will passthrough ");
return false;
}
}
catch( const std::bad_weak_ptr & )
{
LOG_DEBUG("Device was destroyed while trying get shared ptr of it, couldn't create matcher, the frame will passthrough ");
return false;
}
return true;
}
} // namespace librealsense
<commit_msg>Fixed small bug<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include <functional>
#include "source.h"
#include "sync.h"
#include "proc/synthetic-stream.h"
#include "proc/syncer-processing-block.h"
namespace librealsense
{
syncer_process_unit::syncer_process_unit( std::initializer_list< bool_option::ptr > enable_opts,
bool log )
: processing_block( "syncer" )
, _enable_opts( enable_opts.begin(), enable_opts.end() )
{
// This callback gets called by the previous processing block when it is done with a frame. We
// call the matchers with the frame and eventually call the next callback in the list using frame_ready().
// This callback can get called from multiple threads, one thread per stream -- but always in the correct
// frame order per stream.
auto f = [this, log]( frame_holder frame, synthetic_source_interface * source ) {
// if the syncer is disabled passthrough the frame
bool enabled = false;
size_t n_opts = 0;
for( auto & wopt : _enable_opts )
{
auto opt = wopt.lock();
if( opt )
{
++n_opts;
if( opt->is_true() )
{
enabled = true;
break;
}
}
}
if( n_opts && ! enabled )
{
get_source().frame_ready( std::move( frame ) );
return;
}
{
std::lock_guard< std::mutex > lock( _mutex );
if( ! _matcher )
{
if( ! create_matcher( frame ) )
{
get_source().frame_ready( std::move( frame ) );
return;
}
}
auto env = syncronization_environment{ source, _matches, log };
_matcher->dispatch( std::move( frame ), env );
}
frame_holder f;
{
// Another thread has the lock, meaning will get into the following loop and dequeue all
// the frames. So there's nothing for us to do...
std::unique_lock< std::mutex > lock(_callback_mutex, std::try_to_lock);
if (!lock.owns_lock())
return;
while( _matches.try_dequeue( &f ) )
{
LOG_DEBUG("dequeue: " << frame_to_string(f));
get_source().frame_ready( std::move( f ) );
}
}
};
set_processing_callback( std::shared_ptr< rs2_frame_processor_callback >(
new internal_frame_processor_callback< decltype( f ) >( f ) ) );
}
bool syncer_process_unit::create_matcher( const frame_holder & frame )
{
try
{
auto sensor = frame.frame->get_sensor().get();
if (!sensor)
{
LOG_DEBUG("Sensor is not exist any more cannot create matcher the frame will passthrough ");
return false;
}
const device_interface * dev = nullptr;
dev = sensor->get_device().shared_from_this().get();
if (dev)
{
_matcher = dev->create_matcher(frame);
_matcher->set_callback([this](frame_holder f, const syncronization_environment& env) {
if (env.log)
{
LOG_DEBUG("SYNCED: " << frame_to_string(f));
}
// We get here from within a dispatch() call, already protected by a mutex -- so only one thread can enqueue!
env.matches.enqueue(std::move(f));
});
}
else
{
LOG_DEBUG("Device is not exist any more cannot create matcher, the frame will passthrough ");
return false;
}
}
catch( const std::bad_weak_ptr & )
{
LOG_DEBUG("Device was destroyed while trying get shared ptr of it, couldn't create matcher, the frame will passthrough ");
return false;
}
return true;
}
} // namespace librealsense
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <cstdio>
#define MAX 10000
using namespace std;
int W, N, X, Y, counter, temp, V[MAX][MAX], wt[MAX], val[MAX], arr[MAX];
bool keep[MAX][MAX];
int main() {
//cout << "Enter The Number Of Items And Max Weight Of Knapsack
cin >> N >> W;
//Enter The Weight And Value Of Each Of The "N" Items
for (int i = 1; i <= N; i++)
cin >> wt[i] >> val[i];
for (int i = 0; i <= N; i++) {
for (int j = 1; j <= W; j++ ) {
if (i == 0) {
V[i][j] = 0;
keep[i][j] = 0;
}
else {
temp = val[i];
if (j - wt[i] > 0)
temp += V[i-1][j-wt[i]];
if (wt[i] <= j && temp > V[i-1][j]) {
keep[i][j] = 1;
V[i][j] = temp;
}
else {
keep[i][j] = 0;
V[i][j] = V[i-1][j];
}
}
}
}
X = N;
Y = W;
counter = 0;
/*
Value Matrix
for (int i = 0; i <= N; i++) {
for (int j = 1; j <= W; j++)
printf("%-6d", V[i][j]);
cout << endl;
}
*/
while (Y > 0 && X > 0) {
if (keep[X][Y]) {
arr[counter++] = X;
Y -= wt[X];
X--;
}
else
X--;
}
if (!counter)
cout << "No Solution For Knapsack." << endl;
else {
for (int i = counter-1; i >= 0; i--) {
cout << arr[i];
if (i != 0)
cout << ", ";
}
cout << " Are The Element(s) Of The Knapsack. Max Weight = " << V[N][W] << endl;
}
return 0;
}
<commit_msg>remove KnapsackDP.cpp<commit_after><|endoftext|> |
<commit_before>/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Worcester Polytechnic Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Worcester Polytechnic Institute nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************/
/*!
* \file robot_pose_publisher.cpp
* \brief Publishes the robot's position in a geometry_msgs/Pose message.
*
* Publishes the robot's position in a geometry_msgs/Pose message based on the TF
* difference between /map and /base_link.
*
* \author Russell Toris, WPI - rctoris@wpi.edu
* \date Sept 12, 2012
*/
#include <geometry_msgs/PoseStamped.h>
#include <ros/ros.h>
#include <tf/transform_listener.h>
/*!
* Creates and runs the robot_pose_publisher node.
*
* \param argc argument count that is passed to ros::init
* \param argv arguments that are passed to ros::init
* \return EXIT_SUCCESS if the node runs correctly
*/
int main(int argc, char ** argv)
{
// initialize ROS and the node
ros::init(argc, argv, "robot_pose_publisher");
ros::NodeHandle nh;
// configuring parameters
std::string map_frame, base_frame;
double publish_frequency;
nh.param<std::string>("map_frame",map_frame,"/map");
nh.param<std::string>("base_frame",base_frame,"/base_link");
nh.param<double>("publish_frequency",publish_frequency,10);
ros::Publisher posestamped_pub = nh.advertise<geometry_msgs::PoseStamped>("robot_pose", 1);
// create the listener
tf::TransformListener listener;
listener.waitForTransform(map_frame, base_frame, ros::Time(), ros::Duration(1.0));
ros::Rate rate(publish_frequency);
while (nh.ok())
{
tf::StampedTransform transform;
try
{
listener.lookupTransform(map_frame, base_frame, ros::Time(0), transform);
// construct a pose message
geometry_msgs::PoseStamped pose_stamped;
pose_stamped.header.frame_id = map_frame;
pose_stamped.header.stamp = ros::Time::now();
pose_stamped.pose.orientation.x = transform.getRotation().getX();
pose_stamped.pose.orientation.y = transform.getRotation().getY();
pose_stamped.pose.orientation.z = transform.getRotation().getZ();
pose_stamped.pose.orientation.w = transform.getRotation().getW();
pose_stamped.pose.position.x = transform.getOrigin().getX();
pose_stamped.pose.position.y = transform.getOrigin().getY();
pose_stamped.pose.position.z = transform.getOrigin().getZ();
posestamped_pub.publish(pose_stamped);
}
catch (tf::TransformException &ex)
{
// just continue on
}
rate.sleep();
}
return EXIT_SUCCESS;
}
<commit_msg>is_stamped param added<commit_after>/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Worcester Polytechnic Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Worcester Polytechnic Institute nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************/
/*!
* \file robot_pose_publisher.cpp
* \brief Publishes the robot's position in a geometry_msgs/Pose message.
*
* Publishes the robot's position in a geometry_msgs/Pose message based on the TF
* difference between /map and /base_link.
*
* \author Russell Toris, WPI - rctoris@wpi.edu
* \date Sept 12, 2012
*/
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <ros/ros.h>
#include <tf/transform_listener.h>
/*!
* Creates and runs the robot_pose_publisher node.
*
* \param argc argument count that is passed to ros::init
* \param argv arguments that are passed to ros::init
* \return EXIT_SUCCESS if the node runs correctly
*/
int main(int argc, char ** argv)
{
// initialize ROS and the node
ros::init(argc, argv, "robot_pose_publisher");
ros::NodeHandle nh;
// configuring parameters
std::string map_frame, base_frame;
double publish_frequency;
bool is_stamped;
ros::Publisher p_pub;
nh.param<std::string>("map_frame",map_frame,"/map");
nh.param<std::string>("base_frame",base_frame,"/base_link");
nh.param<double>("publish_frequency",publish_frequency,10);
nh.param<bool>("is_stamped", is_stamped, false);
if(is_stamped)
p_pub = nh.advertise<geometry_msgs::PoseStamped>("robot_pose", 1);
else
p_pub = nh.advertise<geometry_msgs::Pose>("robot_pose", 1);
// create the listener
tf::TransformListener listener;
listener.waitForTransform(map_frame, base_frame, ros::Time(), ros::Duration(1.0));
ros::Rate rate(publish_frequency);
while (nh.ok())
{
tf::StampedTransform transform;
try
{
listener.lookupTransform(map_frame, base_frame, ros::Time(0), transform);
// construct a pose message
geometry_msgs::PoseStamped pose_stamped;
pose_stamped.header.frame_id = map_frame;
pose_stamped.header.stamp = ros::Time::now();
pose_stamped.pose.orientation.x = transform.getRotation().getX();
pose_stamped.pose.orientation.y = transform.getRotation().getY();
pose_stamped.pose.orientation.z = transform.getRotation().getZ();
pose_stamped.pose.orientation.w = transform.getRotation().getW();
pose_stamped.pose.position.x = transform.getOrigin().getX();
pose_stamped.pose.position.y = transform.getOrigin().getY();
pose_stamped.pose.position.z = transform.getOrigin().getZ();
if(is_stamped)
p_pub.publish(pose_stamped);
else
p_pub.publish(pose_stamped.pose);
}
catch (tf::TransformException &ex)
{
// just continue on
}
rate.sleep();
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <glog/logging.h>
#include <algorithm>
#include <map>
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/ngraph_bridge.h"
#include "paddle/fluid/framework/ngraph_operator.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/framework/var_desc.h"
#include "paddle/fluid/framework/var_type.h"
#include "ngraph/ngraph.hpp"
namespace paddle {
namespace framework {
static ngraph::Shape Ddim2Shape(const DDim& dims) {
ngraph::Shape sp;
for (int i = 0; i < dims.size(); ++i) {
int k = dims[i];
k = k == 0 ? 1 : k;
sp.push_back(k);
}
return sp;
}
static std::map<proto::VarType::Type, ngraph::element::Type> pd2ng_type_map = {
{proto::VarType::FP32, ngraph::element::f32},
{proto::VarType::FP64, ngraph::element::f64},
{proto::VarType::INT32, ngraph::element::i32},
{proto::VarType::INT64, ngraph::element::i64},
{proto::VarType::BOOL, ngraph::element::boolean},
};
typedef enum { /* nGraph support state on ops */
FULL_TRAIN, /* Support full ops for train */
PARTIAL_TRAIN, /* Support partial ops for train */
FULL_TEST, /* Support full list of ops for test */
PARTIAL_TEST /* Support partial list of ops for test */
} op_state;
// perform graph build through bridge and execute computation
class NgraphEngine {
public:
explicit NgraphEngine(const Scope& scope, const platform::Place& place,
const std::vector<std::shared_ptr<OperatorBase>>& ops,
const std::unordered_map<
std::string, ngraph::element::Type>& var_type_map,
const std::unordered_set<std::string>& persist,
const std::unordered_set<std::string>& fetches,
const std::unordered_set<std::string>& post_op_inputs,
op_state ng_op_state)
: scope_(scope),
place_(place),
fused_ops_(ops),
var_type_map_(var_type_map),
persistables_(persist),
fetches_(fetches),
post_op_inputs_(post_op_inputs),
ng_op_state_(ng_op_state) {
var_in_node_map_ = std::make_shared<
std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>();
var_node_map_ = std::make_shared<
std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>();
BuildNgIO();
GetNgFunction();
}
void Run(const Scope& scope, const platform::Place& place) const;
private:
static std::unordered_map<std::string, std::shared_ptr<ngraph::Function>>
func_cache_;
const Scope& scope_;
const platform::Place& place_;
std::vector<std::shared_ptr<OperatorBase>> fused_ops_;
std::unordered_map<std::string, ngraph::element::Type> var_type_map_;
std::unordered_set<std::string> persistables_;
std::unordered_set<std::string> fetches_;
std::unordered_set<std::string> post_op_inputs_;
op_state ng_op_state_;
// ngraph backend eg. CPU
static std::shared_ptr<ngraph::runtime::Backend> backend_;
// ngraph function to call and execute
std::shared_ptr<ngraph::Function> ngraph_function_;
// var_name of inputs
std::vector<std::string> var_in_;
// var_name of outputs from fetch in order
std::vector<std::string> var_out_;
// map input vars to nodes
std::shared_ptr<
std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
var_in_node_map_;
// map each var name with a ngraph node
std::shared_ptr<
std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>
var_node_map_;
// cache key to check if function is cached
std::shared_ptr<std::string> GetCacheKey();
// get ngraph input and define ngraph input parameters
void GetNgInputShape(std::shared_ptr<OperatorBase> op);
// Call ngraph bridge to map ops
void BuildNgNodes();
// get the ngraph input and output var list
void BuildNgIO();
// build ngraph function call
void BuildNgFunction();
// Check cache for ngraph function or otherwise build the function
void GetNgFunction();
};
std::vector<std::vector<std::vector<std::unique_ptr<OperatorBase>>::iterator>>
NgraphOperator::NgraphOpIntervals(
std::vector<std::unique_ptr<paddle::framework::OperatorBase>>* ops) {
std::vector<std::vector<std::vector<std::unique_ptr<OperatorBase>>::iterator>>
intervals;
if (ops->empty()) {
return intervals;
}
size_t size = ops->size();
size_t left = 0;
while (left < size && ops->at(left)->Type() != kFeedOpType) {
++left;
}
if (left == size) {
return intervals;
}
while (left < size && ops->at(left)->Type() == kFeedOpType) {
++left;
}
size_t right = left;
while (right < size && ops->at(right)->Type() != kFetchOpType) {
++right;
}
if (right == size) {
return intervals;
}
if (left >= right) return intervals;
// (left, right - 1) represents indices between feed and fetch
size_t pivot = left;
while (pivot < right) {
auto op_type = ops->at(pivot)->Type();
if (paddle::framework::NgraphBridge::NG_NODE_MAP.find(op_type) ==
paddle::framework::NgraphBridge::NG_NODE_MAP.end()) {
++pivot;
} else {
size_t start = pivot, end = start;
while (pivot < right &&
(paddle::framework::NgraphBridge::NG_NODE_MAP.find(
ops->at(pivot)->Type()) !=
paddle::framework::NgraphBridge::NG_NODE_MAP.end())) {
++pivot;
++end;
}
std::vector<std::vector<std::unique_ptr<OperatorBase>>::iterator>
interval = {ops->begin() + start, ops->begin() + end};
intervals.push_back(interval);
}
} // end while
return intervals;
}
NgraphOperator::NgraphOperator(
const ProgramDesc& prog, size_t block_id,
std::vector<std::unique_ptr<OperatorBase>>::iterator start,
std::vector<std::unique_ptr<OperatorBase>>::iterator end,
const std::string& type, const VariableNameMap& inputs,
const VariableNameMap& outputs, const AttributeMap& attrs)
: OperatorBase(type, inputs, outputs, attrs),
pdesc_(prog),
block_(block_id) {
for (std::vector<std::unique_ptr<OperatorBase>>::iterator it = start;
it != end; ++it) {
fused_ops_.push_back(std::move(*it));
}
for (std::vector<std::unique_ptr<OperatorBase>>::iterator it = end;
(*it)->Type() != kFetchOpType; ++it) {
for (auto& var_name_item : (*it)->Inputs()) {
for (auto& var_name : var_name_item.second) {
post_op_inputs_.insert(var_name);
}
}
}
if ((*(start - 1))->Type() == kFeedOpType && (*end)->Type() == kFetchOpType) {
is_full_ = true;
}
Process();
}
void NgraphOperator::Process() {
auto& bdesc = pdesc_.Block(block_);
for (auto& var : bdesc.AllVars()) {
if (!(var->GetType() == proto::VarType::SELECTED_ROWS ||
var->GetType() == proto::VarType::LOD_TENSOR ||
var->GetType() == proto::VarType::LOD_TENSOR_ARRAY)) {
continue;
}
auto var_name = var->Name();
if (var->Name() == framework::kEmptyVarName) {
continue;
}
if (var_name != "fetch" && var_name != "feed") {
auto pd_type = var->GetDataType();
if (pd2ng_type_map.find(pd_type) == pd2ng_type_map.end()) {
PADDLE_THROW("Data type of var %s not found in pd2ng_type_map",
var_name);
}
var_type_map_[var_name] = pd2ng_type_map[pd_type];
}
if (var->Persistable()) {
persistables_.insert(var->Name());
}
}
for (auto* op : bdesc.AllOps()) {
if (op->Type() == kFetchOpType) {
std::string fetch_target_name = op->Input("X")[0];
fetches_.insert(fetch_target_name);
}
}
}
void NgraphOperator::RunImpl(const Scope& scope,
const platform::Place& place) const {
op_state ng_op_state = PARTIAL_TEST;
auto& bdesc = pdesc_.Block(block_);
for (auto* op : bdesc.AllOps()) {
if (op->Type().find("_grad") != std::string::npos) {
ng_op_state = PARTIAL_TRAIN;
break;
}
}
if (is_full_) {
ng_op_state = ng_op_state == PARTIAL_TEST ? FULL_TEST : FULL_TRAIN;
}
NgraphEngine ngraph_engine(scope, place, fused_ops_, var_type_map_,
persistables_, fetches_, post_op_inputs_,
ng_op_state);
ngraph_engine.Run(scope, place);
}
std::unordered_map<std::string, std::shared_ptr<ngraph::Function>>
NgraphEngine::func_cache_ = {};
std::shared_ptr<ngraph::runtime::Backend> NgraphEngine::backend_ =
ngraph::runtime::Backend::create("CPU");
void NgraphEngine::GetNgInputShape(std::shared_ptr<OperatorBase> op) {
RuntimeContext ctx(op->Inputs(), op->Outputs(), scope_);
op->RuntimeInferShape(scope_, place_, ctx);
for (auto& var_name_item : op->Inputs()) {
for (auto& var_name : var_name_item.second) {
auto* var = scope_.FindVar(var_name);
if (var && var->IsType<LoDTensor>()) {
auto* tensor_pd = GetLoDTensorOrSelectedRowsValueFromVar(*var);
auto sp = Ddim2Shape(tensor_pd->dims());
if (std::find(var_in_.begin(), var_in_.end(), var_name) !=
var_in_.end()) {
if (var_node_map_->find(var_name) == var_node_map_->end()) {
auto ng_type = var_type_map_.at(var_name);
auto prm =
std::make_shared<ngraph::op::Parameter>(ng_type, sp, true);
(*var_node_map_)[var_name] = prm;
(*var_in_node_map_)[var_name] = prm;
}
}
}
}
}
}
void NgraphEngine::BuildNgNodes() {
for (auto& var_name : var_out_) {
if (var_node_map_->find(var_name) == var_node_map_->end()) {
auto* var = scope_.FindVar(var_name);
if (var && var->IsType<LoDTensor>()) {
auto* tensor_pd = GetLoDTensorOrSelectedRowsValueFromVar(*var);
auto& ddim = tensor_pd->dims();
auto ng_shape = Ddim2Shape(ddim);
auto ng_type = var_type_map_.at(var_name);
auto prm =
std::make_shared<ngraph::op::Parameter>(ng_type, ng_shape, true);
(*var_node_map_)[var_name] = prm;
}
}
}
paddle::framework::NgraphBridge ngb(var_node_map_);
for (auto& op : fused_ops_) {
ngb.BuildNgNode(op);
}
}
void NgraphEngine::BuildNgIO() {
std::unordered_set<std::string> inputs;
std::unordered_set<std::string> outputs;
for (auto& op : fused_ops_) {
for (auto& var_name_item : op->Inputs()) {
for (auto& var_name : var_name_item.second) {
inputs.insert(var_name);
const bool is_output = outputs.find(var_name) != outputs.end();
if (!is_output &&
std::find(var_in_.begin(), var_in_.end(), var_name) ==
var_in_.end()) {
// fill var_in here to keep lhs and rhs order
var_in_.push_back(var_name);
}
}
}
if (op->Type() != "fill_constant") {
GetNgInputShape(op);
}
for (auto& var_name_item : op->Outputs()) {
PADDLE_ENFORCE_LE(var_name_item.second.size(), 1,
"op %s has more than 1 output - Not handling yet",
op->Type());
for (auto& var_name : var_name_item.second) {
outputs.insert(var_name);
}
}
}
// var_out.clear();
for (auto& op : fused_ops_) {
for (auto& var_name_item : op->Outputs()) {
PADDLE_ENFORCE_LE(var_name_item.second.size(), 1,
"op %s has more than 1 output - Not handling yet",
op->Type());
for (auto& var_name : var_name_item.second) {
switch (ng_op_state_) {
case PARTIAL_TEST:
if (post_op_inputs_.find(var_name) != post_op_inputs_.end() ||
fetches_.find(var_name) != fetches_.end()) {
var_out_.push_back(var_name);
}
break;
case FULL_TEST:
if (fetches_.find(var_name) != fetches_.end()) {
var_out_.push_back(var_name);
}
break;
case PARTIAL_TRAIN:
if (fetches_.find(var_name) != fetches_.end() ||
post_op_inputs_.find(var_name) != post_op_inputs_.end() ||
persistables_.find(var_name) != persistables_.end()) {
var_out_.push_back(var_name);
}
break;
case FULL_TRAIN:
if (fetches_.find(var_name) != fetches_.end() ||
persistables_.find(var_name) != persistables_.end()) {
var_out_.push_back(var_name);
}
break;
default:
var_out_.push_back(var_name);
}
}
}
}
}
void NgraphEngine::BuildNgFunction() {
BuildNgNodes();
ngraph_function_ = nullptr;
ngraph::NodeVector func_outputs;
ngraph::ParameterVector func_inputs;
for (auto& vo : var_out_) {
func_outputs.push_back(var_node_map_->at(vo));
}
for (auto& vi : var_in_) {
std::shared_ptr<ngraph::op::Parameter> prm =
std::dynamic_pointer_cast<ngraph::op::Parameter>(
var_in_node_map_->at(vi));
func_inputs.push_back(prm);
}
ngraph_function_ =
std::make_shared<ngraph::Function>(func_outputs, func_inputs);
}
std::shared_ptr<std::string> NgraphEngine::GetCacheKey() {
auto cache_key = std::make_shared<std::string>("");
*cache_key += std::to_string(fused_ops_.size());
for (auto& op : fused_ops_) {
*cache_key += op->Type();
}
for (auto& var_name : var_in_) {
auto shape = var_node_map_->at(var_name)->get_shape();
*cache_key += var_name;
*cache_key += var_type_map_.at(var_name).c_type_string();
for (size_t i = 0; i < shape.size(); ++i) {
*cache_key += std::to_string(shape.at(i));
}
}
for (auto& var_name : var_out_) {
auto* var = scope_.FindVar(var_name);
if (var && var->IsType<LoDTensor>()) {
auto* tensor_pd = GetLoDTensorOrSelectedRowsValueFromVar(*var);
auto& ddim = tensor_pd->dims();
for (int i = 0; i < ddim.size(); ++i) {
*cache_key += std::to_string(ddim[i]);
}
}
}
return cache_key;
}
void NgraphEngine::GetNgFunction() {
bool cache_on = true;
if (cache_on) {
std::string cache_key_val = *GetCacheKey();
if (func_cache_.find(cache_key_val) != func_cache_.end()) {
ngraph_function_ = func_cache_.at(cache_key_val);
} else {
BuildNgFunction();
func_cache_[cache_key_val] = ngraph_function_;
}
} else {
BuildNgFunction();
}
}
void NgraphEngine::Run(const Scope& scope, const platform::Place& place) const {
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> t_in;
std::vector<std::shared_ptr<ngraph::runtime::Tensor>> t_out;
for (size_t i = 0; i < var_in_.size(); ++i) {
auto vi = var_in_.at(i);
auto sp = var_node_map_->at(vi)->get_shape();
std::shared_ptr<ngraph::runtime::Tensor> ti;
auto* var = scope.FindVar(vi);
if (var && var->IsType<LoDTensor>()) {
auto* tensor_pd = GetLoDTensorOrSelectedRowsValueFromVar(*var);
PADDLE_ENFORCE(sp == Ddim2Shape(tensor_pd->dims()),
"Ensure ngraph tensor layout align with paddle tensor");
if (tensor_pd->type() == proto::VarType::FP32) {
const float* arr = tensor_pd->data<float>();
ti = backend_->create_tensor(ngraph::element::f32, sp,
const_cast<float*>(arr));
} else if (tensor_pd->type() == proto::VarType::INT32) {
const int* arr = tensor_pd->data<int>();
ti = backend_->create_tensor(ngraph::element::i32, sp,
const_cast<int*>(arr));
} else if (tensor_pd->type() == proto::VarType::INT64) {
const int64_t* arr = tensor_pd->data<int64_t>();
ti = backend_->create_tensor(ngraph::element::i64, sp,
const_cast<int64_t*>(arr));
} else if (tensor_pd->type() == proto::VarType::FP64) {
const double* arr = tensor_pd->data<double>();
ti = backend_->create_tensor(ngraph::element::f64, sp,
const_cast<double*>(arr));
} else if (tensor_pd->type() == proto::VarType::BOOL) {
const bool* arr = tensor_pd->data<bool>();
ti = backend_->create_tensor(ngraph::element::boolean, sp,
const_cast<bool*>(arr));
} else {
PADDLE_THROW("Data type not handling for var %s", vi);
}
} else {
PADDLE_THROW("Cannot find var or tensor with var name %s", vi);
}
bool is_test = (ng_op_state_ == PARTIAL_TEST || ng_op_state_ == FULL_TEST)
? true
: false;
bool is_persistable =
(persistables_.find(vi) != persistables_.end()) ? true : false;
if (is_test && is_persistable) {
ti->set_stale(false);
}
t_in.push_back(ti);
}
for (size_t i = 0; i < var_out_.size(); ++i) {
auto var_name = var_out_[i];
auto* var = scope.FindVar(var_name);
std::shared_ptr<ngraph::runtime::Tensor> to;
if (var && var->IsType<LoDTensor>()) {
auto* tensor_pd = GetMutableLoDTensorOrSelectedRowsValueFromVar(var);
auto dd = tensor_pd->dims();
ngraph::Shape sp = Ddim2Shape(dd);
auto ng_type = var_type_map_.at(var_name);
if (ng_type == ngraph::element::f32) {
auto pd_arr = tensor_pd->mutable_data<float>(place);
to = backend_->create_tensor(ngraph::element::f32, sp, pd_arr);
} else if (ng_type == ngraph::element::i64) {
auto pd_arr = tensor_pd->mutable_data<int64_t>(place);
to = backend_->create_tensor(ngraph::element::i64, sp, pd_arr);
} else if (ng_type == ngraph::element::f64) {
auto pd_arr = tensor_pd->mutable_data<double>(place);
to = backend_->create_tensor(ngraph::element::f64, sp, pd_arr);
} else if (ng_type == ngraph::element::boolean) {
auto pd_arr = tensor_pd->mutable_data<bool>(place);
to = backend_->create_tensor(ngraph::element::boolean, sp, pd_arr);
} else {
PADDLE_THROW("Data type not handled in for var %s", var_name);
}
t_out.push_back(to);
} else {
PADDLE_THROW("Cannot find var or tensor with var name %s", var_name);
}
}
backend_->call(backend_->compile(ngraph_function_), t_out, t_in);
} // NgraphEngine::RunImpl
} // namespace framework
} // namespace paddle
<commit_msg>rm ngraph_operator.cc test=develop<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* 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) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "PreviewImageProvider.h"
#include <QDir>
#include <kiconloader.h>
#include <kio/previewjob.h>
#include <QCoreApplication>
#include <QIcon>
#include <QMimeDatabase>
class PreviewImageProvider::Private
{
public:
Private() {};
// Yes, we might use the KFileItem here, but we have a one-to-one equivalence between jobs and previews here anyway, so...
QHash<KIO::PreviewJob*, QPixmap> previews;
QHash<KJob*, bool> jobCompletion;
};
PreviewImageProvider::PreviewImageProvider(QObject* parent)
: QObject(parent)
, QQuickImageProvider(QQuickImageProvider::Image)
, d(new Private)
{
qRegisterMetaType<KFileItem>("KFileItem");
}
PreviewImageProvider::~PreviewImageProvider()
{
delete d;
}
QImage PreviewImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize)
{
QImage image;
QSize ourSize(KIconLoader::SizeEnormous, KIconLoader::SizeEnormous);
if(requestedSize.width() > 0 && requestedSize.height() > 0)
{
ourSize = requestedSize;
}
if(QFile(id).exists())
{
QMimeDatabase db;
QList<QMimeType> mimetypes = db.mimeTypesForFileName(id);
QString mimetype;
if(mimetypes.count() > 0)
{
mimetype = mimetypes.first().name();
}
const QStringList* allPlugins = new QStringList(KIO::PreviewJob::availablePlugins());
KIO::PreviewJob* job = new KIO::PreviewJob(KFileItemList() << KFileItem(QUrl(QString("file://").append(id)), mimetype, 0), ourSize, allPlugins);
job->setIgnoreMaximumSize(true);
job->setScaleType(KIO::PreviewJob::ScaledAndCached);
connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)), SLOT(updatePreview(KFileItem,QPixmap)));
connect(job, SIGNAL(failed(KFileItem)), SLOT(fallbackPreview(KFileItem)));
connect(job, SIGNAL(finished(KJob*)), SLOT(finishedPreview(KJob*)));
d->jobCompletion[job] = false;
if(job->exec())
{
// Do not access the job after this point! As we are requesting that
// it be deleted in finishedPreview(), don't expect it to be around.
while(!d->jobCompletion[job]) {
// Let's let the job do its thing and whatnot...
qApp->processEvents();
}
if(!d->previews[job].isNull())
{
if(requestedSize.width() > 0 && requestedSize.height() > 0)
{
image = d->previews[job].scaled(requestedSize).toImage();
}
else
{
image = d->previews[job].toImage();
}
d->previews.remove(job);
}
d->jobCompletion.remove(job);
}
}
else
{
image = QImage(ourSize, QImage::Format_ARGB32);
}
if(size)
{
*size = ourSize;
}
return image;
}
void PreviewImageProvider::fallbackPreview(const KFileItem& item)
{
KIO::PreviewJob* previewJob = qobject_cast<KIO::PreviewJob*>(sender());
if(previewJob)
{
QMimeDatabase db;
QPixmap preview = QIcon::fromTheme(db.mimeTypeForName(item.mimetype()).iconName()).pixmap(128);
d->previews[previewJob] = preview;
d->jobCompletion[previewJob] = true;
}
}
void PreviewImageProvider::updatePreview(const KFileItem&, const QPixmap& p)
{
KIO::PreviewJob* previewJob = qobject_cast<KIO::PreviewJob*>(sender());
if(previewJob)
{
d->previews[previewJob] = p;
}
}
void PreviewImageProvider::finishedPreview(KJob* job)
{
d->jobCompletion[job] = true;
}
<commit_msg>Remove the jobs in a less "clever" place...<commit_after>/*
* Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* 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) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "PreviewImageProvider.h"
#include <QDir>
#include <kiconloader.h>
#include <kio/previewjob.h>
#include <QCoreApplication>
#include <QIcon>
#include <QMimeDatabase>
class PreviewImageProvider::Private
{
public:
Private() {};
// Yes, we might use the KFileItem here, but we have a one-to-one equivalence between jobs and previews here anyway, so...
QHash<KIO::PreviewJob*, QPixmap> previews;
QHash<KJob*, bool> jobCompletion;
};
PreviewImageProvider::PreviewImageProvider(QObject* parent)
: QObject(parent)
, QQuickImageProvider(QQuickImageProvider::Image)
, d(new Private)
{
qRegisterMetaType<KFileItem>("KFileItem");
}
PreviewImageProvider::~PreviewImageProvider()
{
delete d;
}
QImage PreviewImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize)
{
QImage image;
QSize ourSize(KIconLoader::SizeEnormous, KIconLoader::SizeEnormous);
if(requestedSize.width() > 0 && requestedSize.height() > 0)
{
ourSize = requestedSize;
}
if(QFile(id).exists())
{
QMimeDatabase db;
QList<QMimeType> mimetypes = db.mimeTypesForFileName(id);
QString mimetype;
if(mimetypes.count() > 0)
{
mimetype = mimetypes.first().name();
}
const QStringList* allPlugins = new QStringList(KIO::PreviewJob::availablePlugins());
KIO::PreviewJob* job = new KIO::PreviewJob(KFileItemList() << KFileItem(QUrl(QString("file://").append(id)), mimetype, 0), ourSize, allPlugins);
job->setIgnoreMaximumSize(true);
job->setScaleType(KIO::PreviewJob::ScaledAndCached);
connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)), SLOT(updatePreview(KFileItem,QPixmap)));
connect(job, SIGNAL(failed(KFileItem)), SLOT(fallbackPreview(KFileItem)));
connect(job, SIGNAL(finished(KJob*)), SLOT(finishedPreview(KJob*)));
d->jobCompletion[job] = false;
if(job->exec())
{
// Do not access the job after this point! As we are requesting that
// it be deleted in finishedPreview(), don't expect it to be around.
while(!d->jobCompletion[job]) {
// Let's let the job do its thing and whatnot...
qApp->processEvents();
}
if(!d->previews[job].isNull())
{
if(requestedSize.width() > 0 && requestedSize.height() > 0)
{
image = d->previews[job].scaled(requestedSize).toImage();
}
else
{
image = d->previews[job].toImage();
}
}
}
d->previews.remove(job);
d->jobCompletion.remove(job);
}
else
{
image = QImage(ourSize, QImage::Format_ARGB32);
}
if(size)
{
*size = ourSize;
}
return image;
}
void PreviewImageProvider::fallbackPreview(const KFileItem& item)
{
KIO::PreviewJob* previewJob = qobject_cast<KIO::PreviewJob*>(sender());
if(previewJob)
{
QMimeDatabase db;
QPixmap preview = QIcon::fromTheme(db.mimeTypeForName(item.mimetype()).iconName()).pixmap(128);
d->previews[previewJob] = preview;
d->jobCompletion[previewJob] = true;
}
}
void PreviewImageProvider::updatePreview(const KFileItem&, const QPixmap& p)
{
KIO::PreviewJob* previewJob = qobject_cast<KIO::PreviewJob*>(sender());
if(previewJob)
{
d->previews[previewJob] = p;
}
}
void PreviewImageProvider::finishedPreview(KJob* job)
{
d->jobCompletion[job] = true;
}
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <vespa/vespalib/util/time.h>
#ifdef __linux__
#include <linux/futex.h>
#include <sys/syscall.h>
#endif //linux__
#include <vespa/vespalib/gtest/gtest.h>
using namespace vespalib;
struct State {
std::atomic<uint32_t> value; // 0: ready, 1: wakeup, 2: stop, 3: initial
static_assert(sizeof(value) == sizeof(uint32_t));
State() : value(3) {}
void set_ready() {
value.store(0, std::memory_order_relaxed);
}
void set_wakeup() {
value.store(1, std::memory_order_relaxed);
}
void set_stop() {
value.store(2, std::memory_order_relaxed);
}
bool is_ready() const {
return (value.load(std::memory_order_relaxed) == 0);
}
bool should_stop() const {
return (value.load(std::memory_order_relaxed) == 2);
}
};
struct UseSpin : State {
void wakeup() {
set_wakeup();
}
void stop() {
set_stop();
}
void wait() {
while (is_ready()) {
}
}
};
struct UseSpinYield : State {
void wakeup() {
set_wakeup();
}
void stop() {
set_stop();
}
void wait() {
while (is_ready()) {
std::this_thread::yield();
}
}
};
struct UseCond : State {
std::mutex mutex;
std::condition_variable cond;
void wakeup() {
std::unique_lock<std::mutex> lock(mutex);
set_wakeup();
cond.notify_one();
}
void stop() {
std::unique_lock<std::mutex> lock(mutex);
set_stop();
cond.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lock(mutex);
while (is_ready()) {
cond.wait(lock);
}
}
};
struct UseCondNolock : State {
std::mutex mutex;
std::condition_variable cond;
void wakeup() {
std::unique_lock<std::mutex> lock(mutex);
set_wakeup();
lock.unlock();
cond.notify_one();
}
void stop() {
std::unique_lock<std::mutex> lock(mutex);
set_stop();
lock.unlock();
cond.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lock(mutex);
while (is_ready()) {
cond.wait(lock);
}
}
};
struct UsePipe : State {
int pipefd[2];
UsePipe() {
int res = pipe(pipefd);
assert(res == 0);
}
~UsePipe() {
close(pipefd[0]);
close(pipefd[1]);
}
void wakeup() {
set_wakeup();
char token = 'T';
[[maybe_unused]] ssize_t res = write(pipefd[1], &token, 1);
assert(res == 1);
}
void stop() {
set_stop();
char token = 'T';
[[maybe_unused]] ssize_t res = write(pipefd[1], &token, 1);
assert(res == 1);
}
void wait() {
char token_trash[128];
[[maybe_unused]] ssize_t res = read(pipefd[0], token_trash, sizeof(token_trash));
assert(res == 1);
}
};
#ifdef __linux__
struct UseFutex : State {
void wakeup() {
set_wakeup();
syscall(SYS_futex, reinterpret_cast<uint32_t*>(&value),
FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
}
void stop() {
set_stop();
syscall(SYS_futex, reinterpret_cast<uint32_t*>(&value),
FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
}
void wait() {
while (is_ready()) {
syscall(SYS_futex, reinterpret_cast<uint32_t*>(&value),
FUTEX_WAIT_PRIVATE, 0, nullptr, nullptr, 0);
}
}
};
#endif //linux__
template <typename T>
struct Wakeup : T {
using T::should_stop;
using T::set_ready;
using T::wait;
std::thread thread;
Wakeup() : thread([this]{ run(); }) {}
void run() {
while (!should_stop()) {
set_ready();
wait();
}
}
};
constexpr size_t N = 8;
constexpr size_t WAKE_CNT = 1000000;
template <typename T> auto create_list() __attribute__((noinline));
template <typename T> auto create_list() {
std::vector<T*> list;
for (size_t i = 0; i < N; ++i) {
list.push_back(new T());
}
return list;
}
void destroy_list(auto &list) __attribute__((noinline));
void destroy_list(auto &list) {
for (auto *item: list) {
item->stop();
item->thread.join();
delete item;
}
}
void wait_until_ready(const auto &list) __attribute__((noinline));
void wait_until_ready(const auto &list) {
size_t num_ready = 0;
do {
num_ready = 0;
for (auto *item: list) {
if (item->is_ready()) {
++num_ready;
}
}
} while (num_ready < N);
}
auto perform_wakeups(auto &list, size_t target) __attribute__((noinline));
auto perform_wakeups(auto &list, size_t target) {
size_t wake_cnt = 0;
size_t skip_cnt = 0;
while (wake_cnt < target) {
for (auto *item: list) {
if (item->is_ready()) {
item->wakeup();
++wake_cnt;
} else {
++skip_cnt;
}
}
}
return std::make_pair(wake_cnt, skip_cnt);
}
template <typename T>
void benchmark() {
auto list = create_list<T>();
wait_until_ready(list);
auto t0 = steady_clock::now();
while ((steady_clock::now() - t0) < 1s) {
// warmup
perform_wakeups(list, WAKE_CNT / 64);
}
auto t1 = steady_clock::now();
auto res = perform_wakeups(list, WAKE_CNT);
auto t2 = steady_clock::now();
wait_until_ready(list);
destroy_list(list);
fprintf(stderr, "wakeups per second: %zu (skipped: %zu)\n", size_t(res.first / to_s(t2 - t1)), res.second);
}
TEST(WakeupBench, using_spin) { benchmark<Wakeup<UseSpin>>(); }
TEST(WakeupBench, using_spin_yield) { benchmark<Wakeup<UseSpinYield>>(); }
TEST(WakeupBench, using_cond) { benchmark<Wakeup<UseCond>>(); }
TEST(WakeupBench, using_cond_nolock) { benchmark<Wakeup<UseCondNolock>>(); }
TEST(WakeupBench, using_pipe) { benchmark<Wakeup<UsePipe>>(); }
#ifdef __linux__
TEST(WakeupBench, using_futex) { benchmark<Wakeup<UseFutex>>(); }
#endif //linux__
GTEST_MAIN_RUN_ALL_TESTS()
<commit_msg>Use normal function template instead of abbreviated function template.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <vespa/vespalib/util/time.h>
#ifdef __linux__
#include <linux/futex.h>
#include <sys/syscall.h>
#endif //linux__
#include <vespa/vespalib/gtest/gtest.h>
using namespace vespalib;
struct State {
std::atomic<uint32_t> value; // 0: ready, 1: wakeup, 2: stop, 3: initial
static_assert(sizeof(value) == sizeof(uint32_t));
State() : value(3) {}
void set_ready() {
value.store(0, std::memory_order_relaxed);
}
void set_wakeup() {
value.store(1, std::memory_order_relaxed);
}
void set_stop() {
value.store(2, std::memory_order_relaxed);
}
bool is_ready() const {
return (value.load(std::memory_order_relaxed) == 0);
}
bool should_stop() const {
return (value.load(std::memory_order_relaxed) == 2);
}
};
struct UseSpin : State {
void wakeup() {
set_wakeup();
}
void stop() {
set_stop();
}
void wait() {
while (is_ready()) {
}
}
};
struct UseSpinYield : State {
void wakeup() {
set_wakeup();
}
void stop() {
set_stop();
}
void wait() {
while (is_ready()) {
std::this_thread::yield();
}
}
};
struct UseCond : State {
std::mutex mutex;
std::condition_variable cond;
void wakeup() {
std::unique_lock<std::mutex> lock(mutex);
set_wakeup();
cond.notify_one();
}
void stop() {
std::unique_lock<std::mutex> lock(mutex);
set_stop();
cond.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lock(mutex);
while (is_ready()) {
cond.wait(lock);
}
}
};
struct UseCondNolock : State {
std::mutex mutex;
std::condition_variable cond;
void wakeup() {
std::unique_lock<std::mutex> lock(mutex);
set_wakeup();
lock.unlock();
cond.notify_one();
}
void stop() {
std::unique_lock<std::mutex> lock(mutex);
set_stop();
lock.unlock();
cond.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lock(mutex);
while (is_ready()) {
cond.wait(lock);
}
}
};
struct UsePipe : State {
int pipefd[2];
UsePipe() {
int res = pipe(pipefd);
assert(res == 0);
}
~UsePipe() {
close(pipefd[0]);
close(pipefd[1]);
}
void wakeup() {
set_wakeup();
char token = 'T';
[[maybe_unused]] ssize_t res = write(pipefd[1], &token, 1);
assert(res == 1);
}
void stop() {
set_stop();
char token = 'T';
[[maybe_unused]] ssize_t res = write(pipefd[1], &token, 1);
assert(res == 1);
}
void wait() {
char token_trash[128];
[[maybe_unused]] ssize_t res = read(pipefd[0], token_trash, sizeof(token_trash));
assert(res == 1);
}
};
#ifdef __linux__
struct UseFutex : State {
void wakeup() {
set_wakeup();
syscall(SYS_futex, reinterpret_cast<uint32_t*>(&value),
FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
}
void stop() {
set_stop();
syscall(SYS_futex, reinterpret_cast<uint32_t*>(&value),
FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
}
void wait() {
while (is_ready()) {
syscall(SYS_futex, reinterpret_cast<uint32_t*>(&value),
FUTEX_WAIT_PRIVATE, 0, nullptr, nullptr, 0);
}
}
};
#endif //linux__
template <typename T>
struct Wakeup : T {
using T::should_stop;
using T::set_ready;
using T::wait;
std::thread thread;
Wakeup() : thread([this]{ run(); }) {}
void run() {
while (!should_stop()) {
set_ready();
wait();
}
}
};
constexpr size_t N = 8;
constexpr size_t WAKE_CNT = 1000000;
template <typename T> auto create_list() __attribute__((noinline));
template <typename T> auto create_list() {
std::vector<T*> list;
for (size_t i = 0; i < N; ++i) {
list.push_back(new T());
}
return list;
}
template <typename T>
void destroy_list(T &list) __attribute__((noinline));
template <typename T>
void destroy_list(T &list) {
for (auto *item: list) {
item->stop();
item->thread.join();
delete item;
}
}
template <typename T>
void wait_until_ready(const T &list) __attribute__((noinline));
template <typename T>
void wait_until_ready(const T &list) {
size_t num_ready = 0;
do {
num_ready = 0;
for (auto *item: list) {
if (item->is_ready()) {
++num_ready;
}
}
} while (num_ready < N);
}
template <typename T>
auto perform_wakeups(T &list, size_t target) __attribute__((noinline));
template <typename T>
auto perform_wakeups(T &list, size_t target) {
size_t wake_cnt = 0;
size_t skip_cnt = 0;
while (wake_cnt < target) {
for (auto *item: list) {
if (item->is_ready()) {
item->wakeup();
++wake_cnt;
} else {
++skip_cnt;
}
}
}
return std::make_pair(wake_cnt, skip_cnt);
}
template <typename T>
void benchmark() {
auto list = create_list<T>();
wait_until_ready(list);
auto t0 = steady_clock::now();
while ((steady_clock::now() - t0) < 1s) {
// warmup
perform_wakeups(list, WAKE_CNT / 64);
}
auto t1 = steady_clock::now();
auto res = perform_wakeups(list, WAKE_CNT);
auto t2 = steady_clock::now();
wait_until_ready(list);
destroy_list(list);
fprintf(stderr, "wakeups per second: %zu (skipped: %zu)\n", size_t(res.first / to_s(t2 - t1)), res.second);
}
TEST(WakeupBench, using_spin) { benchmark<Wakeup<UseSpin>>(); }
TEST(WakeupBench, using_spin_yield) { benchmark<Wakeup<UseSpinYield>>(); }
TEST(WakeupBench, using_cond) { benchmark<Wakeup<UseCond>>(); }
TEST(WakeupBench, using_cond_nolock) { benchmark<Wakeup<UseCondNolock>>(); }
TEST(WakeupBench, using_pipe) { benchmark<Wakeup<UsePipe>>(); }
#ifdef __linux__
TEST(WakeupBench, using_futex) { benchmark<Wakeup<UseFutex>>(); }
#endif //linux__
GTEST_MAIN_RUN_ALL_TESTS()
<|endoftext|> |
<commit_before>/*************************************************************************/
/* Copyright (c) 2012 Linas Vepstas <linasvepstas@gmail.com> */
/* All rights reserved */
/* */
/* Use of the Viterbi parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software. */
/* This license allows free redistribution and use in source and binary */
/* forms, with or without modification, subject to certain conditions. */
/* */
/*************************************************************************/
#include <ctype.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <link-grammar/link-includes.h>
#include "api-types.h"
#include "read-dict.h"
#include "structures.h"
#include "atom.h"
#include "compile.h"
#include "connect.h"
#include "connector-utils.h"
#include "parser.h"
#include "state.h"
#include "viterbi.h"
using namespace std;
#define DBG(X) X;
namespace link_grammar {
namespace viterbi {
Parser::Parser(Dictionary dict)
: _dict(dict), _alternatives(NULL)
{
DBG(cout << "=============== Parser ctor ===============" << endl);
initialize_state();
}
// ===================================================================
/**
* Convert LG dictionary expression to atomic formula.
*
* The returned expression is in the form of an opencog-style
* prefix-notation boolean expression. Note that it is not in any
* particular kind of normal form. In particular, some AND nodes
* may have only one child: these can be removed.
*
* Note that the order of the connectors is important: while linking,
* these must be satisfied in left-to-right (nested!?) order.
*
* Optional clauses are indicated by OR-ing with null, where "null"
* is a CONNECTOR Node with string-value "0". Optional clauses are
* not necessarily in any sort of normal form; the null connector can
* appear anywhere.
*/
Atom * Parser::lg_exp_to_atom(Exp* exp)
{
if (CONNECTOR_type == exp->type)
{
stringstream ss;
if (exp->multi) ss << "@";
ss << exp->u.string << exp->dir;
return new Connector(ss.str());
}
// Whenever a null appears in an OR-list, it means the
// entire OR-list is optional. A null can never appear
// in an AND-list.
E_list* el = exp->u.l;
if (NULL == el)
return new Connector(OPTIONAL_CLAUSE);
// The data structure that link-grammar uses for connector
// expressions is totally insane, as witnessed by the loop below.
// Anyway: operators are infixed, i.e. are always binary,
// with exp->u.l->e being the left hand side, and
// exp->u.l->next->e being the right hand side.
// This means that exp->u.l->next->next is always null.
OutList alist;
alist.push_back(lg_exp_to_atom(el->e));
el = el->next;
while (el && exp->type == el->e->type)
{
el = el->e->u.l;
alist.push_back(lg_exp_to_atom(el->e));
el = el->next;
}
if (el)
alist.push_back(lg_exp_to_atom(el->e));
if (AND_type == exp->type)
return new Link(AND, alist);
if (OR_type == exp->type)
return new Link(OR, alist);
assert(0, "Not reached");
}
// ===================================================================
/**
* Return atomic formula connector expression for the given word.
*
* This looks up the word in the link-grammar dictionary, and converts
* the resulting link-grammar connective expression into an atomic
* formula.
*/
Set * Parser::word_consets(const string& word)
{
// See if we know about this word, or not.
Dict_node* dn_head = dictionary_lookup_list(_dict, word.c_str());
if (!dn_head) return NULL;
OutList djset;
for (Dict_node*dn = dn_head; dn; dn= dn->right)
{
Exp* exp = dn->exp;
cout<<"duude the word: " << dn->string << ": ";
print_expression(exp);
Atom *dj = lg_exp_to_atom(exp);
// First atom at the from of the outgoing set is the word itself.
// Second atom is the first disjuct that must be fulfilled.
Word* nword = new Word(dn->string);
djset.push_back(new WordCset(nword, dj));
}
return new Set(djset);
}
// ===================================================================
/**
* Set up initial viterbi state for the parser
*/
void Parser::initialize_state()
{
const char * wall_word = "LEFT-WALL";
Set *wall_disj = word_consets(wall_word);
// We are expecting the initiall wall to be unique.
assert(wall_disj->get_arity() == 1, "Unexpected wall structure");
OutList state_vec;
Atom* word_cset = wall_disj->get_outgoing_atom(0);
// Initial state: no output, and the wall cset.
_alternatives = new Set(
new StatePair(
new Seq(word_cset),
new Seq()
)
);
}
// ===================================================================
/**
* Add a single word to the parse.
*/
void Parser::stream_word(const string& word)
{
Set *djset = word_consets(word);
if (!djset)
{
cout << "Unhandled error; word not in dict: " << word << endl;
return;
}
assert(1 == djset->get_arity(), "Multiple dict entries not handled");
// Try to add each dictionary entry to the parse state.
for (int i = 0; i < djset->get_arity(); i++)
{
State stset(_alternatives);
stset.stream_word_conset(dynamic_cast<WordCset*>(djset->get_outgoing_atom(i)));
// XXX this can't possibly be right ...
_alternatives = stset.get_alternatives();
}
}
// ===================================================================
/** convenience wrapper */
Set* Parser::get_alternatives()
{
return _alternatives;
}
// ===================================================================
/**
* Add a stream of text to the input.
*
* No particular assumptiions are made about the input, other than
* that its space-separated words (i.e. no HTML markup or other junk)
*/
void Parser::streamin(const string& text)
{
// A trivial tokenizer
size_t pos = 0;
while(true)
{
size_t wend = text.find(' ', pos);
if (wend != string::npos)
{
string word = text.substr(pos, wend-pos);
stream_word(word);
pos = wend+1; // skip over space
}
else
{
string word = text.substr(pos);
stream_word(word);
break;
}
}
}
void viterbi_parse(Dictionary dict, const char * sentence)
{
Parser pars(dict);
pars.streamin(sentence);
}
} // namespace viterbi
} // namespace link-grammar
// ===================================================================
// Wrapper to escape out from C++
void viterbi_parse(const char * sentence, Dictionary dict)
{
link_grammar::viterbi::viterbi_parse(dict, sentence);
}
<commit_msg>another bugfix to get recently added code kind-of working<commit_after>/*************************************************************************/
/* Copyright (c) 2012 Linas Vepstas <linasvepstas@gmail.com> */
/* All rights reserved */
/* */
/* Use of the Viterbi parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software. */
/* This license allows free redistribution and use in source and binary */
/* forms, with or without modification, subject to certain conditions. */
/* */
/*************************************************************************/
#include <ctype.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <link-grammar/link-includes.h>
#include "api-types.h"
#include "read-dict.h"
#include "structures.h"
#include "atom.h"
#include "compile.h"
#include "connect.h"
#include "connector-utils.h"
#include "disjoin.h"
#include "parser.h"
#include "state.h"
#include "viterbi.h"
using namespace std;
#define DBG(X) X;
namespace link_grammar {
namespace viterbi {
Parser::Parser(Dictionary dict)
: _dict(dict), _alternatives(NULL)
{
DBG(cout << "=============== Parser ctor ===============" << endl);
initialize_state();
}
// ===================================================================
/**
* Convert LG dictionary expression to atomic formula.
*
* The returned expression is in the form of an opencog-style
* prefix-notation boolean expression. Note that it is not in any
* particular kind of normal form. In particular, some AND nodes
* may have only one child: these can be removed.
*
* Note that the order of the connectors is important: while linking,
* these must be satisfied in left-to-right (nested!?) order.
*
* Optional clauses are indicated by OR-ing with null, where "null"
* is a CONNECTOR Node with string-value "0". Optional clauses are
* not necessarily in any sort of normal form; the null connector can
* appear anywhere.
*/
Atom * Parser::lg_exp_to_atom(Exp* exp)
{
if (CONNECTOR_type == exp->type)
{
stringstream ss;
if (exp->multi) ss << "@";
ss << exp->u.string << exp->dir;
return new Connector(ss.str());
}
// Whenever a null appears in an OR-list, it means the
// entire OR-list is optional. A null can never appear
// in an AND-list.
E_list* el = exp->u.l;
if (NULL == el)
return new Connector(OPTIONAL_CLAUSE);
// The data structure that link-grammar uses for connector
// expressions is totally insane, as witnessed by the loop below.
// Anyway: operators are infixed, i.e. are always binary,
// with exp->u.l->e being the left hand side, and
// exp->u.l->next->e being the right hand side.
// This means that exp->u.l->next->next is always null.
OutList alist;
alist.push_back(lg_exp_to_atom(el->e));
el = el->next;
while (el && exp->type == el->e->type)
{
el = el->e->u.l;
alist.push_back(lg_exp_to_atom(el->e));
el = el->next;
}
if (el)
alist.push_back(lg_exp_to_atom(el->e));
if (AND_type == exp->type)
return new And(alist);
if (OR_type == exp->type)
return new Or(alist);
assert(0, "Not reached");
}
// ===================================================================
/**
* Return atomic formula connector expression for the given word.
*
* This looks up the word in the link-grammar dictionary, and converts
* the resulting link-grammar connective expression into an atomic
* formula.
*/
Set * Parser::word_consets(const string& word)
{
// See if we know about this word, or not.
Dict_node* dn_head = dictionary_lookup_list(_dict, word.c_str());
if (!dn_head) return NULL;
OutList djset;
for (Dict_node*dn = dn_head; dn; dn= dn->right)
{
Exp* exp = dn->exp;
cout<<"duude the word: " << dn->string << ": ";
print_expression(exp);
Atom *dj = lg_exp_to_atom(exp);
// xxxx not yet, the code is buggy
// dj = disjoin(dj);
// First atom at the from of the outgoing set is the word itself.
// Second atom is the first disjuct that must be fulfilled.
Word* nword = new Word(dn->string);
djset.push_back(new WordCset(nword, dj));
}
return new Set(djset);
}
// ===================================================================
/**
* Set up initial viterbi state for the parser
*/
void Parser::initialize_state()
{
const char * wall_word = "LEFT-WALL";
Set *wall_disj = word_consets(wall_word);
// We are expecting the initiall wall to be unique.
assert(wall_disj->get_arity() == 1, "Unexpected wall structure");
OutList state_vec;
Atom* word_cset = wall_disj->get_outgoing_atom(0);
// Initial state: no output, and the wall cset.
_alternatives = new Set(
new StatePair(
new Seq(word_cset),
new Seq()
)
);
}
// ===================================================================
/**
* Add a single word to the parse.
*/
void Parser::stream_word(const string& word)
{
Set *djset = word_consets(word);
if (!djset)
{
cout << "Unhandled error; word not in dict: " << word << endl;
return;
}
assert(1 == djset->get_arity(), "Multiple dict entries not handled");
// Try to add each dictionary entry to the parse state.
for (int i = 0; i < djset->get_arity(); i++)
{
State stset(_alternatives);
stset.stream_word_conset(dynamic_cast<WordCset*>(djset->get_outgoing_atom(i)));
// XXX this can't possibly be right ...
_alternatives = stset.get_alternatives();
}
}
// ===================================================================
/** convenience wrapper */
Set* Parser::get_alternatives()
{
return _alternatives;
}
// ===================================================================
/**
* Add a stream of text to the input.
*
* No particular assumptiions are made about the input, other than
* that its space-separated words (i.e. no HTML markup or other junk)
*/
void Parser::streamin(const string& text)
{
// A trivial tokenizer
size_t pos = 0;
while(true)
{
size_t wend = text.find(' ', pos);
if (wend != string::npos)
{
string word = text.substr(pos, wend-pos);
stream_word(word);
pos = wend+1; // skip over space
}
else
{
string word = text.substr(pos);
stream_word(word);
break;
}
}
}
void viterbi_parse(Dictionary dict, const char * sentence)
{
Parser pars(dict);
pars.streamin(sentence);
}
} // namespace viterbi
} // namespace link-grammar
// ===================================================================
// Wrapper to escape out from C++
void viterbi_parse(const char * sentence, Dictionary dict)
{
link_grammar::viterbi::viterbi_parse(dict, sentence);
}
<|endoftext|> |
<commit_before>#include <memory>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <random>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/basic_system_errors.hpp>
#include <realm/impl/simulated_failure.hpp>
#if REALM_PLATFORM_APPLE
# define USE_PTHREADS_IMPL 1
#else
# define USE_PTHREADS_IMPL 0
#endif
#if USE_PTHREADS_IMPL
# include <pthread.h>
#endif
using namespace realm;
using namespace realm::_impl;
#ifdef REALM_DEBUG
namespace {
const int num_failure_types = SimulatedFailure::_num_failure_types;
struct PrimeMode {
virtual bool check_trigger() noexcept = 0;
};
struct PrimeState {
std::unique_ptr<PrimeMode> slots[num_failure_types];
};
struct OneShotPrimeMode: PrimeMode {
bool triggered = false;
bool check_trigger() noexcept override
{
if (triggered)
return false;
triggered = true;
return true;
}
};
struct RandomPrimeMode: PrimeMode {
std::mt19937_64 random;
std::uniform_int_distribution<int> dist;
int n;
RandomPrimeMode(int n, int m, uint_fast64_t seed):
random(seed),
dist(0, m-1),
n(n)
{
REALM_ASSERT(n >= 0 && m > 0);
}
bool check_trigger() noexcept override
{
int i = dist(random);
return i < n;
}
};
# if !USE_PTHREADS_IMPL
REALM_THREAD_LOCAL PrimeState t_prime_state;
PrimeState& get() noexcept
{
return t_prime_state;
}
# else // USE_PTHREADS_IMPL
pthread_key_t key;
pthread_once_t key_once = PTHREAD_ONCE_INIT;
void destroy(void* ptr) noexcept
{
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
delete prime_state;
}
void create() noexcept
{
int ret = pthread_key_create(&key, &destroy);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
PrimeState& get() noexcept
{
pthread_once(&key_once, &create);
void* ptr = pthread_getspecific(key);
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
if (!prime_state) {
prime_state = new PrimeState; // Throws with intended termination
int ret = pthread_setspecific(key, prime_state);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
return *prime_state;
}
# endif // USE_PTHREADS_IMPL
} // unnamed namespace
void SimulatedFailure::do_prime_one_shot(FailureType failure_type)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new OneShotPrimeMode); // Throws
}
void SimulatedFailure::do_prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new RandomPrimeMode(n, m, seed)); // Throws
}
void SimulatedFailure::do_unprime(FailureType failure_type) noexcept
{
PrimeState& state = get();
state.slots[failure_type].reset();
}
bool SimulatedFailure::do_check_trigger(FailureType failure_type) noexcept
{
PrimeState& state = get();
if (PrimeMode* p = state.slots[failure_type].get())
return p->check_trigger();
return false;
}
#endif // REALM_DEBUG
<commit_msg>Fix for: Various improvements to failure simulation (_impl::SimulatedFailure)<commit_after>#include <memory>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <random>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/basic_system_errors.hpp>
#include <realm/impl/simulated_failure.hpp>
#if REALM_PLATFORM_APPLE
# define USE_PTHREADS_IMPL 1
#else
# define USE_PTHREADS_IMPL 0
#endif
#if USE_PTHREADS_IMPL
# include <pthread.h>
#endif
using namespace realm;
using namespace realm::_impl;
#ifdef REALM_DEBUG
namespace {
const int num_failure_types = SimulatedFailure::_num_failure_types;
struct PrimeMode {
virtual bool check_trigger() noexcept = 0;
};
struct PrimeState {
std::unique_ptr<PrimeMode> slots[num_failure_types];
};
struct OneShotPrimeMode: PrimeMode {
bool triggered = false;
bool check_trigger() noexcept override
{
if (triggered)
return false;
triggered = true;
return true;
}
};
struct RandomPrimeMode: PrimeMode {
std::mt19937_64 random;
std::uniform_int_distribution<int> dist;
int n;
RandomPrimeMode(int n, int m, uint_fast64_t seed):
random(seed),
dist(0, m-1),
n(n)
{
REALM_ASSERT(n >= 0 && m > 0);
}
bool check_trigger() noexcept override
{
int i = dist(random);
return i < n;
}
};
# if !USE_PTHREADS_IMPL
thread_local PrimeState t_prime_state;
PrimeState& get() noexcept
{
return t_prime_state;
}
# else // USE_PTHREADS_IMPL
pthread_key_t key;
pthread_once_t key_once = PTHREAD_ONCE_INIT;
void destroy(void* ptr) noexcept
{
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
delete prime_state;
}
void create() noexcept
{
int ret = pthread_key_create(&key, &destroy);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
PrimeState& get() noexcept
{
pthread_once(&key_once, &create);
void* ptr = pthread_getspecific(key);
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
if (!prime_state) {
prime_state = new PrimeState; // Throws with intended termination
int ret = pthread_setspecific(key, prime_state);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
return *prime_state;
}
# endif // USE_PTHREADS_IMPL
} // unnamed namespace
void SimulatedFailure::do_prime_one_shot(FailureType failure_type)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new OneShotPrimeMode); // Throws
}
void SimulatedFailure::do_prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new RandomPrimeMode(n, m, seed)); // Throws
}
void SimulatedFailure::do_unprime(FailureType failure_type) noexcept
{
PrimeState& state = get();
state.slots[failure_type].reset();
}
bool SimulatedFailure::do_check_trigger(FailureType failure_type) noexcept
{
PrimeState& state = get();
if (PrimeMode* p = state.slots[failure_type].get())
return p->check_trigger();
return false;
}
#endif // REALM_DEBUG
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <vector>
#include <boost/thread/tss.hpp>
#include "blackhole/attribute.hpp"
#include "blackhole/detail/config/atomic.hpp"
#include "blackhole/detail/config/noncopyable.hpp"
#include "blackhole/detail/config/nullptr.hpp"
#include "blackhole/detail/util/unique.hpp"
#include "error/handler.hpp"
#include "filter.hpp"
#include "frontend.hpp"
#include "keyword.hpp"
#include "keyword/message.hpp"
#include "keyword/severity.hpp"
#include "keyword/thread.hpp"
#include "keyword/timestamp.hpp"
#include "keyword/tracebit.hpp"
#include "blackhole/config.hpp"
namespace blackhole {
class scoped_attributes_concept_t;
template<typename Level>
struct logger_verbosity_traits {
typedef Level level_type;
static
inline
bool
passed(level_type logger_verbosity, level_type record_verbosity) {
typedef typename aux::underlying_type<Level>::type underlying_type;
return static_cast<underlying_type>(record_verbosity) >=
static_cast<underlying_type>(logger_verbosity);
}
};
class logger_base_t {
friend class scoped_attributes_concept_t;
friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT;
protected:
typedef boost::shared_mutex rw_mutex_type;
typedef boost::shared_lock<rw_mutex_type> reader_lock_type;
typedef boost::unique_lock<rw_mutex_type> writer_lock_type;
struct state_t {
std::atomic<bool> enabled;
std::atomic<bool> tracked;
filter_t filter;
struct attrbutes_t {
boost::thread_specific_ptr<scoped_attributes_concept_t> scoped;
attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) :
scoped(deleter)
{}
} attributes;
std::vector<std::unique_ptr<base_frontend_t>> frontends;
log::exception_handler_t exception;
struct {
mutable rw_mutex_type open;
mutable rw_mutex_type push;
} lock;
state_t();
};
state_t state;
public:
logger_base_t();
//! @compat GCC4.4
//! Blaming GCC4.4 - it needs explicit move constructor definition,
//! because it cannot define default move constructor for derived class.
logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT;
logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT;
bool enabled() const;
void enabled(bool enable);
bool tracked() const;
void tracked(bool enable);
void set_filter(filter_t&& filter);
void add_frontend(std::unique_ptr<base_frontend_t> frontend);
void set_exception_handler(log::exception_handler_t&& handler);
record_t open_record() const;
record_t open_record(attribute::pair_t attribute) const;
record_t open_record(attribute::set_t attributes) const;
void push(record_t&& record) const;
protected:
record_t open_record(attribute::set_t internal, attribute::set_t external) const;
};
/// Concept form scoped attributes holder.
/*!
* @note: It's not movable to avoid moving to another thread.
*/
class scoped_attributes_concept_t {
BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t);
logger_base_t *m_logger;
scoped_attributes_concept_t *m_previous;
friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;
public:
scoped_attributes_concept_t(logger_base_t& log);
virtual ~scoped_attributes_concept_t();
virtual const attribute::set_t& attributes() const = 0;
protected:
bool has_parent() const;
const scoped_attributes_concept_t& parent() const;
};
template<typename Level>
class verbose_logger_t : public logger_base_t {
public:
typedef Level level_type;
typedef std::function<
bool(level_type, const attribute::combined_view_t&)
> filter_type;
private:
level_type level;
filter_type filter;
// TODO: Thread-safety.
public:
explicit verbose_logger_t(level_type level) :
logger_base_t(),
level(level),
filter(default_filter { level })
{}
//! @compat: GCC4.4
//! GCC 4.4 doesn't create default copy/move constructor for derived
//! classes. It's a bug.
verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT :
logger_base_t(std::move(other))
{
level = other.level;
filter = other.filter;
}
verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT {
logger_base_t::operator=(std::move(other));
level = other.level;
filter = other.filter;
return *this;
}
/*!
* Gets the current upper verbosity bound.
*/
level_type verbosity() const {
return level;
}
/*!
* Sets the upper verbosity bound.
* Every log event with a verbosity less than `level` will be dropped.
* @param[in] level - Upper verbosity value.
*/
void verbosity(level_type level) {
this->level = level;
this->filter = default_filter { level };
}
// TODO: Level is necessary!
void verbosity(filter_type filter) {
this->filter = filter;
}
/*!
* Tries to open log record with specific verbosity level.
*
* Internally this method compares desired verbosity level with the upper
* one and checks for tracebit attribute (temporary until filter redesign).
* Can return invalid log record if some conditions are not met.
* @param[in] level - Desired verbosity level.
* @return valid or invalid `record_t` object.
* @todo: Decompose.
*/
record_t
open_record(level_type level, attribute::set_t local = attribute::set_t()) const {
bool passed = false;
reader_lock_type lock(state.lock.open);
if (auto scoped = state.attributes.scoped.get()) {
const attribute::combined_view_t view(local, scoped->attributes());
passed = filter(level, view);
} else {
const attribute::combined_view_t view(local);
passed = filter(level, view);
}
if (passed) {
attribute::set_t internal;
internal.emplace_back(keyword::severity<Level>() = level);
return logger_base_t::open_record(std::move(internal), std::move(local));
}
return record_t();
}
private:
struct default_filter {
level_type threshold;
inline
bool
operator()(level_type level, const attribute::combined_view_t&) const {
return level >= threshold;
}
};
};
} // namespace blackhole
#if defined(BLACKHOLE_HEADER_ONLY)
#include "blackhole/logger.ipp"
#endif
<commit_msg>[Code Clean] Dead code elimination.<commit_after>#pragma once
#include <memory>
#include <vector>
#include <boost/thread/tss.hpp>
#include "blackhole/attribute.hpp"
#include "blackhole/detail/config/atomic.hpp"
#include "blackhole/detail/config/noncopyable.hpp"
#include "blackhole/detail/config/nullptr.hpp"
#include "blackhole/detail/util/unique.hpp"
#include "error/handler.hpp"
#include "filter.hpp"
#include "frontend.hpp"
#include "keyword.hpp"
#include "keyword/message.hpp"
#include "keyword/severity.hpp"
#include "keyword/thread.hpp"
#include "keyword/timestamp.hpp"
#include "keyword/tracebit.hpp"
#include "blackhole/config.hpp"
namespace blackhole {
class scoped_attributes_concept_t;
class logger_base_t {
friend class scoped_attributes_concept_t;
friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT;
protected:
typedef boost::shared_mutex rw_mutex_type;
typedef boost::shared_lock<rw_mutex_type> reader_lock_type;
typedef boost::unique_lock<rw_mutex_type> writer_lock_type;
struct state_t {
std::atomic<bool> enabled;
std::atomic<bool> tracked;
filter_t filter;
struct attrbutes_t {
boost::thread_specific_ptr<scoped_attributes_concept_t> scoped;
attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) :
scoped(deleter)
{}
} attributes;
std::vector<std::unique_ptr<base_frontend_t>> frontends;
log::exception_handler_t exception;
struct {
mutable rw_mutex_type open;
mutable rw_mutex_type push;
} lock;
state_t();
};
state_t state;
public:
logger_base_t();
//! @compat GCC4.4
//! Blaming GCC4.4 - it needs explicit move constructor definition,
//! because it cannot define default move constructor for derived class.
logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT;
logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT;
bool enabled() const;
void enabled(bool enable);
bool tracked() const;
void tracked(bool enable);
void set_filter(filter_t&& filter);
void add_frontend(std::unique_ptr<base_frontend_t> frontend);
void set_exception_handler(log::exception_handler_t&& handler);
record_t open_record() const;
record_t open_record(attribute::pair_t attribute) const;
record_t open_record(attribute::set_t attributes) const;
void push(record_t&& record) const;
protected:
record_t open_record(attribute::set_t internal, attribute::set_t external) const;
};
/// Concept form scoped attributes holder.
/*!
* @note: It's not movable to avoid moving to another thread.
*/
class scoped_attributes_concept_t {
BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t);
logger_base_t *m_logger;
scoped_attributes_concept_t *m_previous;
friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;
public:
scoped_attributes_concept_t(logger_base_t& log);
virtual ~scoped_attributes_concept_t();
virtual const attribute::set_t& attributes() const = 0;
protected:
bool has_parent() const;
const scoped_attributes_concept_t& parent() const;
};
template<typename Level>
class verbose_logger_t : public logger_base_t {
public:
typedef Level level_type;
typedef std::function<
bool(level_type, const attribute::combined_view_t&)
> filter_type;
private:
level_type level;
filter_type filter;
// TODO: Thread-safety.
public:
explicit verbose_logger_t(level_type level) :
logger_base_t(),
level(level),
filter(default_filter { level })
{}
//! @compat: GCC4.4
//! GCC 4.4 doesn't create default copy/move constructor for derived
//! classes. It's a bug.
verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT :
logger_base_t(std::move(other))
{
level = other.level;
filter = other.filter;
}
verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT {
logger_base_t::operator=(std::move(other));
level = other.level;
filter = other.filter;
return *this;
}
/*!
* Gets the current upper verbosity bound.
*/
level_type verbosity() const {
return level;
}
/*!
* Sets the upper verbosity bound.
* Every log event with a verbosity less than `level` will be dropped.
* @param[in] level - Upper verbosity value.
*/
void verbosity(level_type level) {
this->level = level;
this->filter = default_filter { level };
}
// TODO: Level is necessary!
void verbosity(filter_type filter) {
this->filter = filter;
}
/*!
* Tries to open log record with specific verbosity level.
*
* Internally this method compares desired verbosity level with the upper
* one and checks for tracebit attribute (temporary until filter redesign).
* Can return invalid log record if some conditions are not met.
* @param[in] level - Desired verbosity level.
* @return valid or invalid `record_t` object.
* @todo: Decompose.
*/
record_t
open_record(level_type level, attribute::set_t local = attribute::set_t()) const {
bool passed = false;
reader_lock_type lock(state.lock.open);
if (auto scoped = state.attributes.scoped.get()) {
const attribute::combined_view_t view(local, scoped->attributes());
passed = filter(level, view);
} else {
const attribute::combined_view_t view(local);
passed = filter(level, view);
}
if (passed) {
attribute::set_t internal;
internal.emplace_back(keyword::severity<Level>() = level);
return logger_base_t::open_record(std::move(internal), std::move(local));
}
return record_t();
}
private:
struct default_filter {
level_type threshold;
inline
bool
operator()(level_type level, const attribute::combined_view_t&) const {
return level >= threshold;
}
};
};
} // namespace blackhole
#if defined(BLACKHOLE_HEADER_ONLY)
#include "blackhole/logger.ipp"
#endif
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2020 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "RenderDoc.h"
#if defined(REAPER_USE_RENDERDOC)
# include "common/DebugLog.h"
# include "common/ReaperRoot.h"
# include "core/DynamicLibrary.h"
# include "core/Profile.h"
# if defined(REAPER_PLATFORM_LINUX) || defined(REAPER_PLATFORM_MACOSX)
# include <renderdoc.h>
# elif defined(REAPER_PLATFORM_WINDOWS)
# include <renderdoc_app.h>
# endif
namespace Reaper::RenderDoc
{
namespace
{
constexpr RENDERDOC_Version RenderDocVersion = eRENDERDOC_API_Version_1_4_0;
using RenderDocAPI = RENDERDOC_API_1_4_0;
LibHandle g_renderDocLib = nullptr;
RenderDocAPI* g_renderDocAPI = nullptr;
} // namespace
void start_integration(ReaperRoot& root)
{
REAPER_PROFILE_SCOPE("RenderDoc", MP_GREEN1);
log_info(root, "renderdoc: starting integration");
Assert(g_renderDocLib == nullptr);
log_info(root, "renderdoc: loading {}", REAPER_RENDERDOC_LIB_NAME);
// FIXME Documentation recommends RTLD_NOW | RTLD_NOLOAD on linux
g_renderDocLib = dynlib::load(REAPER_RENDERDOC_LIB_NAME);
pRENDERDOC_GetAPI pfn_RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dynlib::getSymbol(g_renderDocLib, "RENDERDOC_GetAPI");
Assert(pfn_RENDERDOC_GetAPI(RenderDocVersion, (void**)&g_renderDocAPI) == 1);
int major, minor, patch;
g_renderDocAPI->GetAPIVersion(&major, &minor, &patch);
log_info(root, "renderdoc: API version {}.{}.{}", major, minor, patch);
}
void stop_integration(ReaperRoot& root)
{
REAPER_PROFILE_SCOPE("RenderDoc", MP_GREEN1);
log_info(root, "renderdoc: stopping integration");
Assert(g_renderDocLib != nullptr);
// We are not supposed to unload RenderDoc lib manually ever.
// See also: https://github.com/bkaradzic/bgfx/issues/1192
// log_info(root, "renderdoc: unloading {}", REAPER_RENDERDOC_LIB_NAME);
// dynlib::close(g_renderDocLib);
// g_renderDocLib = nullptr;
}
} // namespace Reaper::RenderDoc
#else
namespace Reaper::RenderDoc
{
void start_integration(ReaperRoot& /*root*/)
{
AssertUnreachable();
}
void stop_integration(ReaperRoot& /*root*/)
{
AssertUnreachable();
}
} // namespace Reaper::RenderDoc
#endif
<commit_msg>renderdoc: fix include path on linux<commit_after>////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2020 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "RenderDoc.h"
#if defined(REAPER_USE_RENDERDOC)
# include "common/DebugLog.h"
# include "common/ReaperRoot.h"
# include "core/DynamicLibrary.h"
# include "core/Profile.h"
# include <renderdoc_app.h>
namespace Reaper::RenderDoc
{
namespace
{
constexpr RENDERDOC_Version RenderDocVersion = eRENDERDOC_API_Version_1_4_0;
using RenderDocAPI = RENDERDOC_API_1_4_0;
LibHandle g_renderDocLib = nullptr;
RenderDocAPI* g_renderDocAPI = nullptr;
} // namespace
void start_integration(ReaperRoot& root)
{
REAPER_PROFILE_SCOPE("RenderDoc", MP_GREEN1);
log_info(root, "renderdoc: starting integration");
Assert(g_renderDocLib == nullptr);
log_info(root, "renderdoc: loading {}", REAPER_RENDERDOC_LIB_NAME);
// FIXME Documentation recommends RTLD_NOW | RTLD_NOLOAD on linux
g_renderDocLib = dynlib::load(REAPER_RENDERDOC_LIB_NAME);
pRENDERDOC_GetAPI pfn_RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dynlib::getSymbol(g_renderDocLib, "RENDERDOC_GetAPI");
Assert(pfn_RENDERDOC_GetAPI(RenderDocVersion, (void**)&g_renderDocAPI) == 1);
int major, minor, patch;
g_renderDocAPI->GetAPIVersion(&major, &minor, &patch);
log_info(root, "renderdoc: API version {}.{}.{}", major, minor, patch);
}
void stop_integration(ReaperRoot& root)
{
REAPER_PROFILE_SCOPE("RenderDoc", MP_GREEN1);
log_info(root, "renderdoc: stopping integration");
Assert(g_renderDocLib != nullptr);
// We are not supposed to unload RenderDoc lib manually ever.
// See also: https://github.com/bkaradzic/bgfx/issues/1192
// log_info(root, "renderdoc: unloading {}", REAPER_RENDERDOC_LIB_NAME);
// dynlib::close(g_renderDocLib);
// g_renderDocLib = nullptr;
}
} // namespace Reaper::RenderDoc
#else
namespace Reaper::RenderDoc
{
void start_integration(ReaperRoot& /*root*/)
{
AssertUnreachable();
}
void stop_integration(ReaperRoot& /*root*/)
{
AssertUnreachable();
}
} // namespace Reaper::RenderDoc
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Project OSRM contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
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.
*/
#ifndef SCRIPTING_ENVIRONMENT_HPP
#define SCRIPTING_ENVIRONMENT_HPP
#include <string>
#include <memory>
#include <mutex>
#include <tbb/enumerable_thread_specific.h>
struct lua_State;
class ScriptingEnvironment
{
public:
ScriptingEnvironment() = delete;
explicit ScriptingEnvironment(const std::string &file_name);
lua_State *get_lua_state();
private:
void init_lua_state(lua_State *lua_state);
std::mutex init_mutex;
std::string file_name;
tbb::enumerable_thread_specific<std::shared_ptr<lua_State>> script_contexts;
};
#endif /* SCRIPTING_ENVIRONMENT_HPP */
<commit_msg>Add documentation to ScriptingEnvironment<commit_after>/*
Copyright (c) 2014, Project OSRM contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
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.
*/
#ifndef SCRIPTING_ENVIRONMENT_HPP
#define SCRIPTING_ENVIRONMENT_HPP
#include <string>
#include <memory>
#include <mutex>
#include <tbb/enumerable_thread_specific.h>
struct lua_State;
/**
* Creates a lua context and binds osmium way, node and relation objects and
* ExtractionWay and ExtractionNode to lua objects.
*
* Each thread has its own lua state which is implemented with thread specific
* storage from TBB.
*/
class ScriptingEnvironment
{
public:
ScriptingEnvironment() = delete;
explicit ScriptingEnvironment(const std::string &file_name);
lua_State *get_lua_state();
private:
void init_lua_state(lua_State *lua_state);
std::mutex init_mutex;
std::string file_name;
tbb::enumerable_thread_specific<std::shared_ptr<lua_State>> script_contexts;
};
#endif /* SCRIPTING_ENVIRONMENT_HPP */
<|endoftext|> |
<commit_before>/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
sat_clause.cpp
Abstract:
Clauses
Author:
Leonardo de Moura (leonardo) 2011-05-21.
Revision History:
--*/
#include<memory.h>
#include"sat_clause.h"
#include"z3_exception.h"
#include"trace.h"
namespace sat {
clause::clause(unsigned id, unsigned sz, literal const * lits, bool learned):
m_id(id),
m_size(sz),
m_capacity(sz),
m_removed(false),
m_learned(learned),
m_used(false),
m_frozen(false),
m_reinit_stack(false),
m_inact_rounds(0) {
memcpy(m_lits, lits, sizeof(literal) * sz);
mark_strengthened();
SASSERT(check_approx());
SASSERT(sz > 1);
}
var_approx_set clause::approx(unsigned num, literal const * lits) {
var_approx_set r;
for (unsigned i = 0; i < num; i++)
r.insert(lits[i].var());
return r;
}
void clause::update_approx() {
m_approx = approx(m_size, m_lits);
}
bool clause::check_approx() const {
var_approx_set curr = m_approx;
const_cast<clause*>(this)->update_approx();
SASSERT(may_eq(curr, m_approx));
return true;
}
bool clause::contains(literal l) const {
for (unsigned i = 0; i < m_size; i++)
if (m_lits[i] == l)
return true;
return false;
}
bool clause::contains(bool_var v) const {
for (unsigned i = 0; i < m_size; i++)
if (m_lits[i].var() == v)
return true;
return false;
}
void clause::elim(literal l) {
unsigned i;
for (i = 0; i < m_size; i++)
if (m_lits[i] == l)
break;
SASSERT(i < m_size);
i++;
for (; i < m_size; i++)
m_lits[i-1] = m_lits[i];
m_size--;
mark_strengthened();
}
bool clause::satisfied_by(model const & m) const {
for (unsigned i = 0; i < m_size; i++) {
literal l = m_lits[i];
if (l.sign()) {
if (m[l.var()] == l_false)
return true;
}
else {
if (m[l.var()] == l_true)
return true;
}
}
return false;
}
void tmp_clause::set(unsigned num_lits, literal const * lits, bool learned) {
if (m_clause && m_clause->m_capacity < num_lits) {
dealloc_svect(m_clause);
m_clause = 0;
}
if (!m_clause) {
void * mem = alloc_svect(char, clause::get_obj_size(num_lits));
m_clause = new (mem) clause(UINT_MAX, num_lits, lits, learned);
}
else {
SASSERT(m_clause->m_id == UINT_MAX);
m_clause->m_size = num_lits;
m_clause->m_learned = learned;
memcpy(m_clause->m_lits, lits, sizeof(literal) * num_lits);
}
SASSERT(m_clause->m_size <= m_clause->m_capacity);
for (unsigned i = 0; i < num_lits; i++) {
SASSERT((*m_clause)[i] == lits[i]);
}
}
clause_allocator::clause_allocator():
m_allocator("clause-allocator") {
#ifdef _AMD64_
m_num_segments = 0;
#endif
}
clause * clause_allocator::get_clause(clause_offset cls_off) const {
#ifdef _AMD64_
return reinterpret_cast<clause *>(m_segments[cls_off & c_aligment_mask] + (static_cast<size_t>(cls_off) & ~c_aligment_mask));
#else
return reinterpret_cast<clause *>(cls_off);
#endif
}
#ifdef _AMD64_
unsigned clause_allocator::get_segment(size_t ptr) {
SASSERT((ptr & c_aligment_mask) == 0);
ptr &= ~0xFFFFFFFFull; // Keep only high part
unsigned i = 0;
for (i = 0; i < m_num_segments; ++i)
if (m_segments[i] == ptr)
return i;
i = m_num_segments;
m_num_segments++;
if (i > c_max_segments)
throw default_exception("segment out of range");
m_segments[i] = ptr;
return i;
}
#endif
clause_offset clause_allocator::get_offset(clause const * ptr) const {
#ifdef _AMD64_
return static_cast<unsigned>(reinterpret_cast<size_t>(ptr)) + const_cast<clause_allocator*>(this)->get_segment(reinterpret_cast<size_t>(ptr));
#else
return reinterpret_cast<size_t>(ptr);
#endif
}
clause * clause_allocator::mk_clause(unsigned num_lits, literal const * lits, bool learned) {
size_t size = clause::get_obj_size(num_lits);
#ifdef _AMD64_
size_t slot = size >> c_cls_alignment;
if ((size & c_aligment_mask) != 0)
slot++;
size = slot << c_cls_alignment;
#endif
void * mem = m_allocator.allocate(size);
clause * cls = new (mem) clause(m_id_gen.mk(), num_lits, lits, learned);
TRACE("sat", tout << "alloc: " << cls->id() << " " << cls << " " << *cls << " " << (learned?"l":"a") << "\n";);
SASSERT(!learned || cls->is_learned());
return cls;
}
void clause_allocator::del_clause(clause * cls) {
TRACE("sat", tout << "delete: " << cls->id() << " " << cls << " " << *cls << "\n";);
m_id_gen.recycle(cls->id());
size_t size = clause::get_obj_size(cls->m_capacity);
#ifdef _AMD64_
size_t slot = size >> c_cls_alignment;
if ((size & c_aligment_mask) != 0)
slot++;
size = slot << c_cls_alignment;
#endif
cls->~clause();
m_allocator.deallocate(size, cls);
}
std::ostream & operator<<(std::ostream & out, clause const & c) {
out << "(";
for (unsigned i = 0; i < c.size(); i++) {
if (i > 0) out << " ";
out << c[i];
}
out << ")";
if (c.was_removed()) out << "x";
if (c.strengthened()) out << "+";
if (c.is_learned()) out << "*";
return out;
}
std::ostream & operator<<(std::ostream & out, clause_vector const & cs) {
clause_vector::const_iterator it = cs.begin();
clause_vector::const_iterator end = cs.end();
for (; it != end; ++it) {
out << *(*it) << "\n";
}
return out;
}
bool clause_wrapper::contains(literal l) const {
unsigned sz = size();
for (unsigned i = 0; i < sz; i++)
if (operator[](i) == l)
return true;
return false;
}
bool clause_wrapper::contains(bool_var v) const {
unsigned sz = size();
for (unsigned i = 0; i < sz; i++)
if (operator[](i).var() == v)
return true;
return false;
}
std::ostream & operator<<(std::ostream & out, clause_wrapper const & c) {
out << "(";
for (unsigned i = 0; i < c.size(); i++) {
if (i > 0) out << " ";
out << c[i];
}
out << ")";
return out;
}
};
<commit_msg>Fix incorrect (off by one) bound check. Also assert that we don't increment ``m_num_segments`` beyond the maximum value (``c_max_segments``).<commit_after>/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
sat_clause.cpp
Abstract:
Clauses
Author:
Leonardo de Moura (leonardo) 2011-05-21.
Revision History:
--*/
#include<memory.h>
#include"sat_clause.h"
#include"z3_exception.h"
#include"trace.h"
namespace sat {
clause::clause(unsigned id, unsigned sz, literal const * lits, bool learned):
m_id(id),
m_size(sz),
m_capacity(sz),
m_removed(false),
m_learned(learned),
m_used(false),
m_frozen(false),
m_reinit_stack(false),
m_inact_rounds(0) {
memcpy(m_lits, lits, sizeof(literal) * sz);
mark_strengthened();
SASSERT(check_approx());
SASSERT(sz > 1);
}
var_approx_set clause::approx(unsigned num, literal const * lits) {
var_approx_set r;
for (unsigned i = 0; i < num; i++)
r.insert(lits[i].var());
return r;
}
void clause::update_approx() {
m_approx = approx(m_size, m_lits);
}
bool clause::check_approx() const {
var_approx_set curr = m_approx;
const_cast<clause*>(this)->update_approx();
SASSERT(may_eq(curr, m_approx));
return true;
}
bool clause::contains(literal l) const {
for (unsigned i = 0; i < m_size; i++)
if (m_lits[i] == l)
return true;
return false;
}
bool clause::contains(bool_var v) const {
for (unsigned i = 0; i < m_size; i++)
if (m_lits[i].var() == v)
return true;
return false;
}
void clause::elim(literal l) {
unsigned i;
for (i = 0; i < m_size; i++)
if (m_lits[i] == l)
break;
SASSERT(i < m_size);
i++;
for (; i < m_size; i++)
m_lits[i-1] = m_lits[i];
m_size--;
mark_strengthened();
}
bool clause::satisfied_by(model const & m) const {
for (unsigned i = 0; i < m_size; i++) {
literal l = m_lits[i];
if (l.sign()) {
if (m[l.var()] == l_false)
return true;
}
else {
if (m[l.var()] == l_true)
return true;
}
}
return false;
}
void tmp_clause::set(unsigned num_lits, literal const * lits, bool learned) {
if (m_clause && m_clause->m_capacity < num_lits) {
dealloc_svect(m_clause);
m_clause = 0;
}
if (!m_clause) {
void * mem = alloc_svect(char, clause::get_obj_size(num_lits));
m_clause = new (mem) clause(UINT_MAX, num_lits, lits, learned);
}
else {
SASSERT(m_clause->m_id == UINT_MAX);
m_clause->m_size = num_lits;
m_clause->m_learned = learned;
memcpy(m_clause->m_lits, lits, sizeof(literal) * num_lits);
}
SASSERT(m_clause->m_size <= m_clause->m_capacity);
for (unsigned i = 0; i < num_lits; i++) {
SASSERT((*m_clause)[i] == lits[i]);
}
}
clause_allocator::clause_allocator():
m_allocator("clause-allocator") {
#ifdef _AMD64_
m_num_segments = 0;
#endif
}
clause * clause_allocator::get_clause(clause_offset cls_off) const {
#ifdef _AMD64_
return reinterpret_cast<clause *>(m_segments[cls_off & c_aligment_mask] + (static_cast<size_t>(cls_off) & ~c_aligment_mask));
#else
return reinterpret_cast<clause *>(cls_off);
#endif
}
#ifdef _AMD64_
unsigned clause_allocator::get_segment(size_t ptr) {
SASSERT((ptr & c_aligment_mask) == 0);
ptr &= ~0xFFFFFFFFull; // Keep only high part
unsigned i = 0;
for (i = 0; i < m_num_segments; ++i)
if (m_segments[i] == ptr)
return i;
i = m_num_segments;
m_num_segments++;
SASSERT(m_num_segments <= c_max_segments);
if (i >= c_max_segments)
throw default_exception("segment out of range");
m_segments[i] = ptr;
return i;
}
#endif
clause_offset clause_allocator::get_offset(clause const * ptr) const {
#ifdef _AMD64_
return static_cast<unsigned>(reinterpret_cast<size_t>(ptr)) + const_cast<clause_allocator*>(this)->get_segment(reinterpret_cast<size_t>(ptr));
#else
return reinterpret_cast<size_t>(ptr);
#endif
}
clause * clause_allocator::mk_clause(unsigned num_lits, literal const * lits, bool learned) {
size_t size = clause::get_obj_size(num_lits);
#ifdef _AMD64_
size_t slot = size >> c_cls_alignment;
if ((size & c_aligment_mask) != 0)
slot++;
size = slot << c_cls_alignment;
#endif
void * mem = m_allocator.allocate(size);
clause * cls = new (mem) clause(m_id_gen.mk(), num_lits, lits, learned);
TRACE("sat", tout << "alloc: " << cls->id() << " " << cls << " " << *cls << " " << (learned?"l":"a") << "\n";);
SASSERT(!learned || cls->is_learned());
return cls;
}
void clause_allocator::del_clause(clause * cls) {
TRACE("sat", tout << "delete: " << cls->id() << " " << cls << " " << *cls << "\n";);
m_id_gen.recycle(cls->id());
size_t size = clause::get_obj_size(cls->m_capacity);
#ifdef _AMD64_
size_t slot = size >> c_cls_alignment;
if ((size & c_aligment_mask) != 0)
slot++;
size = slot << c_cls_alignment;
#endif
cls->~clause();
m_allocator.deallocate(size, cls);
}
std::ostream & operator<<(std::ostream & out, clause const & c) {
out << "(";
for (unsigned i = 0; i < c.size(); i++) {
if (i > 0) out << " ";
out << c[i];
}
out << ")";
if (c.was_removed()) out << "x";
if (c.strengthened()) out << "+";
if (c.is_learned()) out << "*";
return out;
}
std::ostream & operator<<(std::ostream & out, clause_vector const & cs) {
clause_vector::const_iterator it = cs.begin();
clause_vector::const_iterator end = cs.end();
for (; it != end; ++it) {
out << *(*it) << "\n";
}
return out;
}
bool clause_wrapper::contains(literal l) const {
unsigned sz = size();
for (unsigned i = 0; i < sz; i++)
if (operator[](i) == l)
return true;
return false;
}
bool clause_wrapper::contains(bool_var v) const {
unsigned sz = size();
for (unsigned i = 0; i < sz; i++)
if (operator[](i).var() == v)
return true;
return false;
}
std::ostream & operator<<(std::ostream & out, clause_wrapper const & c) {
out << "(";
for (unsigned i = 0; i < c.size(); i++) {
if (i > 0) out << " ";
out << c[i];
}
out << ")";
return out;
}
};
<|endoftext|> |
<commit_before>#pragma once
#include <pthread.h>
class zl_mutex_impl
{
public:
zl_mutex_impl();
~zl_mutex_impl();
bool try_lock();
void lock();
void unlock();
private:
pthread_mutex_t mx_;
};
<commit_msg>* z_platform 实现linux平台下的mutex(安卓环境测试通过)<commit_after>#pragma once
#include <pthread.h>
class zl_mutex_impl
{
public:
zl_mutex_impl();
~zl_mutex_impl();
bool try_lock();
void lock();
void unlock();
private:
pthread_mutex_t mx_;
};
inline zl_mutex_impl::zl_mutex_impl()
{ pthread_mutex_init(&mx_,NULL); }
inline zl_mutex_impl::~zl_mutex_impl()
{ pthread_mutex_destroy(&mx_); }
inline bool zl_mutex_impl::try_lock()
{ return !pthread_mutex_trylock(&mx_); }
inline void zl_mutex_impl::lock()
{ pthread_mutex_lock(&mx_); }
inline void zl_mutex_impl::unlock()
{ pthread_mutex_unlock(&mx_); }
<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/log/extent_manager.hpp"
#include "arch/arch.hpp"
#include "logger.hpp"
#include "perfmon/perfmon.hpp"
#include "serializer/log/log_serializer.hpp"
struct extent_info_t {
public:
enum state_t {
state_unreserved,
state_in_use,
state_free
};
private:
state_t state_;
public:
void set_state(state_t new_state) {
guarantee(state_ != state_in_use || extent_use_refcount == 0);
state_ = new_state;
}
state_t state() const { return state_; }
// Valid and non-zero when state_in_use. There are two ways to own a part of
// this refcount. One is if you believe you're currently "using" the extent (if
// you're the LBA or data_block_manager_t). The other is (at the time of
// writing) for every (extent_transaction_t, block_id) for live extent
// transactions that have set an i_array entry to zero (in the data block
// manager) but have not yet been commmitted. The data_block_manager_t and LBA
// ownership of the refcount also can get passed into the extent_transaction_t
// object.
int32_t extent_use_refcount;
int64_t next_in_free_list; // Valid if state == state_free
extent_info_t() : state_(state_unreserved),
extent_use_refcount(0),
next_in_free_list(-1) {}
};
class extent_zone_t {
const size_t extent_size;
unsigned int offset_to_id(int64_t extent) {
rassert(divides(extent_size, extent));
return extent / extent_size;
}
/* Combination free-list and extent map. Contains one entry per extent.
During the state_reserving_extents phase, each extent has state state_unreserved
or state state_in_use. When we transition to the state_running phase,
we link all of the state_unreserved entries in each zone together into an
extent free list, such that each free entry's 'next_in_free_list' field is the
offset of the next free extent. */
segmented_vector_t<extent_info_t, MAX_DATA_EXTENTS> extents;
int64_t free_list_head;
file_t *const dbfile;
private:
int held_extents_;
public:
int held_extents() const {
return held_extents_;
}
extent_zone_t(file_t *_dbfile, size_t _extent_size)
: extent_size(_extent_size), dbfile(_dbfile), held_extents_(0) { }
extent_reference_t reserve_extent(int64_t extent) {
unsigned int id = offset_to_id(extent);
if (id >= extents.get_size()) {
extent_info_t default_info;
extents.set_size(id + 1, default_info);
}
rassert(extents[id].state() == extent_info_t::state_unreserved);
extents[id].set_state(extent_info_t::state_in_use);
return make_extent_reference(extent);
}
void reconstruct_free_list() {
free_list_head = NULL_OFFSET;
for (int64_t extent = 0;
extent < static_cast<int64_t>(extents.get_size() * extent_size);
extent += extent_size) {
if (extents[offset_to_id(extent)].state() == extent_info_t::state_unreserved) {
extents[offset_to_id(extent)].set_state(extent_info_t::state_free);
extents[offset_to_id(extent)].next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
}
extent_reference_t gen_extent() {
int64_t extent;
if (free_list_head == NULL_OFFSET) {
extent = extents.get_size() * extent_size;
extents.set_size(extents.get_size() + 1);
} else {
extent = free_list_head;
free_list_head = extents[offset_to_id(free_list_head)].next_in_free_list;
held_extents_--;
}
extent_info_t *info = &extents[offset_to_id(extent)];
info->set_state(extent_info_t::state_in_use);
extent_reference_t extent_ref = make_extent_reference(extent);
dbfile->set_size_at_least(extent + extent_size);
return make_extent_reference(extent);
}
extent_reference_t make_extent_reference(const int64_t extent) {
unsigned int id = offset_to_id(extent);
guarantee(id < extents.get_size());
extent_info_t *info = &extents[id];
guarantee(info->state() == extent_info_t::state_in_use);
++info->extent_use_refcount;
return extent_reference_t(extent);
}
void release_extent(extent_reference_t &&extent_ref) {
int64_t extent = extent_ref.release();
extent_info_t *info = &extents[offset_to_id(extent)];
guarantee(info->state() == extent_info_t::state_in_use);
guarantee(info->extent_use_refcount > 0);
--info->extent_use_refcount;
if (info->extent_use_refcount == 0) {
info->set_state(extent_info_t::state_free);
info->next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
};
extent_manager_t::extent_manager_t(file_t *file,
const log_serializer_on_disk_static_config_t *static_config,
log_serializer_stats_t *_stats)
: stats(_stats), extent_size(static_config->extent_size()),
state(state_reserving_extents) {
guarantee(divides(DEVICE_BLOCK_SIZE, extent_size));
zone.init(new extent_zone_t(file, extent_size));
}
extent_manager_t::~extent_manager_t() {
rassert(state == state_reserving_extents || state == state_shut_down);
}
extent_reference_t extent_manager_t::reserve_extent(int64_t extent) {
assert_thread();
rassert(state == state_reserving_extents);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->reserve_extent(extent);
}
void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) {
mb->padding = 0;
}
void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) {
assert_thread();
rassert(state == state_reserving_extents);
current_transaction = NULL;
zone->reconstruct_free_list();
state = state_running;
}
void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert_thread();
rassert(state == state_running);
metablock->padding = 0;
}
void extent_manager_t::shutdown() {
assert_thread();
rassert(state == state_running);
rassert(!current_transaction);
state = state_shut_down;
}
void extent_manager_t::begin_transaction(extent_transaction_t *out) {
assert_thread();
rassert(!current_transaction);
current_transaction = out;
out->init();
}
extent_reference_t extent_manager_t::gen_extent() {
assert_thread();
rassert(state == state_running);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->gen_extent();
}
extent_reference_t
extent_manager_t::copy_extent_reference(const extent_reference_t &extent_ref) {
int64_t offset = extent_ref.offset();
return zone->make_extent_reference(offset);
}
void extent_manager_t::release_extent_into_transaction(extent_reference_t &&extent_ref, extent_transaction_t *txn) {
release_extent_preliminaries();
rassert(current_transaction);
txn->push_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent(extent_reference_t &&extent_ref) {
release_extent_preliminaries();
zone->release_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent_preliminaries() {
assert_thread();
rassert(state == state_running);
--stats->pm_extents_in_use;
stats->pm_bytes_in_use -= extent_size;
}
void extent_manager_t::end_transaction(extent_transaction_t *t) {
assert_thread();
rassert(current_transaction == t);
current_transaction = NULL;
t->mark_end();
}
void extent_manager_t::commit_transaction(extent_transaction_t *t) {
assert_thread();
std::vector<extent_reference_t> extents = t->reset();
for (auto it = extents.begin(); it != extents.end(); ++it) {
zone->release_extent(std::move(*it));
}
}
int extent_manager_t::held_extents() {
assert_thread();
return zone->held_extents();
}
<commit_msg>Made extent_zone_t::offset_to_id be const.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/log/extent_manager.hpp"
#include "arch/arch.hpp"
#include "logger.hpp"
#include "perfmon/perfmon.hpp"
#include "serializer/log/log_serializer.hpp"
struct extent_info_t {
public:
enum state_t {
state_unreserved,
state_in_use,
state_free
};
private:
state_t state_;
public:
void set_state(state_t new_state) {
guarantee(state_ != state_in_use || extent_use_refcount == 0);
state_ = new_state;
}
state_t state() const { return state_; }
// Valid and non-zero when state_in_use. There are two ways to own a part of
// this refcount. One is if you believe you're currently "using" the extent (if
// you're the LBA or data_block_manager_t). The other is (at the time of
// writing) for every (extent_transaction_t, block_id) for live extent
// transactions that have set an i_array entry to zero (in the data block
// manager) but have not yet been commmitted. The data_block_manager_t and LBA
// ownership of the refcount also can get passed into the extent_transaction_t
// object.
int32_t extent_use_refcount;
int64_t next_in_free_list; // Valid if state == state_free
extent_info_t() : state_(state_unreserved),
extent_use_refcount(0),
next_in_free_list(-1) {}
};
class extent_zone_t {
const size_t extent_size;
unsigned int offset_to_id(int64_t extent) const {
rassert(divides(extent_size, extent));
return extent / extent_size;
}
/* Combination free-list and extent map. Contains one entry per extent.
During the state_reserving_extents phase, each extent has state state_unreserved
or state state_in_use. When we transition to the state_running phase,
we link all of the state_unreserved entries in each zone together into an
extent free list, such that each free entry's 'next_in_free_list' field is the
offset of the next free extent. */
segmented_vector_t<extent_info_t, MAX_DATA_EXTENTS> extents;
int64_t free_list_head;
file_t *const dbfile;
private:
int held_extents_;
public:
int held_extents() const {
return held_extents_;
}
extent_zone_t(file_t *_dbfile, size_t _extent_size)
: extent_size(_extent_size), dbfile(_dbfile), held_extents_(0) { }
extent_reference_t reserve_extent(int64_t extent) {
unsigned int id = offset_to_id(extent);
if (id >= extents.get_size()) {
extent_info_t default_info;
extents.set_size(id + 1, default_info);
}
rassert(extents[id].state() == extent_info_t::state_unreserved);
extents[id].set_state(extent_info_t::state_in_use);
return make_extent_reference(extent);
}
void reconstruct_free_list() {
free_list_head = NULL_OFFSET;
for (int64_t extent = 0;
extent < static_cast<int64_t>(extents.get_size() * extent_size);
extent += extent_size) {
if (extents[offset_to_id(extent)].state() == extent_info_t::state_unreserved) {
extents[offset_to_id(extent)].set_state(extent_info_t::state_free);
extents[offset_to_id(extent)].next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
}
extent_reference_t gen_extent() {
int64_t extent;
if (free_list_head == NULL_OFFSET) {
extent = extents.get_size() * extent_size;
extents.set_size(extents.get_size() + 1);
} else {
extent = free_list_head;
free_list_head = extents[offset_to_id(free_list_head)].next_in_free_list;
held_extents_--;
}
extent_info_t *info = &extents[offset_to_id(extent)];
info->set_state(extent_info_t::state_in_use);
extent_reference_t extent_ref = make_extent_reference(extent);
dbfile->set_size_at_least(extent + extent_size);
return make_extent_reference(extent);
}
extent_reference_t make_extent_reference(const int64_t extent) {
unsigned int id = offset_to_id(extent);
guarantee(id < extents.get_size());
extent_info_t *info = &extents[id];
guarantee(info->state() == extent_info_t::state_in_use);
++info->extent_use_refcount;
return extent_reference_t(extent);
}
void release_extent(extent_reference_t &&extent_ref) {
int64_t extent = extent_ref.release();
extent_info_t *info = &extents[offset_to_id(extent)];
guarantee(info->state() == extent_info_t::state_in_use);
guarantee(info->extent_use_refcount > 0);
--info->extent_use_refcount;
if (info->extent_use_refcount == 0) {
info->set_state(extent_info_t::state_free);
info->next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
};
extent_manager_t::extent_manager_t(file_t *file,
const log_serializer_on_disk_static_config_t *static_config,
log_serializer_stats_t *_stats)
: stats(_stats), extent_size(static_config->extent_size()),
state(state_reserving_extents) {
guarantee(divides(DEVICE_BLOCK_SIZE, extent_size));
zone.init(new extent_zone_t(file, extent_size));
}
extent_manager_t::~extent_manager_t() {
rassert(state == state_reserving_extents || state == state_shut_down);
}
extent_reference_t extent_manager_t::reserve_extent(int64_t extent) {
assert_thread();
rassert(state == state_reserving_extents);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->reserve_extent(extent);
}
void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) {
mb->padding = 0;
}
void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) {
assert_thread();
rassert(state == state_reserving_extents);
current_transaction = NULL;
zone->reconstruct_free_list();
state = state_running;
}
void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert_thread();
rassert(state == state_running);
metablock->padding = 0;
}
void extent_manager_t::shutdown() {
assert_thread();
rassert(state == state_running);
rassert(!current_transaction);
state = state_shut_down;
}
void extent_manager_t::begin_transaction(extent_transaction_t *out) {
assert_thread();
rassert(!current_transaction);
current_transaction = out;
out->init();
}
extent_reference_t extent_manager_t::gen_extent() {
assert_thread();
rassert(state == state_running);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
return zone->gen_extent();
}
extent_reference_t
extent_manager_t::copy_extent_reference(const extent_reference_t &extent_ref) {
int64_t offset = extent_ref.offset();
return zone->make_extent_reference(offset);
}
void extent_manager_t::release_extent_into_transaction(extent_reference_t &&extent_ref, extent_transaction_t *txn) {
release_extent_preliminaries();
rassert(current_transaction);
txn->push_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent(extent_reference_t &&extent_ref) {
release_extent_preliminaries();
zone->release_extent(std::move(extent_ref));
}
void extent_manager_t::release_extent_preliminaries() {
assert_thread();
rassert(state == state_running);
--stats->pm_extents_in_use;
stats->pm_bytes_in_use -= extent_size;
}
void extent_manager_t::end_transaction(extent_transaction_t *t) {
assert_thread();
rassert(current_transaction == t);
current_transaction = NULL;
t->mark_end();
}
void extent_manager_t::commit_transaction(extent_transaction_t *t) {
assert_thread();
std::vector<extent_reference_t> extents = t->reset();
for (auto it = extents.begin(); it != extents.end(); ++it) {
zone->release_extent(std::move(*it));
}
}
int extent_manager_t::held_extents() {
assert_thread();
return zone->held_extents();
}
<|endoftext|> |
<commit_before>#include <fcntl.h>
#include <unistd.h>
#include "teefd.h"
struct teefd_obj {
struct pz pzh;
int fd;
void *coonext;
};
static writerfunc write_teefd;
static closefunc free_teefd;
void *make_teefd(const char *fn, void *coo)
{
teefd_obj *r = new teefd_obj;
r->pzh.wf = write_teefd;
r->pzh.cf = free_teefd;
r->fd = open(fn, O_WRONLY|O_CREAT|O_EXCL, 0666);
if (r->fd == -1) {
delete r;
return NULL;
}
r->coonext = coo;
return r;
}
pssize_type write_teefd(void *coo, const void *buf, psize_type len)
{
teefd_obj *to = (teefd_obj *)coo;
(void)write(to->fd, buf, len); // XXX
return do_write(to->coonext, buf, len);
}
void free_teefd(void *coo)
{
teefd_obj *to = (teefd_obj *)coo;
close(to->fd);
do_close(to->coonext);
delete to;
}
<commit_msg>Another try to shut up that warning<commit_after>#include <fcntl.h>
#include <unistd.h>
#include "teefd.h"
struct teefd_obj {
struct pz pzh;
int fd;
void *coonext;
};
static writerfunc write_teefd;
static closefunc free_teefd;
void *make_teefd(const char *fn, void *coo)
{
teefd_obj *r = new teefd_obj;
r->pzh.wf = write_teefd;
r->pzh.cf = free_teefd;
r->fd = open(fn, O_WRONLY|O_CREAT|O_EXCL, 0666);
if (r->fd == -1) {
delete r;
return NULL;
}
r->coonext = coo;
return r;
}
pssize_type write_teefd(void *coo, const void *buf, psize_type len)
{
teefd_obj *to = (teefd_obj *)coo;
if ((psize_type)write(to->fd, buf, len) != len) {
// XXX
}
return do_write(to->coonext, buf, len);
}
void free_teefd(void *coo)
{
teefd_obj *to = (teefd_obj *)coo;
close(to->fd);
do_close(to->coonext);
delete to;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkData.h"
#include "SkEndian.h"
#include "SkSFNTHeader.h"
#include "SkStream.h"
#include "SkOTTable_head.h"
#include "SkOTTable_name.h"
#include "SkOTTableTypes.h"
#include "SkOTUtils.h"
uint32_t SkOTUtils::CalcTableChecksum(SK_OT_ULONG *data, size_t length) {
uint32_t sum = 0;
SK_OT_ULONG *dataEnd = data + ((length + 3) & ~3) / sizeof(SK_OT_ULONG);
for (; data < dataEnd; ++data) {
sum += SkEndian_SwapBE32(*data);
}
return sum;
}
SkData* SkOTUtils::RenameFont(SkStream* fontData,
const char* fontName, int fontNameLen) {
// Get the sfnt header.
SkSFNTHeader sfntHeader;
if (fontData->read(&sfntHeader, sizeof(sfntHeader)) < sizeof(sfntHeader)) {
return NULL;
}
// Find the existing 'name' table.
int tableIndex;
SkSFNTTableDirectoryEntry tableEntry;
int numTables = SkEndian_SwapBE16(sfntHeader.numTables);
for (tableIndex = 0; tableIndex < numTables; ++tableIndex) {
if (fontData->read(&tableEntry, sizeof(tableEntry)) < sizeof(tableEntry)) {
return NULL;
}
if (SkOTTableName::TAG == tableEntry.tag) {
break;
}
}
if (tableIndex == numTables) {
return NULL;
}
if (!fontData->rewind()) {
return NULL;
}
// The required 'name' record types: Family, Style, Unique, Full and PostScript.
const SkOTTableNameRecord::NameID::Predefined::Value namesToCreate[] = {
SkOTTableNameRecord::NameID::Predefined::FontFamilyName,
SkOTTableNameRecord::NameID::Predefined::FontSubfamilyName,
SkOTTableNameRecord::NameID::Predefined::UniqueFontIdentifier,
SkOTTableNameRecord::NameID::Predefined::FullFontName,
SkOTTableNameRecord::NameID::Predefined::PostscriptName,
};
const int namesCount = SK_ARRAY_COUNT(namesToCreate);
// Copy the data, leaving out the old name table.
// In theory, we could also remove the DSIG table if it exists.
size_t nameTableLogicalSize = sizeof(SkOTTableName) + (namesCount * sizeof(SkOTTableNameRecord)) + (fontNameLen * sizeof(wchar_t));
size_t nameTablePhysicalSize = (nameTableLogicalSize + 3) & ~3; // Rounded up to a multiple of 4.
size_t oldNameTablePhysicalSize = (SkEndian_SwapBE32(tableEntry.logicalLength) + 3) & ~3; // Rounded up to a multiple of 4.
size_t oldNameTableOffset = SkEndian_SwapBE32(tableEntry.offset);
//originalDataSize is the size of the original data without the name table.
size_t originalDataSize = fontData->getLength() - oldNameTablePhysicalSize;
size_t newDataSize = originalDataSize + nameTablePhysicalSize;
SK_OT_BYTE* data = static_cast<SK_OT_BYTE*>(sk_malloc_throw(newDataSize));
SkAutoTUnref<SkData> rewrittenFontData(SkData::NewFromMalloc(data, newDataSize));
if (fontData->read(data, oldNameTableOffset) < oldNameTableOffset) {
return NULL;
}
if (fontData->skip(oldNameTablePhysicalSize) < oldNameTablePhysicalSize) {
return NULL;
}
if (fontData->read(data + oldNameTableOffset, originalDataSize - oldNameTableOffset) < originalDataSize - oldNameTableOffset) {
return NULL;
}
//Fix up the offsets of the directory entries after the old 'name' table entry.
SkSFNTTableDirectoryEntry* currentEntry = reinterpret_cast<SkSFNTTableDirectoryEntry*>(data + sizeof(SkSFNTHeader));
SkSFNTTableDirectoryEntry* endEntry = currentEntry + numTables;
SkSFNTTableDirectoryEntry* headTableEntry = NULL;
for (; currentEntry < endEntry; ++currentEntry) {
uint32_t oldOffset = SkEndian_SwapBE32(currentEntry->offset);
if (oldOffset > oldNameTableOffset) {
currentEntry->offset = SkEndian_SwapBE32(oldOffset - oldNameTablePhysicalSize);
}
if (SkOTTableHead::TAG == tableEntry.tag) {
headTableEntry = currentEntry;
}
}
// Make the table directory entry point to the new 'name' table.
SkSFNTTableDirectoryEntry* nameTableEntry = reinterpret_cast<SkSFNTTableDirectoryEntry*>(data + sizeof(SkSFNTHeader)) + tableIndex;
nameTableEntry->logicalLength = SkEndian_SwapBE32(nameTableLogicalSize);
nameTableEntry->offset = SkEndian_SwapBE32(originalDataSize);
// Write the new 'name' table after the original font data.
SkOTTableName* nameTable = reinterpret_cast<SkOTTableName*>(data + originalDataSize);
unsigned short stringOffset = sizeof(SkOTTableName) + (namesCount * sizeof(SkOTTableNameRecord));
nameTable->format = SkOTTableName::format_0;
nameTable->count = SkEndian_SwapBE16(namesCount);
nameTable->stringOffset = SkEndian_SwapBE16(stringOffset);
SkOTTableNameRecord* nameRecords = reinterpret_cast<SkOTTableNameRecord*>(data + originalDataSize + sizeof(SkOTTableName));
for (int i = 0; i < namesCount; ++i) {
nameRecords[i].platformID.value = SkOTTableNameRecord::PlatformID::Windows;
nameRecords[i].encodingID.windows.value = SkOTTableNameRecord::EncodingID::Windows::UnicodeBMPUCS2;
nameRecords[i].languageID.windows.value = SkOTTableNameRecord::LanguageID::Windows::English_UnitedStates;
nameRecords[i].nameID.predefined.value = namesToCreate[i];
nameRecords[i].offset = SkEndian_SwapBE16(0);
nameRecords[i].length = SkEndian_SwapBE16(fontNameLen * sizeof(wchar_t));
}
SK_OT_USHORT* nameString = reinterpret_cast<SK_OT_USHORT*>(data + originalDataSize + stringOffset);
for (int i = 0; i < fontNameLen; ++i) {
nameString[i] = SkEndian_SwapBE16(fontName[i]);
}
unsigned char* logical = data + originalDataSize + nameTableLogicalSize;
unsigned char* physical = data + originalDataSize + nameTablePhysicalSize;
for (; logical < physical; ++logical) {
*logical = 0;
}
// Update the table checksum in the directory entry.
nameTableEntry->checksum = SkEndian_SwapBE32(SkOTUtils::CalcTableChecksum(reinterpret_cast<SK_OT_ULONG*>(nameTable), nameTableLogicalSize));
// Update the checksum adjustment in the head table.
if (headTableEntry) {
size_t headTableOffset = SkEndian_SwapBE32(headTableEntry->offset);
if (headTableOffset + sizeof(SkOTTableHead) < originalDataSize) {
SkOTTableHead* headTable = reinterpret_cast<SkOTTableHead*>(data + headTableOffset);
headTable->checksumAdjustment = SkEndian_SwapBE32(0);
uint32_t unadjustedFontChecksum = SkOTUtils::CalcTableChecksum(reinterpret_cast<SK_OT_ULONG*>(data), originalDataSize + nameTablePhysicalSize);
headTable->checksumAdjustment = SkEndian_SwapBE32(SkOTTableHead::fontChecksum - unadjustedFontChecksum);
}
}
return rewrittenFontData.detach();
}
<commit_msg>When looking for the head table directory entry, compare against the current entry and not the name table entry.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkData.h"
#include "SkEndian.h"
#include "SkSFNTHeader.h"
#include "SkStream.h"
#include "SkOTTable_head.h"
#include "SkOTTable_name.h"
#include "SkOTTableTypes.h"
#include "SkOTUtils.h"
uint32_t SkOTUtils::CalcTableChecksum(SK_OT_ULONG *data, size_t length) {
uint32_t sum = 0;
SK_OT_ULONG *dataEnd = data + ((length + 3) & ~3) / sizeof(SK_OT_ULONG);
for (; data < dataEnd; ++data) {
sum += SkEndian_SwapBE32(*data);
}
return sum;
}
SkData* SkOTUtils::RenameFont(SkStream* fontData,
const char* fontName, int fontNameLen) {
// Get the sfnt header.
SkSFNTHeader sfntHeader;
if (fontData->read(&sfntHeader, sizeof(sfntHeader)) < sizeof(sfntHeader)) {
return NULL;
}
// Find the existing 'name' table.
int tableIndex;
SkSFNTTableDirectoryEntry tableEntry;
int numTables = SkEndian_SwapBE16(sfntHeader.numTables);
for (tableIndex = 0; tableIndex < numTables; ++tableIndex) {
if (fontData->read(&tableEntry, sizeof(tableEntry)) < sizeof(tableEntry)) {
return NULL;
}
if (SkOTTableName::TAG == tableEntry.tag) {
break;
}
}
if (tableIndex == numTables) {
return NULL;
}
if (!fontData->rewind()) {
return NULL;
}
// The required 'name' record types: Family, Style, Unique, Full and PostScript.
const SkOTTableNameRecord::NameID::Predefined::Value namesToCreate[] = {
SkOTTableNameRecord::NameID::Predefined::FontFamilyName,
SkOTTableNameRecord::NameID::Predefined::FontSubfamilyName,
SkOTTableNameRecord::NameID::Predefined::UniqueFontIdentifier,
SkOTTableNameRecord::NameID::Predefined::FullFontName,
SkOTTableNameRecord::NameID::Predefined::PostscriptName,
};
const int namesCount = SK_ARRAY_COUNT(namesToCreate);
// Copy the data, leaving out the old name table.
// In theory, we could also remove the DSIG table if it exists.
size_t nameTableLogicalSize = sizeof(SkOTTableName) + (namesCount * sizeof(SkOTTableNameRecord)) + (fontNameLen * sizeof(wchar_t));
size_t nameTablePhysicalSize = (nameTableLogicalSize + 3) & ~3; // Rounded up to a multiple of 4.
size_t oldNameTablePhysicalSize = (SkEndian_SwapBE32(tableEntry.logicalLength) + 3) & ~3; // Rounded up to a multiple of 4.
size_t oldNameTableOffset = SkEndian_SwapBE32(tableEntry.offset);
//originalDataSize is the size of the original data without the name table.
size_t originalDataSize = fontData->getLength() - oldNameTablePhysicalSize;
size_t newDataSize = originalDataSize + nameTablePhysicalSize;
SK_OT_BYTE* data = static_cast<SK_OT_BYTE*>(sk_malloc_throw(newDataSize));
SkAutoTUnref<SkData> rewrittenFontData(SkData::NewFromMalloc(data, newDataSize));
if (fontData->read(data, oldNameTableOffset) < oldNameTableOffset) {
return NULL;
}
if (fontData->skip(oldNameTablePhysicalSize) < oldNameTablePhysicalSize) {
return NULL;
}
if (fontData->read(data + oldNameTableOffset, originalDataSize - oldNameTableOffset) < originalDataSize - oldNameTableOffset) {
return NULL;
}
//Fix up the offsets of the directory entries after the old 'name' table entry.
SkSFNTTableDirectoryEntry* currentEntry = reinterpret_cast<SkSFNTTableDirectoryEntry*>(data + sizeof(SkSFNTHeader));
SkSFNTTableDirectoryEntry* endEntry = currentEntry + numTables;
SkSFNTTableDirectoryEntry* headTableEntry = NULL;
for (; currentEntry < endEntry; ++currentEntry) {
uint32_t oldOffset = SkEndian_SwapBE32(currentEntry->offset);
if (oldOffset > oldNameTableOffset) {
currentEntry->offset = SkEndian_SwapBE32(oldOffset - oldNameTablePhysicalSize);
}
if (SkOTTableHead::TAG == currentEntry->tag) {
headTableEntry = currentEntry;
}
}
// Make the table directory entry point to the new 'name' table.
SkSFNTTableDirectoryEntry* nameTableEntry = reinterpret_cast<SkSFNTTableDirectoryEntry*>(data + sizeof(SkSFNTHeader)) + tableIndex;
nameTableEntry->logicalLength = SkEndian_SwapBE32(nameTableLogicalSize);
nameTableEntry->offset = SkEndian_SwapBE32(originalDataSize);
// Write the new 'name' table after the original font data.
SkOTTableName* nameTable = reinterpret_cast<SkOTTableName*>(data + originalDataSize);
unsigned short stringOffset = sizeof(SkOTTableName) + (namesCount * sizeof(SkOTTableNameRecord));
nameTable->format = SkOTTableName::format_0;
nameTable->count = SkEndian_SwapBE16(namesCount);
nameTable->stringOffset = SkEndian_SwapBE16(stringOffset);
SkOTTableNameRecord* nameRecords = reinterpret_cast<SkOTTableNameRecord*>(data + originalDataSize + sizeof(SkOTTableName));
for (int i = 0; i < namesCount; ++i) {
nameRecords[i].platformID.value = SkOTTableNameRecord::PlatformID::Windows;
nameRecords[i].encodingID.windows.value = SkOTTableNameRecord::EncodingID::Windows::UnicodeBMPUCS2;
nameRecords[i].languageID.windows.value = SkOTTableNameRecord::LanguageID::Windows::English_UnitedStates;
nameRecords[i].nameID.predefined.value = namesToCreate[i];
nameRecords[i].offset = SkEndian_SwapBE16(0);
nameRecords[i].length = SkEndian_SwapBE16(fontNameLen * sizeof(wchar_t));
}
SK_OT_USHORT* nameString = reinterpret_cast<SK_OT_USHORT*>(data + originalDataSize + stringOffset);
for (int i = 0; i < fontNameLen; ++i) {
nameString[i] = SkEndian_SwapBE16(fontName[i]);
}
unsigned char* logical = data + originalDataSize + nameTableLogicalSize;
unsigned char* physical = data + originalDataSize + nameTablePhysicalSize;
for (; logical < physical; ++logical) {
*logical = 0;
}
// Update the table checksum in the directory entry.
nameTableEntry->checksum = SkEndian_SwapBE32(SkOTUtils::CalcTableChecksum(reinterpret_cast<SK_OT_ULONG*>(nameTable), nameTableLogicalSize));
// Update the checksum adjustment in the head table.
if (headTableEntry) {
size_t headTableOffset = SkEndian_SwapBE32(headTableEntry->offset);
if (headTableOffset + sizeof(SkOTTableHead) < originalDataSize) {
SkOTTableHead* headTable = reinterpret_cast<SkOTTableHead*>(data + headTableOffset);
headTable->checksumAdjustment = SkEndian_SwapBE32(0);
uint32_t unadjustedFontChecksum = SkOTUtils::CalcTableChecksum(reinterpret_cast<SK_OT_ULONG*>(data), originalDataSize + nameTablePhysicalSize);
headTable->checksumAdjustment = SkEndian_SwapBE32(SkOTTableHead::fontChecksum - unadjustedFontChecksum);
}
}
return rewrittenFontData.detach();
}
<|endoftext|> |
<commit_before>#define OVERRIDE_MATRIX_MULT true
#include <thread>
#include <future>
#include "../lib/matrix.hpp"
#include "../lib/pool.hpp"
#include "../lib/image.hpp"
#include "../lib/promise-polyfill.hpp"
#include "../lib/queue.hpp"
/* 1a */
matrix operator*(const matrix &x, const matrix &y) {
if (x.cols != y.rows) {
throw std::invalid_argument("Invalid arguments");
}
matrix z;
z.create(x.rows, y.cols);
parallel_for(0u, x.rows * y.cols, [&](int k) {
unsigned i = k / y.cols, j = k % y.cols;
int zz = 0;
for (unsigned k = 0; k < x.cols; k++) {
zz += x(i, k) * y(k, j);
}
z(i, j) = zz;
});
return z;
}
/*
* 2. parallel_for uses the queue_work function instead of create_thread.
* a. Why?
* - Parallel for loops are typically used in data problems which require the
* - computation of some value over a loop. As such, these are often short lived
* - and cause blocks in control flow. To mitigate the delay and increase the
* - benefit of using parallel_for, the work is pushed into the pool so that thread
* - creation is not experienced (which takes time), additionally, since the computation
* - is most likely computationally expensive, the pool will only schedule the work
* - when threads are available instead of maxing out the system and causing system lag.
*
* b. Give an example of when should you use create_thread instead of queue_work
* to execute work asynchronously?
* - Create thread should always be used for work which is *long running* or blocking.
* - Reason being is that long running work (or threads which will be alive the entire
* - program life) will utilize all the threads provisioned to the pool and will cease
* - execution of other work (e.g. a worker thread that works on a concurrent queue).
* - Knowing this, simply spawn a new thread!
*/
/* 3 */
//Consider the following program
int mainEx() {
int value = 32;
queue_work([&] {
value -= 17;
printf("%d\n", value);
});
return value;
}
/*
* 3a. What is the result of this program? (Hint: its not always the same).
* - The result of this program varies depending on how quickly the queued
* - works starts in relation to the execution of the remaining code (pop stack
* - [removing queue_work return], push `value`, and return stack[0]/int).
*
* Possible results:
* 1. mainEx returns 32
* 2. mainEx returns 15
* 3. mainEx returns 15 and prints 15
*/
/* 3b - Correct the defect. */
int mainExFixed() {
int value = 32;
auto f = queue_work([&] {
value -= 17;
printf("%d\n", value);
});
f.wait();
return value;
}
/* 4 completed */
void conv(matrix &x, const matrix &k) {
matrix y;
y.create(x.rows + k.rows, x.cols + k.cols);
const unsigned xR = x.rows, xC = x.cols;
parallel_for(0u, xR * xC, [&](auto i) {
auto row = i % xR, col = i / xR;
auto yrow = row + k.rows / 2;
auto ycol = col + k.cols / 2;
y(yrow, ycol) = x(row, col);
});
std::atomic<int> weight(0);
const unsigned kR = k.rows, kC = k.cols;
parallel_for(0u, kR * kC, [&](int i) {
auto row = i % kR, col = i / kR;
weight += k(row, col);
});
parallel_for(0u, xR * xC, [&](int i) {
auto row = i % xR, col = i / xR;
int t = 0;
auto yrow = row;
for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {
auto ycol = col;
for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {
t += y(yrow, ycol) * k(krow, kcol);
}
}
if (weight != 0) {
t /= weight;
}
x(row, col) = t;
});
}
int binomial_coefficient(int n, int k) {
if (n <= 1 || k == 0) {
return 1;
} else {
return binomial_coefficient(n - 1, k - 1) * n / k;
}
}
matrix binomial(int n) {
if ((n & 1) == 0) {
throw std::invalid_argument("n must be odd");
}
matrix x, y;
x.create(1, n);
y.create(n, 1);
for (int i = 0; i < n / 2; i++) {
x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);
y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);
}
x(0, n / 2) = binomial_coefficient(n - 1, n / 2);
y(n / 2, 0) = binomial_coefficient(n - 1, n / 2);
return y * x;
}
concurrent_queue<matrix> pipeline;
std::future<matrix> blur_image_async(matrix x) {
return std::async(std::launch::async, [](matrix bmp) {
matrix kernel = binomial(3);
conv(bmp, kernel);
return std::move(bmp);
}, std::move(x));
}
int main_q4() {
auto pipeline_thread = std::thread([] {
for (;;) {
auto x = pipeline.pop();
auto b = blur_image_async(std::move(x)).share();
Promise::then(b, [](auto f) {
matrix h = histogram(f.get());
}).wait();
}
});
Promise::then(load_image_async("image.png").share(), [](auto f) {
pipeline.push(f.get());
}).wait();
pipeline_thread.join();
return 0;
}
/* 4 end */
/*
* 5a. How does a semaphore differ from mutex?
* - A semaphore differs from a mutex in that it is not a mutual exclusion lock,
* - a semaphore, unlike a mutex, can be aquired multiple times (depending on how
* - the sempahore is created) unlike a mutex which is strictly locked or unlocked.
* - Additionally, a semaphore lives in the file system and is not restrictied to the
* - process in which it was created (like a mutex), which makes it useful to lock
* - access to things like shared memory pools across processes.
*
* 5b. Describe the operation of a bar (sitting down, ordering a drink) in terms
* of a semaphore and mutex.
*/
int main(int argc, char **argv) {
return 0;
}
<commit_msg>Add some clarifying comments<commit_after>#define OVERRIDE_MATRIX_MULT true
#include <thread>
#include <future>
#include "../lib/matrix.hpp"
#include "../lib/pool.hpp"
#include "../lib/image.hpp"
#include "../lib/promise-polyfill.hpp"
#include "../lib/queue.hpp"
/* 1a */
matrix operator*(const matrix &x, const matrix &y) {
if (x.cols != y.rows) {
throw std::invalid_argument("Invalid arguments");
}
matrix z;
z.create(x.rows, y.cols);
//Flatten the loops so we can fairly chunk up the work (assume the
//picture isn't the same width as it is height!)
parallel_for(0u, x.rows * y.cols, [&](int k) {
unsigned i = k / y.cols, j = k % y.cols;
int zz = 0;
for (unsigned k = 0; k < x.cols; k++) {
zz += x(i, k) * y(k, j);
}
z(i, j) = zz;
});
return z;
}
/*
* 2. parallel_for uses the queue_work function instead of create_thread.
* a. Why?
* - Parallel for loops are typically used in data problems which require the
* - computation of some value over a loop. As such, these are often short lived
* - and cause blocks in control flow. To mitigate the delay and increase the
* - benefit of using parallel_for, the work is pushed into the pool so that thread
* - creation is not experienced (which takes time), additionally, since the computation
* - is most likely computationally expensive, the pool will only schedule the work
* - when threads are available instead of maxing out the system and causing system lag.
*
* b. Give an example of when should you use create_thread instead of queue_work
* to execute work asynchronously?
* - Create thread should always be used for work which is *long running* or blocking.
* - Reason being is that long running work (or threads which will be alive the entire
* - program life) will utilize all the threads provisioned to the pool and will cease
* - execution of other work (e.g. a worker thread that works on a concurrent queue).
* - Knowing this, simply spawn a new thread!
*/
/* 3 */
//Consider the following program
int mainEx() {
int value = 32;
queue_work([&] {
value -= 17;
printf("%d\n", value);
});
return value;
}
/*
* 3a. What is the result of this program? (Hint: its not always the same).
* - The result of this program varies depending on how quickly the queued
* - works starts in relation to the execution of the remaining code (pop stack
* - [removing queue_work return], push `value`, and return stack[0]/int).
*
* Possible results:
* 1. mainEx returns 32
* 2. mainEx returns 15
* 3. mainEx returns 15 and prints 15
*/
/* 3b - Correct the defect. */
int mainExFixed() {
int value = 32;
auto f = queue_work([&] {
value -= 17;
printf("%d\n", value);
});
f.wait();//Wait for the async work to complete so our value is consistent every time
return value;
}
/* 4 completed */
void conv(matrix &x, const matrix &k) {
matrix y;
y.create(x.rows + k.rows, x.cols + k.cols);
const unsigned xR = x.rows, xC = x.cols;
parallel_for(0u, xR * xC, [&](auto i) {
auto row = i % xR, col = i / xR;
auto yrow = row + k.rows / 2;
auto ycol = col + k.cols / 2;
y(yrow, ycol) = x(row, col);
});
std::atomic<int> weight(0);
const unsigned kR = k.rows, kC = k.cols;
parallel_for(0u, kR * kC, [&](int i) {
auto row = i % kR, col = i / kR;
weight += k(row, col);
});
parallel_for(0u, xR * xC, [&](int i) {
auto row = i % xR, col = i / xR;
int t = 0;
auto yrow = row;
for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {
auto ycol = col;
for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {
t += y(yrow, ycol) * k(krow, kcol);
}
}
if (weight != 0) {
t /= weight;
}
x(row, col) = t;
});
}
int binomial_coefficient(int n, int k) {
if (n <= 1 || k == 0) {
return 1;
} else {
return binomial_coefficient(n - 1, k - 1) * n / k;
}
}
matrix binomial(int n) {
if ((n & 1) == 0) {
throw std::invalid_argument("n must be odd");
}
matrix x, y;
x.create(1, n);
y.create(n, 1);
for (int i = 0; i < n / 2; i++) {
x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);
y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);
}
x(0, n / 2) = binomial_coefficient(n - 1, n / 2);
y(n / 2, 0) = binomial_coefficient(n - 1, n / 2);
return y * x;
}
concurrent_queue<matrix> pipeline;
std::future<matrix> blur_image_async(matrix x) {
return std::async(std::launch::async, [](matrix bmp) {
matrix kernel = binomial(3);
conv(bmp, kernel);
return std::move(bmp);
}, std::move(x));
}
int main_q4() {
auto pipeline_thread = std::thread([] {
for (;;) {
auto x = pipeline.pop();
auto b = blur_image_async(std::move(x)).share();
Promise::then(b, [](auto f) {
matrix h = histogram(f.get());
}).wait();
}
});
Promise::then(load_image_async("image.png").share(), [](auto f) {
pipeline.push(f.get());
}).wait();
pipeline_thread.join();
return 0;
}
/* 4 end */
/*
* 5a. How does a semaphore differ from mutex?
* - A semaphore differs from a mutex in that it is not a mutual exclusion lock,
* - a semaphore, unlike a mutex, can be aquired multiple times (depending on how
* - the sempahore is created) unlike a mutex which is strictly locked or unlocked.
* - Additionally, a semaphore lives in the file system and is not restrictied to the
* - process in which it was created (like a mutex), which makes it useful to lock
* - access to things like shared memory pools across processes.
*
* 5b. Describe the operation of a bar (sitting down, ordering a drink) in terms
* of a semaphore and mutex.
*/
int main(int argc, char **argv) {
return 0;
}
<|endoftext|> |
<commit_before>#ifndef ECL_COMMAND_HPP
#define ECL_COMMAND_HPP
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <array>
#include "singleton.hpp"
#ifndef RECEIVER_CAPACITY
#define RECEIVER_CAPACITY 32
#endif
#ifndef DEFAULT_INDENT_INCREMENT
#define DEFAULT_INDENT_INCREMENT 4
#endif
namespace ecl
{
template<typename ST>
static void print_indent(ST& st, size_t indent)
{
for(size_t i = 0; i < indent; ++i)
{
st << " ";
}
}
namespace detail
{
template<typename cmd>
class i_receiver
{
protected:
virtual ~i_receiver() {}
public:
virtual void receive(cmd&) = 0;
};
template<typename cmd>
class cmd_core
{
protected:
void reg(detail::i_receiver<cmd>* const i)
{
for(auto &itf: array_singleton::instance())
{
if(nullptr == itf)
{
itf = i;
return;
}
}
}
void execute(cmd& c) const
{
std::size_t sz = array_singleton::instance().size();
for(std::size_t i = 0; i < sz; ++i)
{
if(nullptr != array_singleton::instance()[i])
{
array_singleton::instance()[i]->receive(c);
}
}
}
private:
typedef ecl::singleton<
std::array<detail::i_receiver<cmd>*, RECEIVER_CAPACITY>
> array_singleton;
};
} // namespace detail
template<typename NAME, typename cmd>
class command : public virtual detail::cmd_core<cmd>
{
public:
bool dispatch()
{
this->execute(*static_cast<cmd*>(this));
return true;
}
bool init(const uint8_t argc,
const uint8_t** argv)
{
m_argc = argc;
m_argv = argv;
return true;
}
constexpr static const char* name()
{
return NAME::name();
}
template<typename ST>
static void show_help(ST& st, size_t indent, size_t indent_increment = DEFAULT_INDENT_INCREMENT)
{
(void)indent_increment;
for(size_t i = 0; i < indent; ++i)
{
st << " ";
}
st << name() << "\n\r";
}
protected:
uint8_t m_argc;
const uint8_t** m_argv;
};
template<typename cmd>
class receiver : public virtual detail::cmd_core<cmd>,
public detail::i_receiver<cmd>
{
protected:
receiver()
{
this->detail::cmd_core<cmd>::reg(this);
}
virtual ~receiver() {}
};
} // namespace ecl
#endif // ECL_COMMAND_HPP
<commit_msg>Cleanup.<commit_after>#ifndef ECL_COMMAND_HPP
#define ECL_COMMAND_HPP
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <array>
#include "singleton.hpp"
#ifndef RECEIVER_CAPACITY
#define RECEIVER_CAPACITY 32
#endif
#ifndef DEFAULT_INDENT_INCREMENT
#define DEFAULT_INDENT_INCREMENT 4
#endif
namespace ecl
{
template<typename ST>
static void print_indent(ST& st, size_t indent)
{
for(size_t i = 0; i < indent; ++i)
{
st << " ";
}
}
namespace detail
{
template<typename cmd>
class i_receiver
{
protected:
virtual ~i_receiver() {}
public:
virtual void receive(cmd&) = 0;
};
template<typename cmd>
class cmd_core
{
protected:
void reg(detail::i_receiver<cmd>* const i)
{
for(auto &itf: array_singleton::instance())
{
if(nullptr == itf)
{
itf = i;
return;
}
}
}
void execute(cmd& c) const
{
std::size_t sz = array_singleton::instance().size();
for(std::size_t i = 0; i < sz; ++i)
{
if(nullptr != array_singleton::instance()[i])
{
array_singleton::instance()[i]->receive(c);
}
}
}
private:
typedef ecl::singleton<
std::array<detail::i_receiver<cmd>*, RECEIVER_CAPACITY>
> array_singleton;
};
} // namespace detail
template<typename NAME, typename cmd>
class command : public virtual detail::cmd_core<cmd>
{
public:
bool dispatch()
{
this->execute(*static_cast<cmd*>(this));
return true;
}
bool init(const uint8_t argc,
const uint8_t** argv)
{
m_argc = argc;
m_argv = argv;
return true;
}
constexpr static const char* name()
{
return NAME::name();
}
template<typename ST>
static void show_help(ST& st, size_t indent, size_t indent_increment = DEFAULT_INDENT_INCREMENT)
{
(void)indent_increment;
print_indent(st, indent);
st << name() << "\n\r";
}
protected:
uint8_t m_argc;
const uint8_t** m_argv;
};
template<typename cmd>
class receiver : public virtual detail::cmd_core<cmd>,
public detail::i_receiver<cmd>
{
protected:
receiver()
{
this->detail::cmd_core<cmd>::reg(this);
}
virtual ~receiver() {}
};
} // namespace ecl
#endif // ECL_COMMAND_HPP
<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/log/extent_manager.hpp"
#include "arch/arch.hpp"
#include "logger.hpp"
#include "perfmon/perfmon.hpp"
#include "serializer/log/log_serializer.hpp"
struct extent_info_t {
public:
enum state_t {
state_unreserved,
state_in_use,
state_free
};
private:
state_t state_;
public:
void set_state(state_t new_state) {
guarantee(state_ != state_in_use || extent_use_refcount == 0);
state_ = new_state;
}
state_t state() const { return state_; }
// Valid and non-zero when state_in_use. There are two ways to own a part of
// this refcount. One is if you believe you're currently "using" the extent (if
// you're the LBA or data_block_manager_t). The other is (at the time of
// writing) for every (extent_transaction_t, block_id) for live extent
// transactions that have set an i_array entry to zero (in the data block
// manager) but have not yet been commmitted. The data_block_manager_t and LBA
// ownership of the refcount also can get passed into the extent_transaction_t
// object.
int32_t extent_use_refcount;
int64_t next_in_free_list; // Valid if state == state_free
extent_info_t() : state_(state_unreserved),
extent_use_refcount(0),
next_in_free_list(-1) {}
};
class extent_zone_t {
int64_t start;
const size_t extent_size;
unsigned int offset_to_id(int64_t extent) {
rassert(extent >= start);
rassert(divides(extent_size, extent));
return (extent - start) / extent_size;
}
/* Combination free-list and extent map. Contains one entry per extent.
During the state_reserving_extents phase, each extent has state state_unreserved
or state state_in_use. When we transition to the state_running phase,
we link all of the state_unreserved entries in each zone together into an
extent free list, such that each free entry's 'next_in_free_list' field is the
offset of the next free extent. */
segmented_vector_t<extent_info_t, MAX_DATA_EXTENTS> extents;
int64_t free_list_head;
private:
int held_extents_;
public:
int held_extents() const {
return held_extents_;
}
public:
extent_zone_t(int64_t _start, size_t _extent_size)
: start(_start), extent_size(_extent_size), held_extents_(0)
{
rassert(divides(extent_size, start));
}
void reserve_extent(int64_t extent, extent_reference_t *extent_ref_out) {
unsigned int id = offset_to_id(extent);
if (id >= extents.get_size()) {
extent_info_t default_info;
extents.set_size(id + 1, default_info);
}
rassert(extents[id].state() == extent_info_t::state_unreserved);
extents[id].set_state(extent_info_t::state_in_use);
make_extent_reference(extent, extent_ref_out);
}
void reconstruct_free_list() {
free_list_head = NULL_OFFSET;
for (int64_t extent = start;
extent < start + static_cast<int64_t>(extents.get_size() * extent_size);
extent += extent_size) {
if (extents[offset_to_id(extent)].state() == extent_info_t::state_unreserved) {
extents[offset_to_id(extent)].set_state(extent_info_t::state_free);
extents[offset_to_id(extent)].next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
}
bool gen_extent(extent_reference_t *extent_ref_out) {
int64_t extent;
if (free_list_head == NULL_OFFSET) {
extent = start + extents.get_size() * extent_size;
extents.set_size(extents.get_size() + 1);
} else {
extent = free_list_head;
free_list_head = extents[offset_to_id(free_list_head)].next_in_free_list;
held_extents_--;
}
extent_info_t *info = &extents[offset_to_id(extent)];
info->set_state(extent_info_t::state_in_use);
make_extent_reference(extent, extent_ref_out);
return true;
}
void make_extent_reference(int64_t extent, extent_reference_t *extent_ref_out) {
unsigned int id = offset_to_id(extent);
guarantee(id < extents.get_size());
extent_info_t *info = &extents[id];
guarantee(info->state() == extent_info_t::state_in_use);
++info->extent_use_refcount;
extent_ref_out->init(extent);
}
void release_extent(extent_reference_t *extent_ref) {
int64_t extent = extent_ref->release();
extent_info_t *info = &extents[offset_to_id(extent)];
guarantee(info->state() == extent_info_t::state_in_use);
guarantee(info->extent_use_refcount > 0);
--info->extent_use_refcount;
if (info->extent_use_refcount == 0) {
info->set_state(extent_info_t::state_free);
info->next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
};
extent_manager_t::extent_manager_t(file_t *file,
const log_serializer_on_disk_static_config_t *static_config,
log_serializer_stats_t *_stats)
: stats(_stats), extent_size(static_config->extent_size()),
dbfile(file), state(state_reserving_extents) {
stats->pm_extent_size += extent_size;
guarantee(divides(DEVICE_BLOCK_SIZE, extent_size));
zone.init(new extent_zone_t(0, extent_size));
}
extent_manager_t::~extent_manager_t() {
rassert(state == state_reserving_extents || state == state_shut_down);
}
void extent_manager_t::reserve_extent(int64_t extent, extent_reference_t *extent_ref) {
assert_thread();
rassert(state == state_reserving_extents);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
zone->reserve_extent(extent, extent_ref);
}
void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) {
mb->padding = 0;
}
void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) {
assert_thread();
rassert(state == state_reserving_extents);
current_transaction = NULL;
zone->reconstruct_free_list();
state = state_running;
}
void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert_thread();
rassert(state == state_running);
metablock->padding = 0;
}
void extent_manager_t::shutdown() {
assert_thread();
rassert(state == state_running);
rassert(!current_transaction);
state = state_shut_down;
}
void extent_manager_t::begin_transaction(extent_transaction_t *out) {
assert_thread();
rassert(!current_transaction);
current_transaction = out;
out->init();
}
void extent_manager_t::gen_extent(extent_reference_t *extent_ref_out) {
assert_thread();
rassert(state == state_running);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
extent_reference_t extent_ref;
// RSI: Can gen_extent even fail anymore? We only have one zone.
if (!zone->gen_extent(&extent_ref)) {
/* We tried every zone and there were no free extents */
crash("RethinkDB ran out of disk space.");
}
/* In case we are not on a block device */
dbfile->set_size_at_least(extent_ref.offset() + extent_size);
extent_ref_out->init(extent_ref.release());
}
void extent_manager_t::copy_extent_reference(extent_reference_t *extent_ref, extent_reference_t *extent_ref_out) {
int64_t offset = extent_ref->offset();
zone->make_extent_reference(offset, extent_ref_out);
}
void extent_manager_t::release_extent_into_transaction(extent_reference_t *extent_ref, extent_transaction_t *txn) {
release_extent_preliminaries();
rassert(current_transaction);
txn->push_extent(extent_ref);
}
void extent_manager_t::release_extent(extent_reference_t *extent_ref) {
release_extent_preliminaries();
zone->release_extent(extent_ref);
}
void extent_manager_t::release_extent_preliminaries() {
assert_thread();
rassert(state == state_running);
--stats->pm_extents_in_use;
stats->pm_bytes_in_use -= extent_size;
}
void extent_manager_t::end_transaction(extent_transaction_t *t) {
assert_thread();
rassert(current_transaction == t);
current_transaction = NULL;
t->mark_end();
}
void extent_manager_t::commit_transaction(extent_transaction_t *t) {
assert_thread();
std::deque<int64_t> extents;
t->reset(&extents);
for (std::deque<int64_t>::const_iterator it = extents.begin(); it != extents.end(); ++it) {
extent_reference_t extent_ref;
extent_ref.init(*it);
zone->release_extent(&extent_ref);
}
}
int extent_manager_t::held_extents() {
assert_thread();
return zone->held_extents();
}
<commit_msg>Removed extent_zone_t::start.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/log/extent_manager.hpp"
#include "arch/arch.hpp"
#include "logger.hpp"
#include "perfmon/perfmon.hpp"
#include "serializer/log/log_serializer.hpp"
struct extent_info_t {
public:
enum state_t {
state_unreserved,
state_in_use,
state_free
};
private:
state_t state_;
public:
void set_state(state_t new_state) {
guarantee(state_ != state_in_use || extent_use_refcount == 0);
state_ = new_state;
}
state_t state() const { return state_; }
// Valid and non-zero when state_in_use. There are two ways to own a part of
// this refcount. One is if you believe you're currently "using" the extent (if
// you're the LBA or data_block_manager_t). The other is (at the time of
// writing) for every (extent_transaction_t, block_id) for live extent
// transactions that have set an i_array entry to zero (in the data block
// manager) but have not yet been commmitted. The data_block_manager_t and LBA
// ownership of the refcount also can get passed into the extent_transaction_t
// object.
int32_t extent_use_refcount;
int64_t next_in_free_list; // Valid if state == state_free
extent_info_t() : state_(state_unreserved),
extent_use_refcount(0),
next_in_free_list(-1) {}
};
class extent_zone_t {
const size_t extent_size;
unsigned int offset_to_id(int64_t extent) {
rassert(divides(extent_size, extent));
return extent / extent_size;
}
/* Combination free-list and extent map. Contains one entry per extent.
During the state_reserving_extents phase, each extent has state state_unreserved
or state state_in_use. When we transition to the state_running phase,
we link all of the state_unreserved entries in each zone together into an
extent free list, such that each free entry's 'next_in_free_list' field is the
offset of the next free extent. */
segmented_vector_t<extent_info_t, MAX_DATA_EXTENTS> extents;
int64_t free_list_head;
private:
int held_extents_;
public:
int held_extents() const {
return held_extents_;
}
public:
extent_zone_t(size_t _extent_size)
: extent_size(_extent_size), held_extents_(0) { }
void reserve_extent(int64_t extent, extent_reference_t *extent_ref_out) {
unsigned int id = offset_to_id(extent);
if (id >= extents.get_size()) {
extent_info_t default_info;
extents.set_size(id + 1, default_info);
}
rassert(extents[id].state() == extent_info_t::state_unreserved);
extents[id].set_state(extent_info_t::state_in_use);
make_extent_reference(extent, extent_ref_out);
}
void reconstruct_free_list() {
free_list_head = NULL_OFFSET;
for (int64_t extent = 0;
extent < static_cast<int64_t>(extents.get_size() * extent_size);
extent += extent_size) {
if (extents[offset_to_id(extent)].state() == extent_info_t::state_unreserved) {
extents[offset_to_id(extent)].set_state(extent_info_t::state_free);
extents[offset_to_id(extent)].next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
}
bool gen_extent(extent_reference_t *extent_ref_out) {
int64_t extent;
if (free_list_head == NULL_OFFSET) {
extent = extents.get_size() * extent_size;
extents.set_size(extents.get_size() + 1);
} else {
extent = free_list_head;
free_list_head = extents[offset_to_id(free_list_head)].next_in_free_list;
held_extents_--;
}
extent_info_t *info = &extents[offset_to_id(extent)];
info->set_state(extent_info_t::state_in_use);
make_extent_reference(extent, extent_ref_out);
return true;
}
void make_extent_reference(int64_t extent, extent_reference_t *extent_ref_out) {
unsigned int id = offset_to_id(extent);
guarantee(id < extents.get_size());
extent_info_t *info = &extents[id];
guarantee(info->state() == extent_info_t::state_in_use);
++info->extent_use_refcount;
extent_ref_out->init(extent);
}
void release_extent(extent_reference_t *extent_ref) {
int64_t extent = extent_ref->release();
extent_info_t *info = &extents[offset_to_id(extent)];
guarantee(info->state() == extent_info_t::state_in_use);
guarantee(info->extent_use_refcount > 0);
--info->extent_use_refcount;
if (info->extent_use_refcount == 0) {
info->set_state(extent_info_t::state_free);
info->next_in_free_list = free_list_head;
free_list_head = extent;
held_extents_++;
}
}
};
extent_manager_t::extent_manager_t(file_t *file,
const log_serializer_on_disk_static_config_t *static_config,
log_serializer_stats_t *_stats)
: stats(_stats), extent_size(static_config->extent_size()),
dbfile(file), state(state_reserving_extents) {
stats->pm_extent_size += extent_size;
guarantee(divides(DEVICE_BLOCK_SIZE, extent_size));
zone.init(new extent_zone_t(extent_size));
}
extent_manager_t::~extent_manager_t() {
rassert(state == state_reserving_extents || state == state_shut_down);
}
void extent_manager_t::reserve_extent(int64_t extent, extent_reference_t *extent_ref) {
assert_thread();
rassert(state == state_reserving_extents);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
zone->reserve_extent(extent, extent_ref);
}
void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) {
mb->padding = 0;
}
void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) {
assert_thread();
rassert(state == state_reserving_extents);
current_transaction = NULL;
zone->reconstruct_free_list();
state = state_running;
}
void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) {
assert_thread();
rassert(state == state_running);
metablock->padding = 0;
}
void extent_manager_t::shutdown() {
assert_thread();
rassert(state == state_running);
rassert(!current_transaction);
state = state_shut_down;
}
void extent_manager_t::begin_transaction(extent_transaction_t *out) {
assert_thread();
rassert(!current_transaction);
current_transaction = out;
out->init();
}
void extent_manager_t::gen_extent(extent_reference_t *extent_ref_out) {
assert_thread();
rassert(state == state_running);
++stats->pm_extents_in_use;
stats->pm_bytes_in_use += extent_size;
extent_reference_t extent_ref;
// RSI: Can gen_extent even fail anymore? We only have one zone.
if (!zone->gen_extent(&extent_ref)) {
/* We tried every zone and there were no free extents */
crash("RethinkDB ran out of disk space.");
}
/* In case we are not on a block device */
dbfile->set_size_at_least(extent_ref.offset() + extent_size);
extent_ref_out->init(extent_ref.release());
}
void extent_manager_t::copy_extent_reference(extent_reference_t *extent_ref, extent_reference_t *extent_ref_out) {
int64_t offset = extent_ref->offset();
zone->make_extent_reference(offset, extent_ref_out);
}
void extent_manager_t::release_extent_into_transaction(extent_reference_t *extent_ref, extent_transaction_t *txn) {
release_extent_preliminaries();
rassert(current_transaction);
txn->push_extent(extent_ref);
}
void extent_manager_t::release_extent(extent_reference_t *extent_ref) {
release_extent_preliminaries();
zone->release_extent(extent_ref);
}
void extent_manager_t::release_extent_preliminaries() {
assert_thread();
rassert(state == state_running);
--stats->pm_extents_in_use;
stats->pm_bytes_in_use -= extent_size;
}
void extent_manager_t::end_transaction(extent_transaction_t *t) {
assert_thread();
rassert(current_transaction == t);
current_transaction = NULL;
t->mark_end();
}
void extent_manager_t::commit_transaction(extent_transaction_t *t) {
assert_thread();
std::deque<int64_t> extents;
t->reset(&extents);
for (std::deque<int64_t>::const_iterator it = extents.begin(); it != extents.end(); ++it) {
extent_reference_t extent_ref;
extent_ref.init(*it);
zone->release_extent(&extent_ref);
}
}
int extent_manager_t::held_extents() {
assert_thread();
return zone->held_extents();
}
<|endoftext|> |
<commit_before>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2006 Serious Hack Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; 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 "BaseTexture.hpp"
namespace SH {
BaseTexture::BaseTexture(const TextureNodePtr& node)
: MetaForwarder(node.object()),
m_node(node)
{
for (int i = 0; i < 3; ++i) {
m_stride[i] = 1;
m_repeat[i] = 1;
m_offset[i] = 0;
}
m_count[0] = node->width();
m_count[1] = node->height();
m_count[2] = node->depth();
}
void BaseTexture::get_offset(int* offset, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
offset[i] = m_offset[i];
}
void BaseTexture::get_stride(int* stride, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
stride[i] = m_stride[i];
}
void BaseTexture::get_count(int* count, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
count[i] = m_count[i];
}
void BaseTexture::get_repeat(int* repeat, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
repeat[i] = m_repeat[i];
}
void BaseTexture::set_offset(const int* offset, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_offset[i] = offset[i];
}
void BaseTexture::set_stride(const int* stride, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_stride[i] = stride[i];
}
void BaseTexture::set_count(const int* count, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_count[i] = count[i];
}
void BaseTexture::set_repeat(const int* repeat, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_repeat[i] = repeat[i];
}
void* BaseTexture::read_data(int n) const
{
StoragePtr storage = m_node->memory(n)->findStorage("host");
if (!storage) error(Exception("No host storage found"));
HostStoragePtr host_storage = shref_dynamic_cast<HostStorage>(storage);
SH_DEBUG_ASSERT(host_storage);
host_storage->sync();
return host_storage->data();
}
void* BaseTexture::write_data(int n)
{
StoragePtr storage = m_node->memory(n)->findStorage("host");
if (!storage) error(Exception("No host storage found"));
HostStoragePtr host_storage = shref_dynamic_cast<HostStorage>(storage);
SH_DEBUG_ASSERT(host_storage);
host_storage->dirty();
return host_storage->data();
}
}
<commit_msg>Make read_data and write_data look for up to date storages to save a sync<commit_after>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2006 Serious Hack Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; 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 "BaseTexture.hpp"
namespace {
struct StorageUpToDate : std::binary_function<SH::StoragePtr, SH::MemoryPtr, bool> {
bool operator()(const SH::StoragePtr& storage, const SH::MemoryPtr& memory) const {
return (storage->timestamp() == memory->timestamp());
}
};
SH::HostStoragePtr find_storage(const SH::MemoryPtr& mem)
{
SH::StoragePtr storage = mem->findStorage("host", std::bind2nd(StorageUpToDate(), mem));
if (!storage) {
storage = mem->findStorage("host");
}
if (!storage) {
SH::error(SH::Exception("No host storage found"));
}
return SH::shref_dynamic_cast<SH::HostStorage>(storage);
}
}
namespace SH {
BaseTexture::BaseTexture(const TextureNodePtr& node)
: MetaForwarder(node.object()),
m_node(node)
{
for (int i = 0; i < 3; ++i) {
m_stride[i] = 1;
m_repeat[i] = 1;
m_offset[i] = 0;
}
m_count[0] = node->width();
m_count[1] = node->height();
m_count[2] = node->depth();
}
void BaseTexture::get_offset(int* offset, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
offset[i] = m_offset[i];
}
void BaseTexture::get_stride(int* stride, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
stride[i] = m_stride[i];
}
void BaseTexture::get_count(int* count, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
count[i] = m_count[i];
}
void BaseTexture::get_repeat(int* repeat, int n) const
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
repeat[i] = m_repeat[i];
}
void BaseTexture::set_offset(const int* offset, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_offset[i] = offset[i];
}
void BaseTexture::set_stride(const int* stride, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_stride[i] = stride[i];
}
void BaseTexture::set_count(const int* count, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_count[i] = count[i];
}
void BaseTexture::set_repeat(const int* repeat, int n)
{
SH_DEBUG_ASSERT(n <= 3);
for (int i = 0; i < n; ++i)
m_repeat[i] = repeat[i];
}
void* BaseTexture::read_data(int n) const
{
HostStoragePtr host_storage = find_storage(m_node->memory(n));
SH_DEBUG_ASSERT(host_storage);
host_storage->sync();
return host_storage->data();
}
void* BaseTexture::write_data(int n)
{
HostStoragePtr host_storage = find_storage(m_node->memory(n));
SH_DEBUG_ASSERT(host_storage);
host_storage->dirty();
return host_storage->data();
}
}
<|endoftext|> |
<commit_before>#define OVERRIDE_MATRIX_MULT true
#include "../lib/matrix.hpp"
#include "../lib/pool.hpp"
/* 1a */
matrix operator*(const matrix &x, const matrix &y) {
if (x.cols != y.rows) {
throw std::invalid_argument("Invalid arguments");
}
matrix z;
z.create(x.rows, y.cols);
parallel_for(0u, x.rows * y.cols, [&](int k) {
unsigned i = k / y.cols, j = k % y.cols;
int zz = 0;
for (unsigned k = 0; k < x.cols; k++) {
zz += x(i, k) * y(k, j);
}
z(i, j) = zz;
});
return z;
}
/*
* 2. parallel_for uses the queue_work function instead of create_thread.
* a. Why?
* - Parallel for loops are typically used in data problems which require the
* - computation of some value over a loop. As such, these are often short lived
* - and cause blocks in control flow. To mitigate the delay and increase the
* - benefit of using parallel_for, the work is pushed into the pool so that thread
* - creation is not experienced (which takes time), additionally, since the computation
* - is most likely computationally expensive, the pool will only schedule the work
* - when threads are available instead of maxing out the system and causing system lag.
*
* b. Give an example of when should you use create_thread instead of queue_work
* to execute work asynchronously?
* - Create thread should always be used for work which is *long running* or blocking.
* - Reason being is that long running work (or threads which will be alive the entire
* - program life) will utilize all the threads provisioned to the pool and will cease
* - execution of other work (e.g. a worker thread that works on a concurrent queue).
* - Knowing this, simply spawn a new thread!
*/
/* 3 */
//Consider the following program
int mainEx() {
int value = 32;
queue_work([&] {
value -= 17;
printf("%d\n", value);
});
return value;
}
/*
* 3a. What is the result of this program? (Hint: its not always the same).
* - The result of this program varies depending on how quickly the queued
* - works starts in relation to the execution of the remaining code (pop stack
* - [removing queue_work return], push `value`, and return stack[0]/int).
*
* Possible results:
* 1. mainEx returns 32
* 2. mainEx returns 15
* 3. mainEx returns 15 and prints 15
*/
/* 3b */
int mainExFixed() {
int value = 32;
auto f = queue_work([&] {
value -= 17;
printf("%d\n", value);
});
f.wait();
return value;
}
int main(int argc, char **argv) {
return 0;
}
<commit_msg>Answer 5a<commit_after>#define OVERRIDE_MATRIX_MULT true
#include "../lib/matrix.hpp"
#include "../lib/pool.hpp"
/* 1a */
matrix operator*(const matrix &x, const matrix &y) {
if (x.cols != y.rows) {
throw std::invalid_argument("Invalid arguments");
}
matrix z;
z.create(x.rows, y.cols);
parallel_for(0u, x.rows * y.cols, [&](int k) {
unsigned i = k / y.cols, j = k % y.cols;
int zz = 0;
for (unsigned k = 0; k < x.cols; k++) {
zz += x(i, k) * y(k, j);
}
z(i, j) = zz;
});
return z;
}
/*
* 2. parallel_for uses the queue_work function instead of create_thread.
* a. Why?
* - Parallel for loops are typically used in data problems which require the
* - computation of some value over a loop. As such, these are often short lived
* - and cause blocks in control flow. To mitigate the delay and increase the
* - benefit of using parallel_for, the work is pushed into the pool so that thread
* - creation is not experienced (which takes time), additionally, since the computation
* - is most likely computationally expensive, the pool will only schedule the work
* - when threads are available instead of maxing out the system and causing system lag.
*
* b. Give an example of when should you use create_thread instead of queue_work
* to execute work asynchronously?
* - Create thread should always be used for work which is *long running* or blocking.
* - Reason being is that long running work (or threads which will be alive the entire
* - program life) will utilize all the threads provisioned to the pool and will cease
* - execution of other work (e.g. a worker thread that works on a concurrent queue).
* - Knowing this, simply spawn a new thread!
*/
/* 3 */
//Consider the following program
int mainEx() {
int value = 32;
queue_work([&] {
value -= 17;
printf("%d\n", value);
});
return value;
}
/*
* 3a. What is the result of this program? (Hint: its not always the same).
* - The result of this program varies depending on how quickly the queued
* - works starts in relation to the execution of the remaining code (pop stack
* - [removing queue_work return], push `value`, and return stack[0]/int).
*
* Possible results:
* 1. mainEx returns 32
* 2. mainEx returns 15
* 3. mainEx returns 15 and prints 15
*/
/* 3b - Correct the defect. */
int mainExFixed() {
int value = 32;
auto f = queue_work([&] {
value -= 17;
printf("%d\n", value);
});
f.wait();
return value;
}
/*
* 5a. How does a semaphore differ from mutex?
* - A semaphore differs from a mutex in that it is not a mutual exclusion lock,
* - a semaphore, unlike a mutex, can be aquired multiple times (depending on how
* - the sempahore is created) unlike a mutex which is strictly locked or unlocked.
* - Additionally, a semaphore lives in the file system and is not restrictied to the
* - process in which it was created (like a mutex), which makes it useful to lock
* - access to things like shared memory pools across processes.
*
* 5b. Describe the operation of a bar (sitting down, ordering a drink) in terms
* of a semaphore and mutex.
*/
int main(int argc, char **argv) {
return 0;
}
<|endoftext|> |
<commit_before>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/pca/pca.hpp
*
* Copyright 2017 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef PCA_HPP_
#define PCA_HPP_
#include "eos/morphablemodel/PcaModel.hpp"
#include "Eigen/Core"
#include "Eigen/Eigenvalues"
#include <array>
#include <vector>
#include <utility>
#include <cassert>
namespace eos {
namespace pca {
/**
* A flag specifying how to compute the covariance matrix in the PCA.
*/
enum class Covariance {
AtA, ///< Compute the traditional covariance matrix A^t*A.
AAt ///< Use the inner product, A*A^t, for the covariance matrix.
};
/**
* @brief Compute PCA on a mean-centred data matrix, and return the eigenvectors and respective eigenvalues.
*
* Computes PCA (principal component analysis) on the given mean-centred data matrix. Note that you
* should subtract the mean from the data beforehand, this function will not do so.
* The function computes PCA based on an eigendecomposition of the covariance matrix.
* If the dimensionality of the data is high, the PCA can be computed on the inner-product matrix
* A*A^t instead of the covariance matrix A^t*A by setting the flag \c Covariance::AAt.
*
* The function returns n-1 eigenvectors and eigenvalues, where n is the number of data samples given.
* The eigenvectors and eigenvalues are returned in descending order, with the largest (most significant)
* first.
*
* Note: Changing the \p covariance_type may return eigenvectors with different signs, but otherwise equivalent.
* This is completely fine as the sign of eigenvectors is arbitrary anyway.
*
*
* Developer notes:
* If you want to avoid a copy: myarray = np.array(source, order='F') (this will change
* the numpy array to colmajor, so Eigen can directly accept it.
* There is other ways how to avoid copies:
* See: https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html.
* http://pybind11.readthedocs.io/en/master/advanced/cast/eigen.html
* Also it would be nice if the function could accept any Eigen matrix types (e.g. a MatrixXf or MatrixXd).
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data, Covariance covariance_type = Covariance::AtA)
{
using Eigen::VectorXf;
using Eigen::MatrixXf;
MatrixXf cov;
if (covariance_type == Covariance::AtA)
{
cov = data.adjoint() * data;
}
else if (covariance_type == Covariance::AAt)
{
cov = data * data.adjoint();
}
// The covariance is 1/(n-1) * AtA (or AAt), so divide by (num_samples - 1):
cov /= (data.rows() - 1);
const Eigen::SelfAdjointEigenSolver<MatrixXf> eig(cov);
const int num_eigenvectors_to_keep = data.rows() - 1;
// Select the eigenvectors and eigenvalues that we want to keep, reverse them (from most significant to least):
// For 'n' data points, we get at most 'n - 1' non-zero eigenvalues.
VectorXf eigenvalues = eig.eigenvalues().bottomRows(num_eigenvectors_to_keep).reverse(); // eigenvalues() returns a column-vec
MatrixXf eigenvectors = eig.eigenvectors().rightCols(num_eigenvectors_to_keep).rowwise().reverse();
if (covariance_type == Covariance::AAt)
{
// Bring the AA^t variant in the right form by multiplying with A^t and 1/sqrt(eval):
// (see e.g. https://math.stackexchange.com/questions/787822/how-do-covariance-matrix-c-aat-justify-the-actual-ata-in-pca)
// (note the signs might be different from the AtA solution but that's not a problem as the sign of eigenvectors are arbitrary anyway)
eigenvectors = data.adjoint() * eigenvectors;
// Multiply each eigenvector (column) with one over the square root of its respective eigenvalue (1/sqrt(eigenvalue(i))):
// (this is a neat short-hand notation, see https://stackoverflow.com/a/42945996/1345959).
const VectorXf one_over_sqrt_eigenvalues = eigenvalues.array().rsqrt();
eigenvectors *= one_over_sqrt_eigenvalues.asDiagonal();
// Compensate for the covariance division by (n - 1) above:
eigenvectors /= std::sqrt(data.rows() - 1);
}
return { eigenvectors, eigenvalues };
};
/**
* @brief Performs PCA and returns \p num_eigenvectors_to_keep eigenvectors and eigenvalues.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance).
*
* \p num_eigenvectors_to_keep needs to be smaller or equal to n-1, where n is number of rows of data (i.e. number of data samples).
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] num_eigenvectors_to_keep Specifies how many eigenvectors and eigenvalues to keep.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data, int num_eigenvectors_to_keep, Covariance covariance_type = Covariance::AtA)
{
using Eigen::VectorXf;
using Eigen::MatrixXf;
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(data, covariance_type);
// Reduce the basis and eigenvalues, and return:
assert(num_eigenvectors_to_keep <= eigenvectors.size());
return { eigenvectors.leftCols(num_eigenvectors_to_keep), eigenvalues.topRows(num_eigenvectors_to_keep) };
};
/**
* @brief Performs PCA and returns the number of eigenvectors and eigenvalues to retain \p variance_to_keep variance of the original data.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance).
*
* \p variance_to_keep needs to be between 0.0 and 1.0.
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] variance_to_keep Specifies how much of the variance to retain, in percent (between 0 and 1).
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data, float variance_to_keep, Covariance covariance_type = Covariance::AtA)
{
using Eigen::VectorXf;
using Eigen::MatrixXf;
assert(variance_to_keep >= 0.0f && variance_to_keep <= 1.0f);
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(data, covariance_type);
// Figure out how many coeffs to keep:
// variance_explained_by_first_comp = eigenval(1)/sum(eigenvalues)
// variance_explained_by_second_comp = eigenval(2)/sum(eigenvalues), etc.
auto num_eigenvectors_to_keep = eigenvalues.size(); // In the "worst" case we return all eigenvectors.
const auto total_sum = eigenvalues.sum();
float cum_sum = 0.0f;
for (int i = 0; i < eigenvalues.size(); ++i) {
cum_sum += eigenvalues(i);
// If the current variation explained is larger or equal to the amount of variation that
// the user requested to keep, we're done:
if (cum_sum / total_sum >= variance_to_keep) {
num_eigenvectors_to_keep = i + 1;
break;
}
}
// Reduce the basis and eigenvalues, and return:
assert(num_eigenvectors_to_keep <= eigenvectors.size());
return { eigenvectors.leftCols(num_eigenvectors_to_keep), eigenvalues.topRows(num_eigenvectors_to_keep) };
};
/**
* @brief Performs PCA on the given data (including subtracting the mean) and returns the built PcaModel.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance) for the details on the PCA.
*
* \p data should be a (num_training_samples x num_data_dimensions) matrix, i.e. each row one data instance (e.g. one 3D scan).
*
* @param[in] data Data matrix (orignal, without the mean subtracted), with each row being a training sample.
* @param[in] triangle_list Triangle list to build the topology of the PcaModel mesh.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the inner-product matrix AAt.
* @return A PcaModel constructed from the given data.
*/
inline morphablemodel::PcaModel pca(const Eigen::Ref<const Eigen::MatrixXf> data, std::vector<std::array<int, 3>> triangle_list, Covariance covariance_type = Covariance::AtA)
{
using Eigen::VectorXf;
using Eigen::MatrixXf;
// Compute the mean and mean-free data matrix:
// Each row is one instance of data (e.g. a 3D scan)
const VectorXf mean = data.colwise().mean();
const MatrixXf meanfree_data = data.rowwise() - mean.transpose();
// Carry out PCA and return the constructed model:
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(meanfree_data, covariance_type);
return morphablemodel::PcaModel(mean, eigenvectors, eigenvalues, triangle_list);
};
} /* namespace pca */
} /* namespace eos */
#endif /* PCA_HPP_ */
<commit_msg>Applied .clang-format to pca.hpp<commit_after>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/pca/pca.hpp
*
* Copyright 2017 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef PCA_HPP_
#define PCA_HPP_
#include "eos/morphablemodel/PcaModel.hpp"
#include "Eigen/Core"
#include "Eigen/Eigenvalues"
#include <array>
#include <cassert>
#include <utility>
#include <vector>
namespace eos {
namespace pca {
/**
* A flag specifying how to compute the covariance matrix in the PCA.
*/
enum class Covariance {
AtA, ///< Compute the traditional covariance matrix A^t*A.
AAt ///< Use the inner product, A*A^t, for the covariance matrix.
};
/**
* @brief Compute PCA on a mean-centred data matrix, and return the eigenvectors and respective eigenvalues.
*
* Computes PCA (principal component analysis) on the given mean-centred data matrix. Note that you
* should subtract the mean from the data beforehand, this function will not do so.
* The function computes PCA based on an eigendecomposition of the covariance matrix.
* If the dimensionality of the data is high, the PCA can be computed on the inner-product matrix
* A*A^t instead of the covariance matrix A^t*A by setting the flag \c Covariance::AAt.
*
* The function returns n-1 eigenvectors and eigenvalues, where n is the number of data samples given.
* The eigenvectors and eigenvalues are returned in descending order, with the largest (most significant)
* first.
*
* Note: Changing the \p covariance_type may return eigenvectors with different signs, but otherwise
* equivalent. This is completely fine as the sign of eigenvectors is arbitrary anyway.
*
*
* Developer notes:
* If you want to avoid a copy: myarray = np.array(source, order='F') (this will change
* the numpy array to colmajor, so Eigen can directly accept it.
* There is other ways how to avoid copies:
* See: https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html.
* http://pybind11.readthedocs.io/en/master/advanced/cast/eigen.html
* Also it would be nice if the function could accept any Eigen matrix types (e.g. a MatrixXf or MatrixXd).
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
MatrixXf cov;
if (covariance_type == Covariance::AtA)
{
cov = data.adjoint() * data;
} else if (covariance_type == Covariance::AAt)
{
cov = data * data.adjoint();
}
// The covariance is 1/(n-1) * AtA (or AAt), so divide by (num_samples - 1):
cov /= (data.rows() - 1);
const Eigen::SelfAdjointEigenSolver<MatrixXf> eig(cov);
const int num_eigenvectors_to_keep = data.rows() - 1;
// Select the eigenvectors and eigenvalues that we want to keep, reverse them (from most significant to
// least): For 'n' data points, we get at most 'n - 1' non-zero eigenvalues.
VectorXf eigenvalues = eig.eigenvalues()
.bottomRows(num_eigenvectors_to_keep)
.reverse(); // eigenvalues() returns a column-vec
MatrixXf eigenvectors = eig.eigenvectors().rightCols(num_eigenvectors_to_keep).rowwise().reverse();
if (covariance_type == Covariance::AAt)
{
// Bring the AA^t variant in the right form by multiplying with A^t and 1/sqrt(eval):
// (see e.g. https://math.stackexchange.com/questions/787822/how-do-covariance-matrix-c-aat-justify-the-actual-ata-in-pca)
// (note the signs might be different from the AtA solution but that's not a problem as the sign of
// eigenvectors are arbitrary anyway)
eigenvectors = data.adjoint() * eigenvectors;
// Multiply each eigenvector (column) with one over the square root of its respective eigenvalue
// (1/sqrt(eigenvalue(i))): (this is a neat short-hand notation, see
// https://stackoverflow.com/a/42945996/1345959).
const VectorXf one_over_sqrt_eigenvalues = eigenvalues.array().rsqrt();
eigenvectors *= one_over_sqrt_eigenvalues.asDiagonal();
// Compensate for the covariance division by (n - 1) above:
eigenvectors /= std::sqrt(data.rows() - 1);
}
return { eigenvectors, eigenvalues };
};
/**
* @brief Performs PCA and returns \p num_eigenvectors_to_keep eigenvectors and eigenvalues.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance).
*
* \p num_eigenvectors_to_keep needs to be smaller or equal to n-1, where n is number of rows of data (i.e.
* number of data samples).
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] num_eigenvectors_to_keep Specifies how many eigenvectors and eigenvalues to keep.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data,
int num_eigenvectors_to_keep,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(data, covariance_type);
// Reduce the basis and eigenvalues, and return:
assert(num_eigenvectors_to_keep <= eigenvectors.size());
return { eigenvectors.leftCols(num_eigenvectors_to_keep), eigenvalues.topRows(num_eigenvectors_to_keep) };
};
/**
* @brief Performs PCA and returns the number of eigenvectors and eigenvalues to retain \p variance_to_keep
* variance of the original data.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance).
*
* \p variance_to_keep needs to be between 0.0 and 1.0.
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] variance_to_keep Specifies how much of the variance to retain, in percent (between 0 and 1).
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data,
float variance_to_keep,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
assert(variance_to_keep >= 0.0f && variance_to_keep <= 1.0f);
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(data, covariance_type);
// Figure out how many coeffs to keep:
// variance_explained_by_first_comp = eigenval(1)/sum(eigenvalues)
// variance_explained_by_second_comp = eigenval(2)/sum(eigenvalues), etc.
auto num_eigenvectors_to_keep = eigenvalues.size(); // In the "worst" case we return all eigenvectors.
const auto total_sum = eigenvalues.sum();
float cum_sum = 0.0f;
for (int i = 0; i < eigenvalues.size(); ++i)
{
cum_sum += eigenvalues(i);
// If the current variation explained is larger or equal to the amount of variation that
// the user requested to keep, we're done:
if (cum_sum / total_sum >= variance_to_keep)
{
num_eigenvectors_to_keep = i + 1;
break;
}
}
// Reduce the basis and eigenvalues, and return:
assert(num_eigenvectors_to_keep <= eigenvectors.size());
return { eigenvectors.leftCols(num_eigenvectors_to_keep), eigenvalues.topRows(num_eigenvectors_to_keep) };
};
/**
* @brief Performs PCA on the given data (including subtracting the mean) and returns the built PcaModel.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance)
* for the details on the PCA.
*
* \p data should be a (num_training_samples x num_data_dimensions) matrix, i.e. each row one data instance
* (e.g. one 3D scan).
*
* @param[in] data Data matrix (orignal, without the mean subtracted), with each row being a training sample.
* @param[in] triangle_list Triangle list to build the topology of the PcaModel mesh.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A PcaModel constructed from the given data.
*/
inline morphablemodel::PcaModel pca(const Eigen::Ref<const Eigen::MatrixXf> data,
std::vector<std::array<int, 3>> triangle_list,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
// Compute the mean and mean-free data matrix:
// Each row is one instance of data (e.g. a 3D scan)
const VectorXf mean = data.colwise().mean();
const MatrixXf meanfree_data = data.rowwise() - mean.transpose();
// Carry out PCA and return the constructed model:
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(meanfree_data, covariance_type);
return morphablemodel::PcaModel(mean, eigenvectors, eigenvalues, triangle_list);
};
} /* namespace pca */
} /* namespace eos */
#endif /* PCA_HPP_ */
<|endoftext|> |
<commit_before>/*
*
* Author: Jeffrey Leung
* Last edited: 2016-03-24
*
* This C++ header file contains the definition of the exception logger
* class Exceptional and its methods, as well as functions which can be
* used to log exceptions with.
*
*/
#pragma once
#include <execinfo.h>
#include <cstring>
#include <ctime>
#include <exception>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <typeinfo>
#include <vector>
// For type demangling when using g++
#ifdef __GNUG__
#include <cxxabi.h>
#endif
namespace // Unnamed namespace for local functions/classes
{
// Local functions:
// This local function returns the current time as a string, formatted in
// the ISO 8601 standard.
std::string GetTime();
// This local function returns the current time as a string, formatted in
// the ISO 8601 standard.
std::string GetTime()
{
time_t raw_time;
time( &raw_time );
char buffer[ sizeof("1970-01-01T00:00:00") ];
strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", localtime(&raw_time));
return buffer;
}
// Local classes:
class Logger
{
public:
// Default constructor
Logger();
// Parameterized constructor (string filename)
Logger( const std::string filename );
// Parameterized constructor (output stream)
Logger( std::ostream& os );
// Destructor
~Logger();
// This public method logs a thrown std::exception as a warning.
void LogWarning( const std::exception& except );
// This public method logs a thrown value as a warning.
template <class T>
void LogWarning( const T& except );
// This public method logs a thrown std::exception as an error.
void LogError( const std::exception& except );
// This public method logs a thrown value as an error.
template <class T>
void LogError( const T& except );
private:
const std::string log_filename_default_ = "captains.log";
std::ofstream log_stream_default_file_;
std::ostream& log_stream_;
size_t warning_count_ = 0;
size_t error_count_ = 0;
static constexpr size_t kStackBacktraceLevel = 10;
enum class SeverityLevel
{
kWarning,
kError
};
// This private method logs the severity level of the exception.
void LogSeverityLevel( SeverityLevel sl );
// This private method logs the time of a thrown exception.
void LogTime();
// This private method logs the type of a thrown exception.
template <class T>
void LogExceptionType( const T& except );
// This private method demangles the type of a thrown exception
// if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::string DemangleType( const char* type_name );
// This private method logs the value of a thrown exception.
template <class T>
void LogExceptionValue( const T& except );
// This private method logs the message of an exception from std.
void LogExceptionMessage( const std::exception& except );
// This private method logs a stack backtrace.
void LogStackBacktrace();
// This private method returns backtraces of the current call stack.
// An exception is thrown if:
// backtrace_symbols returns an invalid set of
// function names (runtime_error)
std::vector<std::string> GetStackBacktrace();
// This private method demangles a stack backtrace if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::vector<std::string>
DemangleStackBacktrace( std::vector<std::string> stack_backtrace );
// This private method separates a single stack backtrace entry into
// the function, offset, and remainder.
//
// I.e.:
// Mangled: ./module(function+0x15c) [0x8048a6d]
// Interpretation: ./executable(function+offset)
//
// An exception is thrown if:
// The entry cannot be separated (invalid_argument)
std::tuple<std::string, std::string, std::string>
SeparateBacktraceEntry( std::string entry );
};
// Default constructor
Logger::Logger() :
log_stream_default_file_{},
log_stream_{log_stream_default_file_}
{
// Opens the file in append mode
// Executed on the ofstream object, not the ostream object
log_stream_default_file_.open( log_filename_default_, std::ios::app );
log_stream_
<< "________________________________________"
<< std::endl
<< std::endl
<< "LOG CREATED AT "
<< GetTime()
<< std::endl
<< std::endl;
}
// Parameterized constructor (string filename)
Logger::Logger( const std::string filename ) :
log_stream_default_file_{},
log_stream_{log_stream_default_file_}
{
// Opens the file in append mode
// Executed on the ofstream object, not the ostream object
log_stream_default_file_.open( filename, std::ios::app );
log_stream_
<< "________________________________________"
<< std::endl
<< std::endl
<< "LOG CREATED AT "
<< GetTime()
<< std::endl
<< std::endl;
}
// Parameterized constructor (output stream)
Logger::Logger( std::ostream& os ) :
log_stream_{os}
{
log_stream_
<< "________________________________________"
<< std::endl
<< std::endl
<< "LOG CREATED AT "
<< GetTime()
<< std::endl
<< std::endl;
}
// Destructor
Logger::~Logger()
{
log_stream_
<< "Warnings logged: "
<< warning_count_
<< std::endl
<< "Errors logged: "
<< error_count_
<< std::endl
<< std::endl;
// Executed on the ofstream object, not the ostream object
log_stream_default_file_.close();
}
// This public method logs a thrown std::exception as a warning.
void Logger::LogWarning( const std::exception& except )
{
++warning_count_;
LogSeverityLevel( SeverityLevel::kWarning );
LogTime();
LogExceptionType( except );
LogExceptionMessage( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This public method logs a thrown value as a warning.
template <class T>
void Logger::LogWarning( const T& except )
{
++warning_count_;
LogSeverityLevel( SeverityLevel::kWarning );
LogTime();
LogExceptionType( except );
LogExceptionValue( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This public method logs a thrown std::exception as an error.
void Logger::LogError( const std::exception& except )
{
++error_count_;
LogSeverityLevel( SeverityLevel::kError );
LogTime();
LogExceptionType( except );
LogExceptionMessage( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This public method logs a thrown value as an error.
template <class T>
void Logger::LogError( const T& except )
{
++error_count_;
LogSeverityLevel( SeverityLevel::kError );
LogTime();
LogExceptionType( except );
LogExceptionValue( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This private method logs the severity level of the exception.
void Logger::LogSeverityLevel( SeverityLevel sl )
{
std::string output;
switch( sl )
{
case SeverityLevel::kWarning:
output = "Warning:";
break;
case SeverityLevel::kError:
output = "Error:";
break;
}
log_stream_
<< output
<< std::endl;
}
// This private method logs the time of a thrown exception.
void Logger::LogTime()
{
log_stream_
<< "Logged at: "
<< GetTime()
<< std::endl;
}
// This private method logs the type of a thrown exception.
template <class T>
void Logger::LogExceptionType( const T& except )
{
const char* type_name = typeid(except).name();
if(type_name == nullptr)
{
log_stream_
<< "Type of exception value could not be detected."
<< std::endl;
}
else
{
try
{
log_stream_
<< "Type of exception value: "
<< DemangleType(type_name)
<< std::endl;
}
catch(...)
{
}
}
}
#ifdef __GNUG__ // Using g++
// This private method demangles the type of a thrown exception
// if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::string Logger::DemangleType( const char* type_name )
{
if( type_name == nullptr )
{
throw std::invalid_argument("Error: DemangleType() was given an invalid "\
"(null) pointer.\n");
}
int status = -1;
char* type_name_demangled =
abi::__cxa_demangle( type_name, NULL, NULL, &status );
if( status == 0 )
{
std::string demangled_string( type_name_demangled );
free( type_name_demangled );
return demangled_string;
}
else
{
return type_name;
}
}
#else
// This private method demangles the type of a thrown exception
// if g++ is used.
std::string Logger::DemangleType( const char* type_name )
{
return type_name;
}
#endif
// This private method logs the type of a thrown exception.
template <class T>
void Logger::LogExceptionValue( const T& except )
{
log_stream_
<< "Exception value: "
<< except
<< std::endl;
}
// This private method logs the message of an exception from std.
void Logger::LogExceptionMessage( const std::exception& except )
{
log_stream_
<< "Exception message: "
<< except.what();
std::string s = except.what();
if( s[s.length()-1] != '\n' )
{
log_stream_
<< std::endl;
}
}
// This private method logs a stack backtrace.
void Logger::LogStackBacktrace()
{
std::vector<std::string> stack_backtrace;
try
{
stack_backtrace = GetStackBacktrace();
}
catch (...)
{
return;
}
log_stream_
<< "Stack backtrace:"
<< std::endl;
for( auto i : stack_backtrace )
{
log_stream_
<< " "
<< i
<< std::endl;
}
}
// This private method returns backtraces of the current call stack.
// An exception is thrown if:
// backtrace_symbols returns an invalid set of
// function names (runtime_error)
std::vector<std::string> Logger::GetStackBacktrace()
{
void* address_buffer[kStackBacktraceLevel];
unsigned int address_count = backtrace(address_buffer, kStackBacktraceLevel);
char** function_names =
backtrace_symbols(address_buffer, address_count);
if(function_names == nullptr)
{
throw std::runtime_error("Error: GetStackBacktrace() failed to retrieve "\
"a set of function names.\n");
}
std::vector<std::string> stack_backtrace;
for(size_t i = 0; i < address_count; ++i)
{
stack_backtrace.push_back(function_names[i]);
}
free(function_names);
return stack_backtrace;
}
#ifdef __GNUG__ // Using g++
// This private method demangles a stack backtrace if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::vector<std::string>
Logger::DemangleStackBacktrace( std::vector<std::string> stack_backtrace )
{
std::vector<std::string> stack_backtrace_demangled;
// Forms of a stack backtrace entry
// Mangled (original): ./module(function+0x15c) [0x8048a6d]
// Interpretation: ./executable(function+offset)
// Separated: executable function offset
// Demangled: executable : demangled_function_name + offset
for( auto i : stack_backtrace )
{
std::tuple<std::string, std::string, std::string> entry;
try
{
entry = SeparateBacktraceEntry( i );
}
catch( ... )
{
stack_backtrace_demangled.push_back( i );
continue;
}
std::string executable = std::get<0>(entry);
std::string function = std::get<1>(entry);
std::string offset = std::get<2>(entry);
int status = -1;
char* func_demangled =
abi::__cxa_demangle( function.c_str(), NULL, NULL, &status );
if( status == 0 )
{
std::string demangled_string( func_demangled );
free( func_demangled );
std::string full_string
(
executable +
" : " +
demangled_string +
" + " +
offset
);
stack_backtrace_demangled.push_back( full_string );
}
else
{
stack_backtrace_demangled.push_back( i );
}
}
return stack_backtrace_demangled;
}
#else
// This private method demangles a stack backtrace if g++ is used.
std::vector<std::string>
Logger::DemangleStackBacktrace( std::vector<std::string> stack_backtrace )
{
return stack_backtrace;
}
#endif
// This private method separates a single stack backtrace entry into
// the function, offset, and remainder.
//
// I.e.:
// Mangled: ./module(function+0x15c) [0x8048a6d]
// Interpretation: ./executable(function+offset)
//
// An exception is thrown if:
// The entry cannot be separated (invalid_argument)
std::tuple<std::string, std::string, std::string>
Logger::SeparateBacktraceEntry( std::string entry )
{
std::string executable;
std::string function;
std::string offset;
size_t executable_begin = 2;
size_t func_begin = 0;
size_t offset_begin = 0;
size_t len = entry.length();
for( size_t i = 0; i < len; ++i )
{
if( entry.at(i) == '(' )
{
func_begin = i + 1;
size_t chars_to_copy = i - executable_begin;
executable = std::string(entry, executable_begin, chars_to_copy);
break;
}
}
for( size_t i = func_begin; i < len; ++i )
{
if( entry.at(i) == '+' )
{
offset_begin = i + 1;
size_t chars_to_copy = i - func_begin;
function = std::string(entry, func_begin, chars_to_copy);
break;
}
}
for( size_t i = offset_begin; i < len; ++i )
{
if( entry.at(i) == ')' )
{
size_t chars_to_copy = i - offset_begin;
offset = std::string(entry, offset_begin, chars_to_copy);
break;
}
}
if( executable.empty() || function.empty() || offset.empty() )
{
throw std::invalid_argument("Error: SeparateBacktraceEntry() was "\
"unable to parse the given entry.\n");
}
return make_tuple(executable, function, offset);
}
} // End of unnamed namespace (local to the file)
// Place loggers in here
namespace exceptional
{
Logger logger_default_file;
Logger logger_example_file("example_file.log");
Logger logger_cout(std::cout);
}
<commit_msg>Enabling stacktrace demangling for all logs<commit_after>/*
*
* Author: Jeffrey Leung
* Last edited: 2016-03-24
*
* This C++ header file contains the definition of the exception logger
* class Exceptional and its methods, as well as functions which can be
* used to log exceptions with.
*
*/
#pragma once
#include <execinfo.h>
#include <cstring>
#include <ctime>
#include <exception>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <typeinfo>
#include <vector>
// For type demangling when using g++
#ifdef __GNUG__
#include <cxxabi.h>
#endif
namespace // Unnamed namespace for local functions/classes
{
// Local functions:
// This local function returns the current time as a string, formatted in
// the ISO 8601 standard.
std::string GetTime();
// This local function returns the current time as a string, formatted in
// the ISO 8601 standard.
std::string GetTime()
{
time_t raw_time;
time( &raw_time );
char buffer[ sizeof("1970-01-01T00:00:00") ];
strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", localtime(&raw_time));
return buffer;
}
// Local classes:
class Logger
{
public:
// Default constructor
Logger();
// Parameterized constructor (string filename)
Logger( const std::string filename );
// Parameterized constructor (output stream)
Logger( std::ostream& os );
// Destructor
~Logger();
// This public method logs a thrown std::exception as a warning.
void LogWarning( const std::exception& except );
// This public method logs a thrown value as a warning.
template <class T>
void LogWarning( const T& except );
// This public method logs a thrown std::exception as an error.
void LogError( const std::exception& except );
// This public method logs a thrown value as an error.
template <class T>
void LogError( const T& except );
private:
const std::string log_filename_default_ = "captains.log";
std::ofstream log_stream_default_file_;
std::ostream& log_stream_;
size_t warning_count_ = 0;
size_t error_count_ = 0;
static constexpr size_t kStackBacktraceLevel = 10;
enum class SeverityLevel
{
kWarning,
kError
};
// This private method logs the severity level of the exception.
void LogSeverityLevel( SeverityLevel sl );
// This private method logs the time of a thrown exception.
void LogTime();
// This private method logs the type of a thrown exception.
template <class T>
void LogExceptionType( const T& except );
// This private method demangles the type of a thrown exception
// if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::string DemangleType( const char* type_name );
// This private method logs the value of a thrown exception.
template <class T>
void LogExceptionValue( const T& except );
// This private method logs the message of an exception from std.
void LogExceptionMessage( const std::exception& except );
// This private method logs a stack backtrace.
void LogStackBacktrace();
// This private method returns backtraces of the current call stack.
// An exception is thrown if:
// backtrace_symbols returns an invalid set of
// function names (runtime_error)
std::vector<std::string> GetStackBacktrace();
// This private method demangles a stack backtrace if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::vector<std::string>
DemangleStackBacktrace( std::vector<std::string> stack_backtrace );
// This private method separates a single stack backtrace entry into
// the function, offset, and remainder.
//
// I.e.:
// Mangled: ./module(function+0x15c) [0x8048a6d]
// Interpretation: ./executable(function+offset)
//
// An exception is thrown if:
// The entry cannot be separated (invalid_argument)
std::tuple<std::string, std::string, std::string>
SeparateBacktraceEntry( std::string entry );
};
// Default constructor
Logger::Logger() :
log_stream_default_file_{},
log_stream_{log_stream_default_file_}
{
// Opens the file in append mode
// Executed on the ofstream object, not the ostream object
log_stream_default_file_.open( log_filename_default_, std::ios::app );
log_stream_
<< "________________________________________"
<< std::endl
<< std::endl
<< "LOG CREATED AT "
<< GetTime()
<< std::endl
<< std::endl;
}
// Parameterized constructor (string filename)
Logger::Logger( const std::string filename ) :
log_stream_default_file_{},
log_stream_{log_stream_default_file_}
{
// Opens the file in append mode
// Executed on the ofstream object, not the ostream object
log_stream_default_file_.open( filename, std::ios::app );
log_stream_
<< "________________________________________"
<< std::endl
<< std::endl
<< "LOG CREATED AT "
<< GetTime()
<< std::endl
<< std::endl;
}
// Parameterized constructor (output stream)
Logger::Logger( std::ostream& os ) :
log_stream_{os}
{
log_stream_
<< "________________________________________"
<< std::endl
<< std::endl
<< "LOG CREATED AT "
<< GetTime()
<< std::endl
<< std::endl;
}
// Destructor
Logger::~Logger()
{
log_stream_
<< "Warnings logged: "
<< warning_count_
<< std::endl
<< "Errors logged: "
<< error_count_
<< std::endl
<< std::endl;
// Executed on the ofstream object, not the ostream object
log_stream_default_file_.close();
}
// This public method logs a thrown std::exception as a warning.
void Logger::LogWarning( const std::exception& except )
{
++warning_count_;
LogSeverityLevel( SeverityLevel::kWarning );
LogTime();
LogExceptionType( except );
LogExceptionMessage( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This public method logs a thrown value as a warning.
template <class T>
void Logger::LogWarning( const T& except )
{
++warning_count_;
LogSeverityLevel( SeverityLevel::kWarning );
LogTime();
LogExceptionType( except );
LogExceptionValue( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This public method logs a thrown std::exception as an error.
void Logger::LogError( const std::exception& except )
{
++error_count_;
LogSeverityLevel( SeverityLevel::kError );
LogTime();
LogExceptionType( except );
LogExceptionMessage( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This public method logs a thrown value as an error.
template <class T>
void Logger::LogError( const T& except )
{
++error_count_;
LogSeverityLevel( SeverityLevel::kError );
LogTime();
LogExceptionType( except );
LogExceptionValue( except );
LogStackBacktrace();
log_stream_ << std::endl;
}
// This private method logs the severity level of the exception.
void Logger::LogSeverityLevel( SeverityLevel sl )
{
std::string output;
switch( sl )
{
case SeverityLevel::kWarning:
output = "Warning:";
break;
case SeverityLevel::kError:
output = "Error:";
break;
}
log_stream_
<< output
<< std::endl;
}
// This private method logs the time of a thrown exception.
void Logger::LogTime()
{
log_stream_
<< "Logged at: "
<< GetTime()
<< std::endl;
}
// This private method logs the type of a thrown exception.
template <class T>
void Logger::LogExceptionType( const T& except )
{
const char* type_name = typeid(except).name();
if(type_name == nullptr)
{
log_stream_
<< "Type of exception value could not be detected."
<< std::endl;
}
else
{
try
{
log_stream_
<< "Type of exception value: "
<< DemangleType(type_name)
<< std::endl;
}
catch(...)
{
}
}
}
#ifdef __GNUG__ // Using g++
// This private method demangles the type of a thrown exception
// if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::string Logger::DemangleType( const char* type_name )
{
if( type_name == nullptr )
{
throw std::invalid_argument("Error: DemangleType() was given an invalid "\
"(null) pointer.\n");
}
int status = -1;
char* type_name_demangled =
abi::__cxa_demangle( type_name, NULL, NULL, &status );
if( status == 0 )
{
std::string demangled_string( type_name_demangled );
free( type_name_demangled );
return demangled_string;
}
else
{
return type_name;
}
}
#else
// This private method demangles the type of a thrown exception
// if g++ is used.
std::string Logger::DemangleType( const char* type_name )
{
return type_name;
}
#endif
// This private method logs the type of a thrown exception.
template <class T>
void Logger::LogExceptionValue( const T& except )
{
log_stream_
<< "Exception value: "
<< except
<< std::endl;
}
// This private method logs the message of an exception from std.
void Logger::LogExceptionMessage( const std::exception& except )
{
log_stream_
<< "Exception message: "
<< except.what();
std::string s = except.what();
if( s[s.length()-1] != '\n' )
{
log_stream_
<< std::endl;
}
}
// This private method logs a stack backtrace.
void Logger::LogStackBacktrace()
{
std::vector<std::string> stack_backtrace;
try
{
stack_backtrace = DemangleStackBacktrace(GetStackBacktrace());
}
catch (...)
{
return;
}
log_stream_
<< "Stack backtrace:"
<< std::endl;
for( auto i : stack_backtrace )
{
log_stream_
<< " "
<< i
<< std::endl;
}
}
// This private method returns backtraces of the current call stack.
// An exception is thrown if:
// backtrace_symbols returns an invalid set of
// function names (runtime_error)
std::vector<std::string> Logger::GetStackBacktrace()
{
void* address_buffer[kStackBacktraceLevel];
unsigned int address_count = backtrace(address_buffer, kStackBacktraceLevel);
char** function_names =
backtrace_symbols(address_buffer, address_count);
if(function_names == nullptr)
{
throw std::runtime_error("Error: GetStackBacktrace() failed to retrieve "\
"a set of function names.\n");
}
std::vector<std::string> stack_backtrace;
for(size_t i = 0; i < address_count; ++i)
{
stack_backtrace.push_back(function_names[i]);
}
free(function_names);
return stack_backtrace;
}
#ifdef __GNUG__ // Using g++
// This private method demangles a stack backtrace if g++ is used.
// An exception is thrown if:
// type_name is null (invalid_argument)
std::vector<std::string>
Logger::DemangleStackBacktrace( std::vector<std::string> stack_backtrace )
{
std::vector<std::string> stack_backtrace_demangled;
// Forms of a stack backtrace entry
// Mangled (original): ./module(function+0x15c) [0x8048a6d]
// Interpretation: ./executable(function+offset)
// Separated: executable function offset
// Demangled: executable : demangled_function_name + offset
for( auto i : stack_backtrace )
{
std::tuple<std::string, std::string, std::string> entry;
try
{
entry = SeparateBacktraceEntry( i );
}
catch( ... )
{
stack_backtrace_demangled.push_back( i );
continue;
}
std::string executable = std::get<0>(entry);
std::string function = std::get<1>(entry);
std::string offset = std::get<2>(entry);
int status = -1;
char* func_demangled =
abi::__cxa_demangle( function.c_str(), NULL, NULL, &status );
if( status == 0 )
{
std::string demangled_string( func_demangled );
free( func_demangled );
std::string full_string
(
executable +
" : " +
demangled_string +
" + " +
offset
);
stack_backtrace_demangled.push_back( full_string );
}
else
{
stack_backtrace_demangled.push_back( i );
}
}
return stack_backtrace_demangled;
}
#else
// This private method demangles a stack backtrace if g++ is used.
std::vector<std::string>
Logger::DemangleStackBacktrace( std::vector<std::string> stack_backtrace )
{
return stack_backtrace;
}
#endif
// This private method separates a single stack backtrace entry into
// the function, offset, and remainder.
//
// I.e.:
// Mangled: ./module(function+0x15c) [0x8048a6d]
// Interpretation: ./executable(function+offset)
//
// An exception is thrown if:
// The entry cannot be separated (invalid_argument)
std::tuple<std::string, std::string, std::string>
Logger::SeparateBacktraceEntry( std::string entry )
{
std::string executable;
std::string function;
std::string offset;
size_t executable_begin = 2;
size_t func_begin = 0;
size_t offset_begin = 0;
size_t len = entry.length();
for( size_t i = 0; i < len; ++i )
{
if( entry.at(i) == '(' )
{
func_begin = i + 1;
size_t chars_to_copy = i - executable_begin;
executable = std::string(entry, executable_begin, chars_to_copy);
break;
}
}
for( size_t i = func_begin; i < len; ++i )
{
if( entry.at(i) == '+' )
{
offset_begin = i + 1;
size_t chars_to_copy = i - func_begin;
function = std::string(entry, func_begin, chars_to_copy);
break;
}
}
for( size_t i = offset_begin; i < len; ++i )
{
if( entry.at(i) == ')' )
{
size_t chars_to_copy = i - offset_begin;
offset = std::string(entry, offset_begin, chars_to_copy);
break;
}
}
if( executable.empty() || function.empty() || offset.empty() )
{
throw std::invalid_argument("Error: SeparateBacktraceEntry() was "\
"unable to parse the given entry.\n");
}
return make_tuple(executable, function, offset);
}
} // End of unnamed namespace (local to the file)
// Place loggers in here
namespace exceptional
{
Logger logger_default_file;
Logger logger_example_file("example_file.log");
Logger logger_cout(std::cout);
}
<|endoftext|> |
<commit_before>#pragma once
#include <gfx/shape2d.hpp>
#include <gfx/shape3d.hpp>
namespace gfx
{
template<typename D>
struct shape_properties
{
draw_mode mode;
D dimensions;
};
class shape_factory
{
public:
template<typename ...Args>
auto make_triangle(triangle_properties const& properties, Args &&... args) const
{
return triangle_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_rectangle(rectangle_properties const& properties, Args &&... args) const
{
return rectangle_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_polygon(polygon_properties const& properties, Args &&... args) const
{
return polygon_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_spotted_cube(cube_properties const& properties, Args &&... args) const
{
return cube_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_textured_cube(cube_properties const& properties, Args &&... args) const
{
return cube_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_wireframe_cube(cube_properties const& properties, Args &&... args) const
{
return cube_factory::make(properties, std::forward<Args>(args)...);
}
};
} // ns gfx
<commit_msg>dead code<commit_after>#pragma once
#include <gfx/shape2d.hpp>
#include <gfx/shape3d.hpp>
namespace gfx
{
class shape_factory
{
public:
template<typename ...Args>
auto make_triangle(triangle_properties const& properties, Args &&... args) const
{
return triangle_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_rectangle(rectangle_properties const& properties, Args &&... args) const
{
return rectangle_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_polygon(polygon_properties const& properties, Args &&... args) const
{
return polygon_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_spotted_cube(cube_properties const& properties, Args &&... args) const
{
return cube_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_textured_cube(cube_properties const& properties, Args &&... args) const
{
return cube_factory::make(properties, std::forward<Args>(args)...);
}
template<typename ...Args>
auto make_wireframe_cube(cube_properties const& properties, Args &&... args) const
{
return cube_factory::make(properties, std::forward<Args>(args)...);
}
};
} // ns gfx
<|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson
*
*
* Per Larsson a.k.a finalman
* Olof Naessn a.k.a jansem/yakslem
*
* Visit: http://guichan.sourceforge.net
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Guichan nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GCN_GUI_HPP
#define GCN_GUI_HPP
#include <list>
#include <deque>
#include "guichan/keyevent.hpp"
#include "guichan/mouseevent.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/platform.hpp"
namespace gcn
{
class FocusHandler;
class Graphics;
class Input;
class KeyListener;
class Widget;
// The following comment will appear in the doxygen main page.
/**
* @mainpage
* @section Introduction
* This documentation is mostly intended as a reference to the API. If you want to get started with Guichan, we suggest you check out the programs in the examples directory of the Guichan release.
* @n
* @n
* This documentation is, and will always be, work in progress. If you find any errors, typos or inconsistencies, or if you feel something needs to be explained in more detail - don't hesitate to tell us.
*/
/**
* Contains a Guichan GUI. This is the core class of Guichan to which
* implementations of back ends are passed, to make Guichan work with
* a specific library, and to where the top widget (root widget of GUI)
* is added. If you want to be able to have more then one widget in your
* GUI, the top widget should be a container.
*
* A Gui object cannot work properly without passing back end
* implementations to it. A Gui object must have an implementation of a
* Graphics and an implementation of Input.
*
* NOTE: A complete GUI also must have the ability to load images.
* Images are loaded with the Image class, so to make Guichan
* able to load images an implementation of ImageLoader must be
* passed to Image.
*
* @see Graphics, Input, Image
*/
class GCN_CORE_DECLSPEC Gui
{
public:
/**
* Constructor.
*/
Gui();
/**
* Destructor.
*/
virtual ~Gui();
/**
* Sets the top widget. The top widget is the root widget
* of the GUI. If you want a GUI to be able to contain more
* than one widget the top widget should be a container.
*
* @param top The top widget.
* @see Container
* @since 0.1.0
*/
virtual void setTop(Widget* top);
/**
* Gets the top widget. The top widget is the root widget
* of the GUI.
*
* @return The top widget. NULL if no top widget has been set.
* @since 0.1.0
*/
virtual Widget* getTop() const;
/**
* Sets the graphics object to use for drawing.
*
* @param graphics The graphics object to use for drawing.
* @see getGraphics, AllegroGraphics, HGEGraphics,
* OpenLayerGraphics, OpenGLGraphics, SDLGraphics
* @since 0.1.0
*/
virtual void setGraphics(Graphics* graphics);
/**
* Gets the graphics object used for drawing.
*
* @return The graphics object used for drawing. NULL if no
* graphics object has been set.
* @see setGraphics, AllegroGraphics, HGEGraphics,
* OpenLayerGraphics, OpenGLGraphics, SDLGraphics
* @since 0.1.0
*/
virtual Graphics* getGraphics() const;
/**
* Sets the input object to use for input handling.
*
* @param input The input object to use for input handling.
* @see getInput, AllegroInput, HGEInput, OpenLayerInput,
* SDLInput
* @since 0.1.0
*/
virtual void setInput(Input* input);
/**
* Gets the input object being used for input handling.
*
* @return The input object used for handling input. NULL if no
* input object has been set.
* @see setInput, AllegroInput, HGEInput, OpenLayerInput,
* SDLInput
* @since 0.1.0
*/
virtual Input* getInput() const;
/**
* Performs logic of the GUI. By calling this function all logic
* functions down in the GUI heirarchy will be called. When logic
* is called for Gui, user input will be handled.
*
* @see Widget::logic
* @since 0.1.0
*/
virtual void logic();
/**
* Draws the GUI. By calling this funcion all draw functions
* down in the GUI hierarchy will be called. When draw is called
* the used Graphics object will be initialised and drawing of
* the top widget will commence.
*
* @see Widget::draw
* @since 0.1.0
*/
virtual void draw();
/**
* Focuses none of the widgets in the Gui.
*
* @since 0.1.0
*/
virtual void focusNone();
/**
* Sets tabbing enabled, or not. Tabbing is the usage of
* changing focus by utilising the tab key.
*
* @param tabbing True if tabbing should be enabled, false
* otherwise.
* @see isTabbingEnabled
* @since 0.1.0
*/
virtual void setTabbingEnabled(bool tabbing);
/**
* Checks if tabbing is enabled.
*
* @return True if tabbing is enabled, false otherwise.
* @see setTabbingEnabled
* @since 0.1.0
*/
virtual bool isTabbingEnabled();
/**
* Adds a global key listener to the Gui. A global key listener
* will receive all key events generated from the GUI and global
* key listeners will receive the events before key listeners
* of widgets.
*
* @param keyListener The key listener to add.
* @see removeGlobalKeyListener
* @since 0.5.0
*/
virtual void addGlobalKeyListener(KeyListener* keyListener);
/**
* Removes global key listener from the Gui.
*
* @param keyListener The key listener to remove.
* @throws Exception if the key listener hasn't been added.
* @see addGlobalKeyListener
* @since 0.5.0
*/
virtual void removeGlobalKeyListener(KeyListener* keyListener);
protected:
/**
* Handles all mouse input.
*
* @since 0.6.0
*/
virtual void handleMouseInput();
/**
* Handles key input.
*
* @since 0.6.0
*/
virtual void handleKeyInput();
/**
* Handles mouse moved input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseMoved(const MouseInput& mouseInput);
/**
* Handles mouse pressed input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMousePressed(const MouseInput& mouseInput);
/**
*
* Handles mouse wheel moved down input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseWheelMovedDown(const MouseInput& mouseInput);
/**
* Handles mouse wheel moved up input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseWheelMovedUp(const MouseInput& mouseInput);
/**
* Handles mouse released input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseReleased(const MouseInput& mouseInput);
/**
* Handles modal focus. Modal focus needs to be checked at
* each logic iteration as it might be necessary to distribute
* mouse entered or mouse exited events.
*
* @since 0.8.0
*/
virtual void handleModalFocus();
/**
* Handles modal mouse input focus. Modal mouse input focus needs
* to be checked at each logic iteration as it might be necessary to
* distribute mouse entered or mouse exited events.
*
* @since 0.8.0
*/
virtual void handleModalMouseInputFocus();
/**
* Handles modal focus gained. If modal focus has been gaind it might
* be necessary to distribute mouse entered or mouse exited events.
*
* @since 0.8.0
*/
virtual void handleModalFocusGained();
/**
* Handles modal mouse input focus gained. If modal focus has been gaind
* it might be necessary to distribute mouse entered or mouse exited events.
*
* @since 0.8.0
*/
virtual void handleModalFocusReleased();
/**
* Distributes a mouse event.
*
* @param type The type of the event to distribute,
* @param button The button of the event (if any used) to distribute.
* @param x The x coordinate of the event.
* @param y The y coordinate of the event.
* @param fource indicates whether the distribution should be forced or not.
* A forced distribution distributes the event even if a widget
* is not enabled, not visible, another widget has modal
* focus or another widget has modal mouse input focus.
* Default value is false.
* @param toSourceOnly indicates whether the distribution should be to the
* source widget only or to it's parent's mouse listeners
* as well.
*
* @since 0.6.0
*/
virtual void distributeMouseEvent(Widget* source,
int type,
int button,
int x,
int y,
bool force = false,
bool toSourceOnly = false);
/**
* Distributes a key event.
*
* @param keyEvent The key event to distribute.
* @since 0.6.0
*/
virtual void distributeKeyEvent(KeyEvent& keyEvent);
/**
* Distributes a key event to the global key listeners.
*
* @param keyEvent The key event to distribute.
*
* @since 0.6.0
*/
virtual void distributeKeyEventToGlobalKeyListeners(KeyEvent& keyEvent);
/**
* Gets the widget at a certain position.
*
* @return The widget at a certain position.
* @since 0.6.0
*/
virtual Widget* getWidgetAt(int x, int y);
/**
* Gets the source of the mouse event.
*
* @return The source widget of the mouse event.
* @since 0.6.0
*/
virtual Widget* getMouseEventSource(int x, int y);
/**
* Gets the source of the key event.
*
* @return The source widget of the key event.
* @since 0.6.0
*/
virtual Widget* getKeyEventSource();
/**
* Holds the top widget.
*/
Widget* mTop;
/**
* Holds the graphics implementation used.
*/
Graphics* mGraphics;
/**
* Holds the input implementation used.
*/
Input* mInput;
/**
* Holds the focus handler for the Gui.
*/
FocusHandler* mFocusHandler;
/**
* True if tabbing is enabled, false otherwise.
*/
bool mTabbing;
/**
* Typedef.
*/
typedef std::list<KeyListener*> KeyListenerList;
/**
* Typedef.
*/
typedef KeyListenerList::iterator KeyListenerListIterator;
/**
* Holds the global key listeners of the Gui.
*/
KeyListenerList mKeyListeners;
/**
* True if shift is pressed, false otherwise.
*/
bool mShiftPressed;
/**
* True if meta is pressed, false otherwise.
*/
bool mMetaPressed;
/**
* True if control is pressed, false otherwise.
*/
bool mControlPressed;
/**
* True if alt is pressed, false otherwise.
*/
bool mAltPressed;
/**
* Holds the last mouse button pressed.
*/
unsigned int mLastMousePressButton;
/**
* Holds the last mouse press time stamp.
*/
int mLastMousePressTimeStamp;
/**
* Holds the last mouse x coordinate.
*/
int mLastMouseX;
/**
* Holds the last mouse y coordinate.
*/
int mLastMouseY;
/**
* Holds the current click count. Used to keep track
* of clicks for a the last pressed button.
*/
int mClickCount;
/**
* Holds the last button used when a drag of a widget
* was initiated. Used to be able to release a drag
* when the same button is released.
*/
int mLastMouseDragButton;
/**
* Holds a stack with all the widgets with the mouse.
* Used to properly distribute mouse events.
*/
std::deque<Widget*> mWidgetWithMouseQueue;
};
}
#endif // end GCN_GUI_HPP
/* yakslem - "Women, it's a constant struggle."
* finalman - "Yes, but sometimes they succeed with their guesses."
* yaklsem - "...eh...I was talking about love."
* finalman - "Oh...ok..."
* An awkward silence followed.
*/
<commit_msg>Another typo.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson
*
*
* Per Larsson a.k.a finalman
* Olof Naessn a.k.a jansem/yakslem
*
* Visit: http://guichan.sourceforge.net
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Guichan nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GCN_GUI_HPP
#define GCN_GUI_HPP
#include <list>
#include <deque>
#include "guichan/keyevent.hpp"
#include "guichan/mouseevent.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/platform.hpp"
namespace gcn
{
class FocusHandler;
class Graphics;
class Input;
class KeyListener;
class Widget;
// The following comment will appear in the doxygen main page.
/**
* @mainpage
* @section Introduction
* This documentation is mostly intended as a reference to the API. If you want to get started with Guichan, we suggest you check out the programs in the examples directory of the Guichan release.
* @n
* @n
* This documentation is, and will always be, work in progress. If you find any errors, typos or inconsistencies, or if you feel something needs to be explained in more detail - don't hesitate to tell us.
*/
/**
* Contains a Guichan GUI. This is the core class of Guichan to which
* implementations of back ends are passed, to make Guichan work with
* a specific library, and to where the top widget (root widget of GUI)
* is added. If you want to be able to have more then one widget in your
* GUI, the top widget should be a container.
*
* A Gui object cannot work properly without passing back end
* implementations to it. A Gui object must have an implementation of a
* Graphics and an implementation of Input.
*
* NOTE: A complete GUI also must have the ability to load images.
* Images are loaded with the Image class, so to make Guichan
* able to load images an implementation of ImageLoader must be
* passed to Image.
*
* @see Graphics, Input, Image
*/
class GCN_CORE_DECLSPEC Gui
{
public:
/**
* Constructor.
*/
Gui();
/**
* Destructor.
*/
virtual ~Gui();
/**
* Sets the top widget. The top widget is the root widget
* of the GUI. If you want a GUI to be able to contain more
* than one widget the top widget should be a container.
*
* @param top The top widget.
* @see Container
* @since 0.1.0
*/
virtual void setTop(Widget* top);
/**
* Gets the top widget. The top widget is the root widget
* of the GUI.
*
* @return The top widget. NULL if no top widget has been set.
* @since 0.1.0
*/
virtual Widget* getTop() const;
/**
* Sets the graphics object to use for drawing.
*
* @param graphics The graphics object to use for drawing.
* @see getGraphics, AllegroGraphics, HGEGraphics,
* OpenLayerGraphics, OpenGLGraphics, SDLGraphics
* @since 0.1.0
*/
virtual void setGraphics(Graphics* graphics);
/**
* Gets the graphics object used for drawing.
*
* @return The graphics object used for drawing. NULL if no
* graphics object has been set.
* @see setGraphics, AllegroGraphics, HGEGraphics,
* OpenLayerGraphics, OpenGLGraphics, SDLGraphics
* @since 0.1.0
*/
virtual Graphics* getGraphics() const;
/**
* Sets the input object to use for input handling.
*
* @param input The input object to use for input handling.
* @see getInput, AllegroInput, HGEInput, OpenLayerInput,
* SDLInput
* @since 0.1.0
*/
virtual void setInput(Input* input);
/**
* Gets the input object being used for input handling.
*
* @return The input object used for handling input. NULL if no
* input object has been set.
* @see setInput, AllegroInput, HGEInput, OpenLayerInput,
* SDLInput
* @since 0.1.0
*/
virtual Input* getInput() const;
/**
* Performs logic of the GUI. By calling this function all logic
* functions down in the GUI heirarchy will be called. When logic
* is called for Gui, user input will be handled.
*
* @see Widget::logic
* @since 0.1.0
*/
virtual void logic();
/**
* Draws the GUI. By calling this funcion all draw functions
* down in the GUI hierarchy will be called. When draw is called
* the used Graphics object will be initialised and drawing of
* the top widget will commence.
*
* @see Widget::draw
* @since 0.1.0
*/
virtual void draw();
/**
* Focuses none of the widgets in the Gui.
*
* @since 0.1.0
*/
virtual void focusNone();
/**
* Sets tabbing enabled, or not. Tabbing is the usage of
* changing focus by utilising the tab key.
*
* @param tabbing True if tabbing should be enabled, false
* otherwise.
* @see isTabbingEnabled
* @since 0.1.0
*/
virtual void setTabbingEnabled(bool tabbing);
/**
* Checks if tabbing is enabled.
*
* @return True if tabbing is enabled, false otherwise.
* @see setTabbingEnabled
* @since 0.1.0
*/
virtual bool isTabbingEnabled();
/**
* Adds a global key listener to the Gui. A global key listener
* will receive all key events generated from the GUI and global
* key listeners will receive the events before key listeners
* of widgets.
*
* @param keyListener The key listener to add.
* @see removeGlobalKeyListener
* @since 0.5.0
*/
virtual void addGlobalKeyListener(KeyListener* keyListener);
/**
* Removes global key listener from the Gui.
*
* @param keyListener The key listener to remove.
* @throws Exception if the key listener hasn't been added.
* @see addGlobalKeyListener
* @since 0.5.0
*/
virtual void removeGlobalKeyListener(KeyListener* keyListener);
protected:
/**
* Handles all mouse input.
*
* @since 0.6.0
*/
virtual void handleMouseInput();
/**
* Handles key input.
*
* @since 0.6.0
*/
virtual void handleKeyInput();
/**
* Handles mouse moved input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseMoved(const MouseInput& mouseInput);
/**
* Handles mouse pressed input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMousePressed(const MouseInput& mouseInput);
/**
*
* Handles mouse wheel moved down input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseWheelMovedDown(const MouseInput& mouseInput);
/**
* Handles mouse wheel moved up input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseWheelMovedUp(const MouseInput& mouseInput);
/**
* Handles mouse released input.
*
* @param mouseInput The mouse input to handle.
* @since 0.6.0
*/
virtual void handleMouseReleased(const MouseInput& mouseInput);
/**
* Handles modal focus. Modal focus needs to be checked at
* each logic iteration as it might be necessary to distribute
* mouse entered or mouse exited events.
*
* @since 0.8.0
*/
virtual void handleModalFocus();
/**
* Handles modal mouse input focus. Modal mouse input focus needs
* to be checked at each logic iteration as it might be necessary to
* distribute mouse entered or mouse exited events.
*
* @since 0.8.0
*/
virtual void handleModalMouseInputFocus();
/**
* Handles modal focus gained. If modal focus has been gained it might
* be necessary to distribute mouse entered or mouse exited events.
*
* @since 0.8.0
*/
virtual void handleModalFocusGained();
/**
* Handles modal mouse input focus gained. If modal focus has been
* gained it might be necessary to distribute mouse entered or mouse
* exited events.
*
* @since 0.8.0
*/
virtual void handleModalFocusReleased();
/**
* Distributes a mouse event.
*
* @param type The type of the event to distribute,
* @param button The button of the event (if any used) to distribute.
* @param x The x coordinate of the event.
* @param y The y coordinate of the event.
* @param fource indicates whether the distribution should be forced or not.
* A forced distribution distributes the event even if a widget
* is not enabled, not visible, another widget has modal
* focus or another widget has modal mouse input focus.
* Default value is false.
* @param toSourceOnly indicates whether the distribution should be to the
* source widget only or to it's parent's mouse listeners
* as well.
*
* @since 0.6.0
*/
virtual void distributeMouseEvent(Widget* source,
int type,
int button,
int x,
int y,
bool force = false,
bool toSourceOnly = false);
/**
* Distributes a key event.
*
* @param keyEvent The key event to distribute.
* @since 0.6.0
*/
virtual void distributeKeyEvent(KeyEvent& keyEvent);
/**
* Distributes a key event to the global key listeners.
*
* @param keyEvent The key event to distribute.
*
* @since 0.6.0
*/
virtual void distributeKeyEventToGlobalKeyListeners(KeyEvent& keyEvent);
/**
* Gets the widget at a certain position.
*
* @return The widget at a certain position.
* @since 0.6.0
*/
virtual Widget* getWidgetAt(int x, int y);
/**
* Gets the source of the mouse event.
*
* @return The source widget of the mouse event.
* @since 0.6.0
*/
virtual Widget* getMouseEventSource(int x, int y);
/**
* Gets the source of the key event.
*
* @return The source widget of the key event.
* @since 0.6.0
*/
virtual Widget* getKeyEventSource();
/**
* Holds the top widget.
*/
Widget* mTop;
/**
* Holds the graphics implementation used.
*/
Graphics* mGraphics;
/**
* Holds the input implementation used.
*/
Input* mInput;
/**
* Holds the focus handler for the Gui.
*/
FocusHandler* mFocusHandler;
/**
* True if tabbing is enabled, false otherwise.
*/
bool mTabbing;
/**
* Typedef.
*/
typedef std::list<KeyListener*> KeyListenerList;
/**
* Typedef.
*/
typedef KeyListenerList::iterator KeyListenerListIterator;
/**
* Holds the global key listeners of the Gui.
*/
KeyListenerList mKeyListeners;
/**
* True if shift is pressed, false otherwise.
*/
bool mShiftPressed;
/**
* True if meta is pressed, false otherwise.
*/
bool mMetaPressed;
/**
* True if control is pressed, false otherwise.
*/
bool mControlPressed;
/**
* True if alt is pressed, false otherwise.
*/
bool mAltPressed;
/**
* Holds the last mouse button pressed.
*/
unsigned int mLastMousePressButton;
/**
* Holds the last mouse press time stamp.
*/
int mLastMousePressTimeStamp;
/**
* Holds the last mouse x coordinate.
*/
int mLastMouseX;
/**
* Holds the last mouse y coordinate.
*/
int mLastMouseY;
/**
* Holds the current click count. Used to keep track
* of clicks for a the last pressed button.
*/
int mClickCount;
/**
* Holds the last button used when a drag of a widget
* was initiated. Used to be able to release a drag
* when the same button is released.
*/
int mLastMouseDragButton;
/**
* Holds a stack with all the widgets with the mouse.
* Used to properly distribute mouse events.
*/
std::deque<Widget*> mWidgetWithMouseQueue;
};
}
#endif // end GCN_GUI_HPP
/* yakslem - "Women, it's a constant struggle."
* finalman - "Yes, but sometimes they succeed with their guesses."
* yaklsem - "...eh...I was talking about love."
* finalman - "Oh...ok..."
* An awkward silence followed.
*/
<|endoftext|> |
<commit_before>#include "readOFF.h"
#include "list_to_matrix.h"
#include <cstdio>
template <typename Scalar, typename Index>
IGL_INLINE bool igl::readOFF(
const std::string off_file_name,
std::vector<std::vector<Scalar > > & V,
std::vector<std::vector<Index > > & F,
std::vector<std::vector<Scalar > > & N)
{
FILE * off_file = fopen(off_file_name.c_str(),"r");
if(NULL==off_file)
{
printf("IOError: %s could not be opened...\n",off_file_name.c_str());
return false;
}
V.clear();
F.clear();
N.clear();
// First line is always OFF
char header[1000];
const std::string OFF("OFF");
const std::string NOFF("NOFF");
if(!fscanf(off_file,"%s\n",header)==1
|| !(OFF == header || NOFF == header))
{
printf("Error: %s's first line should be OFF or NOFF not %s...",off_file_name.c_str(),header);
fclose(off_file);
return false;
}
bool has_normals = NOFF==header;
// Second line is #vertices #faces #edges
int number_of_vertices;
int number_of_faces;
int number_of_edges;
char tic_tac_toe;
char line[1000];
bool still_comments = true;
while(still_comments)
{
fgets(line,1000,off_file);
still_comments = line[0] == '#';
}
sscanf(line,"%d %d %d",&number_of_vertices,&number_of_faces,&number_of_edges);
V.resize(number_of_vertices);
if (has_normals)
N.resize(number_of_vertices);
F.resize(number_of_faces);
//printf("%s %d %d %d\n",(has_normals ? "NOFF" : "OFF"),number_of_vertices,number_of_faces,number_of_edges);
// Read vertices
for(int i = 0;i<number_of_vertices;)
{
float x,y,z,nx,ny,nz;
if((has_normals && fscanf(off_file, "%g %g %g %g %g %g\n",&x,&y,&z,&nx,&ny,&nz)==6) ||
(!has_normals && fscanf(off_file, "%g %g %g\n",&x,&y,&z)==3))
{
std::vector<Scalar > vertex;
vertex.resize(3);
vertex[0] = x;
vertex[1] = y;
vertex[2] = z;
V[i] = vertex;
if (has_normals)
{
std::vector<Scalar > normal;
normal.resize(3);
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
N[i] = normal;
}
i++;
}else if(
fscanf(off_file,"%[#]",&tic_tac_toe)==1)
{
char comment[1000];
fscanf(off_file,"%[^\n]",comment);
}else
{
printf("Error: bad line in %s\n",off_file_name.c_str());
fclose(off_file);
return false;
}
}
// Read faces
for(int i = 0;i<number_of_faces;)
{
std::vector<Index > face;
int valence;
if(fscanf(off_file,"%d",&valence)==1)
{
face.resize(valence);
for(int j = 0;j<valence;j++)
{
int index;
if(j<valence-1)
{
fscanf(off_file,"%d",&index);
}else{
fscanf(off_file,"%d%*[^\n]",&index);
}
face[j] = index;
}
F[i] = face;
i++;
}else if(
fscanf(off_file,"%[#]",&tic_tac_toe)==1)
{
char comment[1000];
fscanf(off_file,"%[^\n]",comment);
}else
{
printf("Error: bad line in %s\n",off_file_name.c_str());
fclose(off_file);
return false;
}
}
fclose(off_file);
return true;
}
#ifndef IGL_NO_EIGEN
template <typename DerivedV, typename DerivedF>
IGL_INLINE bool igl::readOFF(
const std::string str,
Eigen::PlainObjectBase<DerivedV>& V,
Eigen::PlainObjectBase<DerivedF>& F)
{
std::vector<std::vector<double> > vV;
std::vector<std::vector<double> > vN;
std::vector<std::vector<int> > vF;
bool success = igl::readOFF(str,vV,vF,vN);
if(!success)
{
// readOFF(str,vV,vF) should have already printed an error
// message to stderr
return false;
}
bool V_rect = igl::list_to_matrix(vV,V);
if(!V_rect)
{
// igl::list_to_matrix(vV,V) already printed error message to std err
return false;
}
bool F_rect = igl::list_to_matrix(vF,F);
if(!F_rect)
{
// igl::list_to_matrix(vF,F) already printed error message to std err
return false;
}
return true;
}
template <typename DerivedV, typename DerivedF>
IGL_INLINE bool igl::readOFF(
const std::string str,
Eigen::PlainObjectBase<DerivedV>& V,
Eigen::PlainObjectBase<DerivedF>& F,
Eigen::PlainObjectBase<DerivedV>& N)
{
std::vector<std::vector<double> > vV;
std::vector<std::vector<double> > vN;
std::vector<std::vector<int> > vF;
bool success = igl::readOFF(str,vV,vF,vN);
if(!success)
{
// readOFF(str,vV,vF) should have already printed an error
// message to stderr
return false;
}
bool V_rect = igl::list_to_matrix(vV,V);
if(!V_rect)
{
// igl::list_to_matrix(vV,V) already printed error message to std err
return false;
}
bool F_rect = igl::list_to_matrix(vF,F);
if(!F_rect)
{
// igl::list_to_matrix(vF,F) already printed error message to std err
return false;
}
if (vN.size())
{
bool N_rect = igl::list_to_matrix(vN,N);
if(!N_rect)
{
// igl::list_to_matrix(vN,N) already printed error message to std err
return false;
}
}
return true;
}
#endif
#ifndef IGL_HEADER_ONLY
// Explicit template specialization
// generated by autoexplicit.sh
template bool igl::readOFF<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
template bool igl::readOFF<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >&);
#endif
<commit_msg>Fixed bug in readoff that cast input to single precision float<commit_after>#include "readOFF.h"
#include "list_to_matrix.h"
#include <cstdio>
template <typename Scalar, typename Index>
IGL_INLINE bool igl::readOFF(
const std::string off_file_name,
std::vector<std::vector<Scalar > > & V,
std::vector<std::vector<Index > > & F,
std::vector<std::vector<Scalar > > & N)
{
FILE * off_file = fopen(off_file_name.c_str(),"r");
if(NULL==off_file)
{
printf("IOError: %s could not be opened...\n",off_file_name.c_str());
return false;
}
V.clear();
F.clear();
N.clear();
// First line is always OFF
char header[1000];
const std::string OFF("OFF");
const std::string NOFF("NOFF");
if(!fscanf(off_file,"%s\n",header)==1
|| !(OFF == header || NOFF == header))
{
printf("Error: %s's first line should be OFF or NOFF not %s...",off_file_name.c_str(),header);
fclose(off_file);
return false;
}
bool has_normals = NOFF==header;
// Second line is #vertices #faces #edges
int number_of_vertices;
int number_of_faces;
int number_of_edges;
char tic_tac_toe;
char line[1000];
bool still_comments = true;
while(still_comments)
{
fgets(line,1000,off_file);
still_comments = line[0] == '#';
}
sscanf(line,"%d %d %d",&number_of_vertices,&number_of_faces,&number_of_edges);
V.resize(number_of_vertices);
if (has_normals)
N.resize(number_of_vertices);
F.resize(number_of_faces);
//printf("%s %d %d %d\n",(has_normals ? "NOFF" : "OFF"),number_of_vertices,number_of_faces,number_of_edges);
// Read vertices
for(int i = 0;i<number_of_vertices;)
{
double x,y,z,nx,ny,nz;
if((has_normals && fscanf(off_file, "%lg %lg %lg %lg %lg %lg\n",&x,&y,&z,&nx,&ny,&nz)==6) ||
(!has_normals && fscanf(off_file, "%lg %lg %lg\n",&x,&y,&z)==3))
{
std::vector<Scalar > vertex;
vertex.resize(3);
vertex[0] = x;
vertex[1] = y;
vertex[2] = z;
V[i] = vertex;
if (has_normals)
{
std::vector<Scalar > normal;
normal.resize(3);
normal[0] = nx;
normal[1] = ny;
normal[2] = nz;
N[i] = normal;
}
i++;
}else if(
fscanf(off_file,"%[#]",&tic_tac_toe)==1)
{
char comment[1000];
fscanf(off_file,"%[^\n]",comment);
}else
{
printf("Error: bad line in %s\n",off_file_name.c_str());
fclose(off_file);
return false;
}
}
// Read faces
for(int i = 0;i<number_of_faces;)
{
std::vector<Index > face;
int valence;
if(fscanf(off_file,"%d",&valence)==1)
{
face.resize(valence);
for(int j = 0;j<valence;j++)
{
int index;
if(j<valence-1)
{
fscanf(off_file,"%d",&index);
}else{
fscanf(off_file,"%d%*[^\n]",&index);
}
face[j] = index;
}
F[i] = face;
i++;
}else if(
fscanf(off_file,"%[#]",&tic_tac_toe)==1)
{
char comment[1000];
fscanf(off_file,"%[^\n]",comment);
}else
{
printf("Error: bad line in %s\n",off_file_name.c_str());
fclose(off_file);
return false;
}
}
fclose(off_file);
return true;
}
#ifndef IGL_NO_EIGEN
template <typename DerivedV, typename DerivedF>
IGL_INLINE bool igl::readOFF(
const std::string str,
Eigen::PlainObjectBase<DerivedV>& V,
Eigen::PlainObjectBase<DerivedF>& F)
{
std::vector<std::vector<double> > vV;
std::vector<std::vector<double> > vN;
std::vector<std::vector<int> > vF;
bool success = igl::readOFF(str,vV,vF,vN);
if(!success)
{
// readOFF(str,vV,vF) should have already printed an error
// message to stderr
return false;
}
bool V_rect = igl::list_to_matrix(vV,V);
if(!V_rect)
{
// igl::list_to_matrix(vV,V) already printed error message to std err
return false;
}
bool F_rect = igl::list_to_matrix(vF,F);
if(!F_rect)
{
// igl::list_to_matrix(vF,F) already printed error message to std err
return false;
}
return true;
}
template <typename DerivedV, typename DerivedF>
IGL_INLINE bool igl::readOFF(
const std::string str,
Eigen::PlainObjectBase<DerivedV>& V,
Eigen::PlainObjectBase<DerivedF>& F,
Eigen::PlainObjectBase<DerivedV>& N)
{
std::vector<std::vector<double> > vV;
std::vector<std::vector<double> > vN;
std::vector<std::vector<int> > vF;
bool success = igl::readOFF(str,vV,vF,vN);
if(!success)
{
// readOFF(str,vV,vF) should have already printed an error
// message to stderr
return false;
}
bool V_rect = igl::list_to_matrix(vV,V);
if(!V_rect)
{
// igl::list_to_matrix(vV,V) already printed error message to std err
return false;
}
bool F_rect = igl::list_to_matrix(vF,F);
if(!F_rect)
{
// igl::list_to_matrix(vF,F) already printed error message to std err
return false;
}
if (vN.size())
{
bool N_rect = igl::list_to_matrix(vN,N);
if(!N_rect)
{
// igl::list_to_matrix(vN,N) already printed error message to std err
return false;
}
}
return true;
}
#endif
#ifndef IGL_HEADER_ONLY
// Explicit template specialization
// generated by autoexplicit.sh
template bool igl::readOFF<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
template bool igl::readOFF<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >&);
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
// Copyright (c) 2013, Christian Kellner <kellner@bio.lmu.de>
//
// 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 NIX_NDARRAY_H
#define NIX_NDARRAY_H
#include <vector>
#include <iostream>
#include <nix/Hydra.hpp>
#include <nix/Platform.hpp>
namespace nix {
class NIXAPI NDArray {
public:
typedef uint8_t byte_type;
NDArray(DataType dtype, NDSize dims);
size_t rank() const { return extends.size(); }
size_t num_elements() const { return extends.nelms(); }
NDSize shape() const { return extends; }
NDSize size()const { return extends; }
DataType dtype() const { return dataType ;}
template<typename T> const T get(size_t index) const;
template<typename T> const T get(const NDSize &index) const;
template<typename T> void set(size_t index, T value);
template<typename T> void set(const NDSize &index, T value);
byte_type *data() { return dstore.data(); }
const byte_type *data() const { return dstore.data(); }
void resize(const NDSize &new_size);
size_t sub2index(const NDSize &sub) const;
private:
DataType dataType;
void allocate_space();
void calc_strides();
NDSize extends;
NDSize strides;
std::vector<byte_type> dstore;
};
/* ******************************************* */
template<typename T>
const T NDArray::get(size_t index) const
{
const T *dx = reinterpret_cast<const T *>(&dstore[0]);
return dx[index];
}
template<typename T>
const T NDArray::get(const NDSize &index) const
{
size_t pos = sub2index(index);
const T *dx = reinterpret_cast<const T *>(&dstore[0]);
return dx[pos];
}
template<typename T>
void NDArray::set(size_t index, T value)
{
T* dx = reinterpret_cast<T *>(&dstore[0]);
dx[index] = value;
}
template<typename T>
void NDArray::set(const NDSize &index, T value)
{
size_t pos = sub2index(index);
T* dx = reinterpret_cast<T *>(&dstore[0]);
dx[pos] = value;
}
/* ****************************************** */
template<>
struct data_traits<NDArray> {
typedef NDArray value_type;
typedef NDArray& reference;
typedef const NDArray& const_reference;
typedef uint8_t element_type;
typedef uint8_t* element_pointer;
typedef const uint8_t* const_element_pointer;
static DataType data_type(const_reference value) {
return value.dtype();
}
static NDSize shape(const_reference value) {
return value.shape();
}
static size_t num_elements(const_reference value) {
return value.num_elements();
}
static const_element_pointer get_data(const_reference value) {
return value.data();
}
static element_pointer get_data(reference value) {
return value.data();
}
static void resize(reference value, const NDSize &dims) {
value.resize(dims);
}
};
} // namespace nix
#endif // NIX_NDARRAY_H
<commit_msg>NDArray: delegete access with NDSize to size_t arg<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
// Copyright (c) 2013, Christian Kellner <kellner@bio.lmu.de>
//
// 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 NIX_NDARRAY_H
#define NIX_NDARRAY_H
#include <vector>
#include <iostream>
#include <nix/Hydra.hpp>
#include <nix/Platform.hpp>
namespace nix {
class NIXAPI NDArray {
public:
typedef uint8_t byte_type;
NDArray(DataType dtype, NDSize dims);
size_t rank() const { return extends.size(); }
size_t num_elements() const { return extends.nelms(); }
NDSize shape() const { return extends; }
NDSize size()const { return extends; }
DataType dtype() const { return dataType ;}
template<typename T> const T get(size_t index) const;
template<typename T> const T get(const NDSize &index) const;
template<typename T> void set(size_t index, T value);
template<typename T> void set(const NDSize &index, T value);
byte_type *data() { return dstore.data(); }
const byte_type *data() const { return dstore.data(); }
void resize(const NDSize &new_size);
size_t sub2index(const NDSize &sub) const;
private:
DataType dataType;
void allocate_space();
void calc_strides();
NDSize extends;
NDSize strides;
std::vector<byte_type> dstore;
};
/* ******************************************* */
template<typename T>
const T NDArray::get(size_t index) const
{
const T *dx = reinterpret_cast<const T *>(&dstore[0]);
return dx[index];
}
template<typename T>
const T NDArray::get(const NDSize &index) const
{
size_t pos = sub2index(index);
return get<T>(pos);
}
template<typename T>
void NDArray::set(size_t index, T value)
{
T* dx = reinterpret_cast<T *>(&dstore[0]);
dx[index] = value;
}
template<typename T>
void NDArray::set(const NDSize &index, T value)
{
size_t pos = sub2index(index);
set(pos, value);
}
/* ****************************************** */
template<>
struct data_traits<NDArray> {
typedef NDArray value_type;
typedef NDArray& reference;
typedef const NDArray& const_reference;
typedef uint8_t element_type;
typedef uint8_t* element_pointer;
typedef const uint8_t* const_element_pointer;
static DataType data_type(const_reference value) {
return value.dtype();
}
static NDSize shape(const_reference value) {
return value.shape();
}
static size_t num_elements(const_reference value) {
return value.num_elements();
}
static const_element_pointer get_data(const_reference value) {
return value.data();
}
static element_pointer get_data(reference value) {
return value.data();
}
static void resize(reference value, const NDSize &dims) {
value.resize(dims);
}
};
} // namespace nix
#endif // NIX_NDARRAY_H
<|endoftext|> |
<commit_before>// safe_switch.hpp: Put the brakes on "break;" breakage.
// Copyright 2015 by David Krauss.
// This source is released under the MIT license, http://opensource.org/licenses/MIT
#ifndef INCLUDED_SSTAR_SAFE_SWITCH_HPP
#define INCLUDED_SSTAR_SAFE_SWITCH_HPP
#include <initializer_list>
#include <utility>
#if __cplusplus < 201402
namespace sstar_safe_switch {
namespace impl {
template< typename = void >
struct equal_to {
template< typename lhs, typename rhs >
bool operator () ( lhs const & l, rhs const & r ) const
{ return l == r; }
};
#else
# include <functional>
namespace sstar_safe_switch {
namespace impl {
using std::equal_to;
#endif
template< typename operand, typename comparison = equal_to<> >
class bound_comparison {
operand o;
comparison c;
public:
bound_comparison( operand && in_o, comparison in_c = {} )
: o( std::forward< operand >( in_o ) )
, c( std::move( in_c ) ) {}
typename std::decay< operand >::type const & get_value() const
{ return o; }
template< typename rhs >
bool operator () ( rhs const & r ) const
{ return { c( get_value(), r ) }; }
template< typename rhs >
bool operator () ( std::initializer_list< rhs > il ) const {
for ( auto && r : il ) {
if ( c( get_value(), r ) ) return true;
}
return false;
}
bool operator () ( std::initializer_list< typename std::decay< operand >::type > il ) const {
for ( auto && r : il ) {
if ( c( get_value(), r ) ) return true;
}
return false;
}
};
} // end namespace impl
template< typename comparison = impl::equal_to<>, typename operand >
impl::bound_comparison< operand, comparison >
bind_comparator( operand && o, comparison c = {} )
{ return { std::forward< operand >( o ), std::move( c ) }; }
} // end namespace sstar_safe_switch
#endif
<commit_msg>Consisntently insist on bool return from comparator.<commit_after>// safe_switch.hpp: Put the brakes on "break;" breakage.
// Copyright 2015 by David Krauss.
// This source is released under the MIT license, http://opensource.org/licenses/MIT
#ifndef INCLUDED_SSTAR_SAFE_SWITCH_HPP
#define INCLUDED_SSTAR_SAFE_SWITCH_HPP
#include <initializer_list>
#include <utility>
#if __cplusplus < 201402
namespace sstar_safe_switch {
namespace impl {
template< typename = void >
struct equal_to {
template< typename lhs, typename rhs >
bool operator () ( lhs const & l, rhs const & r ) const
{ return l == r; }
};
#else
# include <functional>
namespace sstar_safe_switch {
namespace impl {
using std::equal_to;
#endif
template< typename operand, typename comparison = equal_to<> >
class bound_comparison {
operand o;
comparison c;
public:
bound_comparison( operand && in_o, comparison in_c = {} )
: o( std::forward< operand >( in_o ) )
, c( std::move( in_c ) ) {}
typename std::decay< operand >::type const & get_value() const
{ return o; }
template< typename rhs >
bool operator () ( rhs const & r ) const
{ return bool{ c( get_value(), r ) }; }
template< typename rhs >
bool operator () ( std::initializer_list< rhs > il ) const {
for ( auto && r : il ) {
if ( bool{ c( get_value(), r ) } ) return true;
}
return false;
}
bool operator () ( std::initializer_list< typename std::decay< operand >::type > il ) const {
for ( auto && r : il ) {
if ( bool{ c( get_value(), r ) } ) return true;
}
return false;
}
};
} // end namespace impl
template< typename comparison = impl::equal_to<>, typename operand >
impl::bound_comparison< operand, comparison >
bind_comparator( operand && o, comparison c = {} )
{ return { std::forward< operand >( o ), std::move( c ) }; }
} // end namespace sstar_safe_switch
#endif
<|endoftext|> |
<commit_before>#include "include/vortex.hpp"
#include "include/app.hpp"
#include "common_def_priv.hpp"
#include <memory>
namespace vtx
{
struct PRIVATE_STRUCT_NAME(Vortex)
{
std::unique_ptr<Application> m_application;
};
void Vortex::setApplication(Application &&app)
{
m_private->m_application.reset(&app);
}
Vortex::Vortex() : m_private{ new PRIVATE_STRUCT_NAME(Vortex) }
{
}
Vortex::~Vortex()
{
DELETE_PRIVATE_MPRIVATE_PIMPL(Vortex)
}
void vtx::Vortex::initialize()
{
}
void vtx::Vortex::deinitialize()
{
}
}
<commit_msg>not needed scope<commit_after>#include "include/vortex.hpp"
#include "include/app.hpp"
#include "common_def_priv.hpp"
#include <memory>
namespace vtx
{
struct PRIVATE_STRUCT_NAME(Vortex)
{
std::unique_ptr<Application> m_application;
};
void Vortex::setApplication(Application &&app)
{
m_private->m_application.reset(&app);
}
Vortex::Vortex() : m_private{ new PRIVATE_STRUCT_NAME(Vortex) }
{
}
Vortex::~Vortex()
{
DELETE_PRIVATE_MPRIVATE_PIMPL(Vortex)
}
void Vortex::initialize()
{
}
void Vortex::deinitialize()
{
}
}
<|endoftext|> |
<commit_before>#include <libmemcached/memcached.h>
#include <string>
#include <vector>
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
~Memcached()
{
memcached_free(&memc);
}
bool fetch(std::string &key,
std::string &ret_val,
size_t *key_length,
size_t *value_length,
uint32_t *flags,
memcached_return *rc)
{
char ret_key[MEMCACHED_MAX_KEY];
char *value= memcached_fetch(&memc, ret_key, key_length,
value_length, flags, rc);
if (value)
{
ret_val.assign(value);
key.assign(ret_key);
return true;
}
return false;
}
std::string get(const std::string &key, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get(&memc, key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string get_by_key(const std::string &master_key,
const std::string &key,
size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get_by_key(&memc, master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
bool mget(std::vector<std::string> &keys)
{
std::vector<const char *> real_keys;
std::vector<size_t> key_len;
/*
* Construct an array which will contain the length
* of each of the strings in the input vector. Also, to
* interface with the memcached C API, we need to convert
* the vector of std::string's to a vector of char *.
*/
real_keys.reserve(keys.size());
key_len.reserve(keys.size());
std::vector<std::string>::iterator it= keys.begin();
while (it != keys.end())
{
real_keys.push_back(const_cast<char *>((*it).c_str()));
key_len.push_back((*it).length());
++it;
}
/*
* If the std::vector of keys is empty then we cannot
* call memcached_mget as we will get undefined behavior.
*/
if (!real_keys.empty())
{
memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0],
real_keys.size());
return (rc == MEMCACHED_SUCCESS);
}
return false;
}
bool set(const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration, flags);
return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);
}
bool set_all(std::vector<std::string> &keys,
std::vector<std::string> &values,
time_t expiration,
uint32_t flags)
{
if (keys.size() != values.size())
{
return false;
}
bool retval= true;
std::vector<std::string>::iterator key_it= keys.begin();
std::vector<std::string>::iterator val_it= values.begin();
while (key_it != keys.end())
{
retval= set((*key_it), (*val_it), expiration, flags);
if (retval == false)
{
return retval;
}
++key_it;
++val_it;
}
return retval;
}
bool set_by_key(const std::string &master_key,
const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration,
flags);
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool add_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool append_by_key(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool cas_by_key(const std::string &master_key,
const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
// using 'remove' vs. 'delete' since 'delete' is a keyword
bool remove(const std::string &key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool delete_by_key(const std::string &master_key,
const std::string &key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
bool flush(time_t expiration)
{
memcached_return rc= memcached_flush(&memc, expiration);
return (rc == MEMCACHED_SUCCESS);
}
bool fetch_execute(memcached_execute_function *callback,
void *context,
unsigned int num_of_callbacks)
{
memcached_return rc= memcached_fetch_execute(&memc,
callback,
context,
num_of_callbacks);
return (rc == MEMCACHED_SUCCESS);
}
const std::string lib_version() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
<commit_msg>Updated C++ interface to have include guards. Also modified the naming convention for the functions in the C++ interface. We should use camel case for the C++ interface.<commit_after>/*
* Summary: C++ interface for memcached server
*
* Copy: See Copyright for the status of this software.
*
* Authors: Padraig O'Sullivan, Patrick Galbraith
*/
#ifndef LIBMEMCACHEDPP_H
#define LIBMEMCACHEDPP_H
#include <libmemcached/memcached.h>
#include <string>
#include <vector>
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
~Memcached()
{
memcached_free(&memc);
}
bool fetch(std::string &key,
std::string &ret_val,
size_t *key_length,
size_t *value_length,
uint32_t *flags,
memcached_return *rc)
{
char ret_key[MEMCACHED_MAX_KEY];
char *value= memcached_fetch(&memc, ret_key, key_length,
value_length, flags, rc);
if (value)
{
ret_val.assign(value);
key.assign(ret_key);
return true;
}
return false;
}
std::string get(const std::string &key, size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get(&memc, key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
std::string getByKey(const std::string &master_key,
const std::string &key,
size_t *value_length)
{
uint32_t flags;
memcached_return rc;
std::string ret_val;
char *value= memcached_get_by_key(&memc,
master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
value_length, &flags, &rc);
if (value)
{
ret_val.assign(value);
}
return ret_val;
}
bool mget(std::vector<std::string> &keys)
{
std::vector<const char *> real_keys;
std::vector<size_t> key_len;
/*
* Construct an array which will contain the length
* of each of the strings in the input vector. Also, to
* interface with the memcached C API, we need to convert
* the vector of std::string's to a vector of char *.
*/
real_keys.reserve(keys.size());
key_len.reserve(keys.size());
std::vector<std::string>::iterator it= keys.begin();
while (it != keys.end())
{
real_keys.push_back(const_cast<char *>((*it).c_str()));
key_len.push_back((*it).length());
++it;
}
/*
* If the std::vector of keys is empty then we cannot
* call memcached_mget as we will get undefined behavior.
*/
if (!real_keys.empty())
{
memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0],
real_keys.size());
return (rc == MEMCACHED_SUCCESS);
}
return false;
}
bool set(const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration, flags);
return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);
}
bool setAll(std::vector<std::string> &keys,
std::vector<std::string> &values,
time_t expiration,
uint32_t flags)
{
if (keys.size() != values.size())
{
return false;
}
bool retval= true;
std::vector<std::string>::iterator key_it= keys.begin();
std::vector<std::string>::iterator val_it= values.begin();
while (key_it != keys.end())
{
retval= set((*key_it), (*val_it), expiration, flags);
if (retval == false)
{
return retval;
}
++key_it;
++val_it;
}
return retval;
}
bool setByKey(const std::string &master_key,
const std::string &key,
const std::string &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
value.c_str(), value.length(),
expiration,
flags);
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool addByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replaceByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
value.c_str(), value.length(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prependByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string &key, const std::string &value)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool appendByKey(const std::string &master_key,
const std::string &key,
const std::string &value)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
value.c_str(), value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool casByKey(const std::string &master_key,
const std::string &key,
const std::string &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
value.c_str(),
value.length(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
// using 'remove' vs. 'delete' since 'delete' is a keyword
bool remove(const std::string &key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool removeByKey(const std::string &master_key,
const std::string &key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
bool flush(time_t expiration)
{
memcached_return rc= memcached_flush(&memc, expiration);
return (rc == MEMCACHED_SUCCESS);
}
bool fetchExecute(memcached_execute_function *callback,
void *context,
unsigned int num_of_callbacks)
{
memcached_return rc= memcached_fetch_execute(&memc,
callback,
context,
num_of_callbacks);
return (rc == MEMCACHED_SUCCESS);
}
const std::string libVersion() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
#endif /* LIBMEMCACHEDPP_H */
<|endoftext|> |
<commit_before>/*
* Summary: C++ interface for memcached server
*
* Copy: See Copyright for the status of this software.
*
* Authors: Padraig O'Sullivan, Patrick Galbraith
*/
#ifndef LIBMEMCACHEDPP_H
#define LIBMEMCACHEDPP_H
#include <libmemcached/memcached.h>
#include <string.h>
#include <string>
#include <vector>
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
~Memcached()
{
memcached_free(&memc);
}
bool fetch(std::string &key,
std::vector<char> &ret_val,
uint32_t *flags,
memcached_return *rc)
{
char ret_key[MEMCACHED_MAX_KEY];
size_t value_length= 0;
size_t key_length= 0;
char *value= memcached_fetch(&memc, ret_key, &key_length,
&value_length, flags, rc);
if (value)
{
ret_val.reserve(value_length);
memcpy(&*ret_val.begin(), value, value_length);
key.assign(ret_key);
return true;
}
return false;
}
std::vector<char> &get(const std::string &key,
std::vector<char> &ret_val)
{
uint32_t flags= 0;
memcached_return rc;
size_t value_length= 0;
char *value= memcached_get(&memc, key.c_str(), key.length(),
&value_length, &flags, &rc);
if (value != NULL)
{
ret_val.reserve(value_length);
memcpy(&ret_val[0], value, value_length);
}
return ret_val;
}
std::vector<char> &getByKey(const std::string &master_key,
const std::string &key,
std::vector<char> &ret_val)
{
uint32_t flags= 0;
memcached_return rc;
size_t value_length= 0;
char *value= memcached_get_by_key(&memc,
master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
&value_length, &flags, &rc);
if (value)
{
ret_val.reserve(value_length);
memcpy(&*ret_val.begin(), value, value_length);
}
return ret_val;
}
bool mget(std::vector<std::string> &keys)
{
std::vector<const char *> real_keys;
std::vector<size_t> key_len;
/*
* Construct an array which will contain the length
* of each of the strings in the input vector. Also, to
* interface with the memcached C API, we need to convert
* the vector of std::string's to a vector of char *.
*/
real_keys.reserve(keys.size());
key_len.reserve(keys.size());
std::vector<std::string>::iterator it= keys.begin();
while (it != keys.end())
{
real_keys.push_back(const_cast<char *>((*it).c_str()));
key_len.push_back((*it).length());
++it;
}
/*
* If the std::vector of keys is empty then we cannot
* call memcached_mget as we will get undefined behavior.
*/
if (!real_keys.empty())
{
memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0],
real_keys.size());
return (rc == MEMCACHED_SUCCESS);
}
return false;
}
bool set(const std::string &key,
const std::vector<char> &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
&value[0], value.size(),
expiration, flags);
return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);
}
bool setAll(std::vector<std::string> &keys,
std::vector< std::vector<char> > &values,
time_t expiration,
uint32_t flags)
{
if (keys.size() != values.size())
{
return false;
}
bool retval= true;
std::vector<std::string>::iterator key_it= keys.begin();
std::vector< std::vector<char> >::iterator val_it= values.begin();
while (key_it != keys.end())
{
retval= set((*key_it), (*val_it), expiration, flags);
if (retval == false)
{
return retval;
}
++key_it;
++val_it;
}
return retval;
}
bool setByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
&value[0], value.size(),
expiration,
flags);
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
&value[0], value.size(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool addByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
&value[0], value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replaceByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
&value[0], value.size(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prependByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool appendByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string &key,
const std::vector<char> &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
&value[0], value.size(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool casByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool remove(const std::string &key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool removeByKey(const std::string &master_key,
const std::string &key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
bool flush(time_t expiration)
{
memcached_return rc= memcached_flush(&memc, expiration);
return (rc == MEMCACHED_SUCCESS);
}
bool fetchExecute(memcached_execute_function *callback,
void *context,
unsigned int num_of_callbacks)
{
memcached_return rc= memcached_fetch_execute(&memc,
callback,
context,
num_of_callbacks);
return (rc == MEMCACHED_SUCCESS);
}
const std::string libVersion() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
#endif /* LIBMEMCACHEDPP_H */
<commit_msg>Adding some comments to the C++ interface. Added few small utility functions to the C++ interface also.<commit_after>/*
* Summary: C++ interface for memcached server
*
* Copy: See Copyright for the status of this software.
*
* Authors: Padraig O'Sullivan <osullivan.padraig@gmail.com>
* Patrick Galbraith <patg@patg.net>
*/
/**
* @file memcached.hh
* @brief Libmemcached C++ interface
*/
#ifndef LIBMEMCACHEDPP_H
#define LIBMEMCACHEDPP_H
#include <libmemcached/memcached.h>
#include <string.h>
#include <string>
#include <vector>
/**
* This is the core memcached library (if later, other objects
* are needed, they will be created from this class).
*/
class Memcached
{
public:
Memcached()
:
memc(),
result()
{
memcached_create(&memc);
}
Memcached(memcached_st *clone)
:
memc(),
result()
{
memcached_clone(&memc, clone);
}
Memcached(const Memcached &rhs)
:
memc(),
result()
{
memcached_clone(&memc, const_cast<memcached_st *>(&rhs.getImpl()));
}
~Memcached()
{
memcached_free(&memc);
}
/**
* Get the internal memcached_st *
*/
memcached_st &getImpl()
{
return memc;
}
/**
* Get the internal memcached_st *
*/
const memcached_st &getImpl() const
{
return memc;
}
/**
* Return an error string for the given return structure.
*
* @param[in] rc a memcached_return structure
* @return error string corresponding to given return code in the library.
*/
const std::string getError(memcached_return rc) const
{
/* first parameter to strerror is unused */
return memcached_strerror(NULL, rc);
}
bool fetch(std::string &key,
std::vector<char> &ret_val,
uint32_t *flags,
memcached_return *rc)
{
char ret_key[MEMCACHED_MAX_KEY];
size_t value_length= 0;
size_t key_length= 0;
char *value= memcached_fetch(&memc, ret_key, &key_length,
&value_length, flags, rc);
if (value)
{
ret_val.reserve(value_length);
memcpy(&*ret_val.begin(), value, value_length);
key.assign(ret_key);
return true;
}
return false;
}
std::vector<char> &get(const std::string &key,
std::vector<char> &ret_val)
{
uint32_t flags= 0;
memcached_return rc;
size_t value_length= 0;
char *value= memcached_get(&memc, key.c_str(), key.length(),
&value_length, &flags, &rc);
if (value != NULL)
{
ret_val.reserve(value_length);
memcpy(&ret_val[0], value, value_length);
}
return ret_val;
}
std::vector<char> &getByKey(const std::string &master_key,
const std::string &key,
std::vector<char> &ret_val)
{
uint32_t flags= 0;
memcached_return rc;
size_t value_length= 0;
char *value= memcached_get_by_key(&memc,
master_key.c_str(), master_key.length(),
key.c_str(), key.length(),
&value_length, &flags, &rc);
if (value)
{
ret_val.reserve(value_length);
memcpy(&*ret_val.begin(), value, value_length);
}
return ret_val;
}
bool mget(std::vector<std::string> &keys)
{
std::vector<const char *> real_keys;
std::vector<size_t> key_len;
/*
* Construct an array which will contain the length
* of each of the strings in the input vector. Also, to
* interface with the memcached C API, we need to convert
* the vector of std::string's to a vector of char *.
*/
real_keys.reserve(keys.size());
key_len.reserve(keys.size());
std::vector<std::string>::iterator it= keys.begin();
while (it != keys.end())
{
real_keys.push_back(const_cast<char *>((*it).c_str()));
key_len.push_back((*it).length());
++it;
}
/*
* If the std::vector of keys is empty then we cannot
* call memcached_mget as we will get undefined behavior.
*/
if (!real_keys.empty())
{
memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0],
real_keys.size());
return (rc == MEMCACHED_SUCCESS);
}
return false;
}
bool set(const std::string &key,
const std::vector<char> &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set(&memc,
key.c_str(), key.length(),
&value[0], value.size(),
expiration, flags);
return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);
}
bool setAll(std::vector<std::string> &keys,
std::vector< std::vector<char> > &values,
time_t expiration,
uint32_t flags)
{
if (keys.size() != values.size())
{
return false;
}
bool retval= true;
std::vector<std::string>::iterator key_it= keys.begin();
std::vector< std::vector<char> >::iterator val_it= values.begin();
while (key_it != keys.end())
{
retval= set((*key_it), (*val_it), expiration, flags);
if (retval == false)
{
return retval;
}
++key_it;
++val_it;
}
return retval;
}
bool setByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value,
time_t expiration,
uint32_t flags)
{
memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(),
master_key.length(),
key.c_str(), key.length(),
&value[0], value.size(),
expiration,
flags);
return (rc == MEMCACHED_SUCCESS);
}
bool increment(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool decrement(const std::string &key, unsigned int offset, uint64_t *value)
{
memcached_return rc= memcached_decrement(&memc, key.c_str(),
key.length(),
offset, value);
return (rc == MEMCACHED_SUCCESS);
}
bool add(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_add(&memc, key.c_str(), key.length(),
&value[0], value.size(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool addByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_add_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replace(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),
&value[0], value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool replaceByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_replace_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prepend(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),
&value[0], value.size(), 0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool prependByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_prepend_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0,
0);
return (rc == MEMCACHED_SUCCESS);
}
bool append(const std::string &key, const std::vector<char> &value)
{
memcached_return rc= memcached_append(&memc,
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool appendByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value)
{
memcached_return rc= memcached_append_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0);
return (rc == MEMCACHED_SUCCESS);
}
bool cas(const std::string &key,
const std::vector<char> &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),
&value[0], value.size(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool casByKey(const std::string &master_key,
const std::string &key,
const std::vector<char> &value,
uint64_t cas_arg)
{
memcached_return rc= memcached_cas_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
&value[0],
value.size(),
0, 0, cas_arg);
return (rc == MEMCACHED_SUCCESS);
}
bool remove(const std::string &key)
{
memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);
return (rc == MEMCACHED_SUCCESS);
}
bool removeByKey(const std::string &master_key,
const std::string &key)
{
memcached_return rc= memcached_delete_by_key(&memc,
master_key.c_str(),
master_key.length(),
key.c_str(),
key.length(),
0);
return (rc == MEMCACHED_SUCCESS);
}
bool flush(time_t expiration)
{
memcached_return rc= memcached_flush(&memc, expiration);
return (rc == MEMCACHED_SUCCESS);
}
bool fetchExecute(memcached_execute_function *callback,
void *context,
unsigned int num_of_callbacks)
{
memcached_return rc= memcached_fetch_execute(&memc,
callback,
context,
num_of_callbacks);
return (rc == MEMCACHED_SUCCESS);
}
/**
* Get the library version string.
* @return std::string containing a copy of the library version string.
*/
const std::string libVersion() const
{
const char *ver= memcached_lib_version();
const std::string version(ver);
return version;
}
private:
memcached_st memc;
memcached_result_st result;
};
#endif /* LIBMEMCACHEDPP_H */
<|endoftext|> |
<commit_before>/*
* GameDelta.h
*
* Created on: 30 May 2014
* Author: Marco
*/
#ifndef GAMEDELTA_H_
#define GAMEDELTA_H_
#include "RenderObject.hpp"
#include "Position.hpp"
#include "Entity.hpp"
#include "Health.hpp"
class Behaviour;
#include <map>
#include <vector>
#include <memory>
using std::shared_ptr;
class RenderObjectDelta;
class CollisionEvent;
class GameDelta {
public:
GameDelta() :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects(),
deltaHealth(),
deltaBehaviours(),
deltaCollisionEvents()
{}
GameDelta(const GameDelta &delta);
GameDelta(Entity entity, const Position& pos);
GameDelta(Entity entity, const Coords& coords);
GameDelta(Entity entity, const Orientation& orientation);
GameDelta(Entity entity, const BoundingBox& bb);
GameDelta(Entity entity, const Health& health);
GameDelta(Entity, RenderObject* ro);
GameDelta(Entity entity, CollisionEvent event);
GameDelta(Entity entity, Behaviour *behaviour) : GameDelta()
{
deltaBehaviours[entity].push_back(behaviour);
}
void purgePosition(Entity entity)
{
deltaPositions.erase(entity);
}
GameDelta &mergeDelta(const GameDelta &oldDelta);
const std::map<Entity, std::vector<Behaviour *> >& getBehaviourDelta() const
{
return deltaBehaviours;
}
const std::map<Entity, Position>& getPositionsDelta() const
{
return deltaPositions;
}
const std::map<Entity, Orientation>& getOrientationsDelta() const
{
return deltaOrientations;
}
const std::map<Entity, BoundingBox>& getBoundingBoxDelta() const
{
return deltaBoundingBoxes;
}
std::map<Entity, shared_ptr<RenderObjectDelta>>& getRenderObjectsDelta()
{
return deltaRenderObjects;
}
const std::map<Entity, Health>& getHealthDelta() const
{
return deltaHealth;
}
const std::map<Entity, std::vector<CollisionEvent> >& getCollisionEvents()
{
return deltaCollisionEvents;
}
private:
std::map<Entity, Position> deltaPositions;
std::map<Entity, Orientation> deltaOrientations;
std::map<Entity, BoundingBox> deltaBoundingBoxes;
std::map<Entity, Health> deltaHealth;
std::map<Entity, std::vector<Behaviour *> > deltaBehaviours;
std::map<Entity, shared_ptr<RenderObjectDelta> > deltaRenderObjects;
std::map<Entity, std::vector<CollisionEvent> > deltaCollisionEvents;
};
class CollisionEvent
{
public:
CollisionEvent(Entity active, Entity passive);
private:
Entity m_active;
Entity m_passive;
};
enum class ObjectDelta {
ADDED,
REMOVED,
UPDATED
};
class RenderObjectDelta{
public:
RenderObjectDelta(ObjectDelta updateType, RenderObject* renderObject) :
m_updateType(updateType),
m_renderObject(renderObject)
{}
ObjectDelta m_updateType;
RenderObject* m_renderObject;
};
#endif /* GAMEDELTA_H_ */
<commit_msg>fixed<commit_after>/*
* GameDelta.h
*
* Created on: 30 May 2014
* Author: Marco
*/
#ifndef GAMEDELTA_H_
#define GAMEDELTA_H_
#include "RenderObject.hpp"
#include "Position.hpp"
#include "Entity.hpp"
#include "Health.hpp"
class Behaviour;
#include <map>
#include <vector>
#include <memory>
using std::shared_ptr;
class RenderObjectDelta;
class CollisionEvent;
class GameDelta {
public:
GameDelta() :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects(),
deltaHealth(),
deltaBehaviours(),
deltaCollisionEvents()
{}
GameDelta(const GameDelta &delta);
GameDelta(Entity entity, const Position& pos);
GameDelta(Entity entity, const Coords& coords);
GameDelta(Entity entity, const Orientation& orientation);
GameDelta(Entity entity, const BoundingBox& bb);
GameDelta(Entity entity, const Health& health);
GameDelta(Entity, RenderObject* ro);
GameDelta(Entity entity, CollisionEvent event);
GameDelta(Entity entity, Behaviour *behaviour) : GameDelta()
{
deltaBehaviours[entity].push_back(behaviour);
}
void purgePosition(Entity entity)
{
deltaPositions.erase(entity);
}
GameDelta &mergeDelta(const GameDelta &oldDelta);
const std::map<Entity, std::vector<Behaviour *> >& getBehaviourDelta() const
{
return deltaBehaviours;
}
const std::map<Entity, Position>& getPositionsDelta() const
{
return deltaPositions;
}
const std::map<Entity, Orientation>& getOrientationsDelta() const
{
return deltaOrientations;
}
const std::map<Entity, BoundingBox>& getBoundingBoxDelta() const
{
return deltaBoundingBoxes;
}
std::map<Entity, shared_ptr<RenderObjectDelta>>& getRenderObjectsDelta()
{
return deltaRenderObjects;
}
const std::map<Entity, Health>& getHealthDelta() const
{
return deltaHealth;
}
const std::map<Entity, std::vector<CollisionEvent> >& getCollisionEvents()
{
return deltaCollisionEvents;
}
private:
std::map<Entity, Position> deltaPositions;
std::map<Entity, Orientation> deltaOrientations;
std::map<Entity, BoundingBox> deltaBoundingBoxes;
std::map<Entity, Health> deltaHealth;
std::map<Entity, std::vector<Behaviour *> > deltaBehaviours;
std::map<Entity, shared_ptr<RenderObjectDelta> > deltaRenderObjects;
std::map<Entity, std::vector<CollisionEvent> > deltaCollisionEvents;
};
class CollisionEvent
{
public:
CollisionEvent(Entity active, Entity passive) : m_active(active), m_passive(passive) {};
private:
Entity m_active;
Entity m_passive;
};
enum class ObjectDelta {
ADDED,
REMOVED,
UPDATED
};
class RenderObjectDelta{
public:
RenderObjectDelta(ObjectDelta updateType, RenderObject* renderObject) :
m_updateType(updateType),
m_renderObject(renderObject)
{}
ObjectDelta m_updateType;
RenderObject* m_renderObject;
};
#endif /* GAMEDELTA_H_ */
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define SZ(x) ((int)((x).size()))
#define PB(x) push_back(x);
typedef long long LL;
typedef pair<int, int> PII; typedef pair<PII, int> PII2;
typedef vector<int> VI; typedef vector<VI> VVI;
int main() {
return 0;
}
<commit_msg>Added INF and MEMSET to default code<commit_after>#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define SZ(x) ((int)((x).size()))
#define PB(x) push_back(x);
#define INF (0x3f3f3f3f)
#define MEMSET(x,v) memset(x,v,sizeof(x));
typedef long long LL;
typedef pair<int, int> PII; typedef pair<PII, int> PII2;
typedef vector<int> VI; typedef vector<VI> VVI;
int main() {
return 0;
}
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
//#include "stdafx.h"
#include "common/ExtManager.h"
#include "rubyext/WebView.h"
#include <common/RhodesApp.h>
//#include "MainWindow.h"
#include "common/app_build_capabilities.h"
//extern CMainWindow& getAppWindow();
//#define IDM_NAVIGATE 40022
//#define IDM_EXECUTEJS 40033
//#define IDM_STOPNAVIGATE 40034
//#define IDM_ZOOMPAGE 40035
//#define IDM_ZOOMTEXT 40036
extern "C" HWND getMainWnd();
extern "C" HINSTANCE rho_wmimpl_get_appinstance();
extern "C" void rho_sys_app_exit();
extern "C" WCHAR* rho_wmimpl_get_configfilepath();
namespace rho {
namespace common {
IMPLEMENT_LOGCLASS(CExtManager, "ExtManager");
void CExtManager::registerExtension(const String& strName, IRhoExtension* pExt)
{
m_hashExtensions.put(strName, pExt);
}
IRhoExtension* CExtManager::getExtByName(const String& strName)
{
return m_hashExtensions.get(strName);
}
CRhoExtData CExtManager::makeExtData()
{
CRhoExtData oData;
oData.m_hWnd = getMainWnd();
oData.m_hInstance = rho_wmimpl_get_appinstance();
#if !defined(OS_WINDOWS_DESKTOP)
//oData.m_hBrowserWnd = getAppWindow().getWebKitEngine()->GetHTMLWND();
#endif
oData.m_iTabIndex = rho_webview_active_tab();
return oData;
}
void CExtManager::onSetPropertiesData( const wchar_t* pPropID, const wchar_t* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onSetPropertiesData( pPropID, pData, makeExtData() );
}
}
void CExtManager::onUnhandledProperty( const wchar_t* pModuleName, const wchar_t* pName, const wchar_t* pValue, const CRhoExtData& oExtData )
{
rho::common::IRhoExtension* pExt = getExtByName( rho::common::convertToStringA(pModuleName) );
if (pExt)
pExt->onSetProperty( pName, pValue, oExtData );
}
void CExtManager::onBeforeNavigate(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onBeforeNavigate( szUrlBeingNavigatedTo, makeExtData() );
}
}
void CExtManager::onNavigateComplete(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onNavigateComplete( szUrlBeingNavigatedTo, makeExtData() );
}
}
void CExtManager::onDocumentComplete(const wchar_t* szUrlOfDocument)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onDocumentComplete( szUrlOfDocument, makeExtData() );
}
}
void CExtManager::close()
{
m_hashExtensions.clear();
}
void CExtManager::executeRubyCallback( const char* szCallback, const char* szCallbackBody, const char* szCallbackData, bool bWaitForResponse)
{
//RHODESAPP().callCallbackWithData(szCallback, szCallbackBody, szCallbackData, bWaitForResponse );
}
void CExtManager::executeRubyCallbackWithJsonBody( const char* szCallback, const char* szCallbackBody, const char* szCallbackData, bool bWaitForResponse)
{
//RHODESAPP().callCallbackWithJsonBody(szCallback, szCallbackBody, szCallbackData, bWaitForResponse );
}
//extern "C" VALUE rjson_tokener_parse(const char *str, char** pszError );
unsigned long CExtManager::parseJsonToRubyHash(const char* szJson)
{
//char* szError = 0;
//unsigned long valBody = rjson_tokener_parse(szJson, &szError);
//if ( valBody != 0 )
// return valBody;
//LOG(ERROR) + "Incorrect json body.Error:" + (szError ? szError : "");
//if ( szError )
// free(szError);
//return rho_ruby_get_NIL();
return 0;
}
void CExtManager::navigate(const wchar_t* szUrl)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE, (LPARAM)_wcsdup(szUrl) );
}
bool CExtManager::existsJavascript(const wchar_t* szJSFunction)
{
#if !defined(OS_WINDOWS_DESKTOP)
return false; //getAppWindow().getWebKitEngine()->isExistJavascript(szJSFunction, rho_webview_active_tab());
#else
return true;
#endif
}
void CExtManager::setBrowserGesturing(bool bEnableGesturing)
{
#if !defined(OS_WINDOWS_DESKTOP)
//getAppWindow().getWebKitEngine()->setBrowserGesturing(bEnableGesturing);
#endif
}
void CExtManager::passSipPositionToEngine()
{
#if !defined(OS_WINDOWS_DESKTOP)
//getAppWindow().getWebKitEngine()->NotifyEngineOfSipPosition();
#endif
}
void CExtManager::executeJavascript(const wchar_t* szJSFunction)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_EXECUTEJS, (LPARAM)_wcsdup(szJSFunction) );
}
StringW CExtManager::getCurrentUrl()
{
return L"";//convertToStringW(RHODESAPP().getCurrentUrl(rho_webview_active_tab()));
}
void CExtManager::historyForward()
{
//rho_webview_navigate_forward();
}
void CExtManager::historyBack()
{
//rho_webview_navigate_back();
}
void CExtManager::refreshPage(bool bFromCache)
{
//rho_webview_refresh(rho_webview_active_tab());
}
void CExtManager::stopNavigate()
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_STOPNAVIGATE, (LPARAM)rho_webview_active_tab() );
}
void CExtManager::quitApp()
{
//rho_sys_app_exit();
}
static void __minimize_restoreApp(int nParam)
{
//::ShowWindow(getMainWnd(), nParam );
}
void CExtManager::minimizeApp()
{
//rho_callInUIThread(__minimize_restoreApp, SW_MINIMIZE);
}
void CExtManager::restoreApp()
{
// rho_callInUIThread(__minimize_restoreApp, SW_RESTORE);
}
void CExtManager::resizeBrowserWindow(RECT rc)
{
//::MoveWindow( getMainWnd(), rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, TRUE );
}
void CExtManager::zoomPage(float fZoom)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMPAGE, (LPARAM)new CRhoFloatData(fZoom) );
}
void CExtManager::zoomText(int nZoom)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMTEXT, (LPARAM)nZoom );
}
int CExtManager::getTextZoom() //Enum (0 to 4)
{
#if !defined(OS_WINDOWS_DESKTOP)
return 0;//getAppWindow().getWebKitEngine()->GetTextZoomOnTab(rho_webview_active_tab());
#else
return 2;
#endif
}
StringW CExtManager::getConfigPath()
{
#if defined(APP_BUILD_CAPABILITY_MOTOROLA)
return L"";//rho_wmimpl_get_configfilepath();
#else
return L"";
#endif
}
StringW CExtManager::getPageTitle(UINT iTab)
{
#if !defined(OS_WINDOWS_DESKTOP)
wchar_t szBuf[1025];
szBuf[0]=0;
//getAppWindow().getWebKitEngine()->GetTitleOnTab( szBuf, 1024, iTab );
return szBuf ? szBuf : L"";
#else
return L"";
#endif
}
extern "C" int rho_wmimpl_is_loglevel_enabled(int nLogLevel);
extern "C" bool rho_wmimpl_get_is_version2();
void CExtManager::rhoLog(ELogExtLevels eLogLevel, const char* szModule, const char* szMsg, const char* szFile, int nLine)
{
#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
bool bRE1App = false;
if (!rho_wmimpl_get_is_version2())
bRE1App = true;
if (bRE1App && !rho_wmimpl_is_loglevel_enabled(eLogLevel))
return;
#endif
int nSeverity = L_INFO;
switch (eLogLevel)
{
case eLogError:
nSeverity = L_ERROR;
break;
case eLogWarning:
nSeverity = L_WARNING;
break;
case eLogInfo:
nSeverity = L_INFO;
break;
case eLogUser:
nSeverity = L_INFO;
break;
case eLogDebug:
nSeverity = L_TRACE;
break;
}
//rhoPlainLog(szFile, nLine, nSeverity, szModule, szMsg);
}
bool CExtManager::onWndMsg(MSG& oMsg)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
if ( (it->second)->onWndMsg( oMsg ) )
return true;
}
return false;
}
bool CExtManager::onHTMLWndMsg(MSG& oMsg)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
if ( (it->second)->onHTMLWndMsg( oMsg ) )
return true;
}
return false;
}
long CExtManager::OnNavigateTimeout(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnNavigateTimeout( szUrlBeingNavigatedTo, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnSIPState(bool bSIPState)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnSIPState( bSIPState, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnAlertPopup(int nEnum, void* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnAlertPopup( nEnum, pData, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnAuthenticationRequest(int nEnum, void* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnAuthenticationRequest( nEnum, pData, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnGeolocationData(int nEnum, void* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnGeolocationData( nEnum, pData, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnNavigateError(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnNavigateError( szUrlBeingNavigatedTo, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnLicenseError(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnLicenseError( szUrlBeingNavigatedTo, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
void CExtManager::OnAppActivate(bool bActivate)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->OnAppActivate( bActivate, makeExtData() );
}
}
void CExtManager::OnWindowChanged(LPVOID lparam)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->OnWindowChanged( lparam );
}
}
//DWORD CExtManager::getProcessId()
//{
//#if !defined(OS_WINDOWS_DESKTOP)
// return 0;//getAppWindow().getWebKitEngine()->GetProcessID();
//#else
// return 0;
//#endif
//}
} //namespace common
} //namespace rho
<commit_msg>wp8: build fixed<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
//#include "stdafx.h"
#include "common/ExtManager.h"
#include "rubyext/WebView.h"
#include <common/RhodesApp.h>
//#include "MainWindow.h"
#include "common/app_build_capabilities.h"
//extern CMainWindow& getAppWindow();
//#define IDM_NAVIGATE 40022
//#define IDM_EXECUTEJS 40033
//#define IDM_STOPNAVIGATE 40034
//#define IDM_ZOOMPAGE 40035
//#define IDM_ZOOMTEXT 40036
extern "C" HWND getMainWnd();
extern "C" HINSTANCE rho_wmimpl_get_appinstance();
extern "C" void rho_sys_app_exit();
extern "C" WCHAR* rho_wmimpl_get_configfilepath();
namespace rho {
namespace common {
IMPLEMENT_LOGCLASS(CExtManager, "ExtManager");
void CExtManager::registerExtension(const String& strName, IRhoExtension* pExt)
{
m_hashExtensions.put(strName, pExt);
}
IRhoExtension* CExtManager::getExtByName(const String& strName)
{
return m_hashExtensions.get(strName);
}
CRhoExtData CExtManager::makeExtData()
{
CRhoExtData oData;
oData.m_hWnd = getMainWnd();
oData.m_hInstance = rho_wmimpl_get_appinstance();
#if !defined(OS_WINDOWS_DESKTOP)
//oData.m_hBrowserWnd = getAppWindow().getWebKitEngine()->GetHTMLWND();
#endif
oData.m_iTabIndex = rho_webview_active_tab();
return oData;
}
void CExtManager::onSetPropertiesData( const wchar_t* pPropID, const wchar_t* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onSetPropertiesData( pPropID, pData, makeExtData() );
}
}
void CExtManager::onUnhandledProperty( const wchar_t* pModuleName, const wchar_t* pName, const wchar_t* pValue, const CRhoExtData& oExtData )
{
rho::common::IRhoExtension* pExt = getExtByName( rho::common::convertToStringA(pModuleName) );
if (pExt)
pExt->onSetProperty( pName, pValue, oExtData );
}
void CExtManager::onBeforeNavigate(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onBeforeNavigate( szUrlBeingNavigatedTo, makeExtData() );
}
}
void CExtManager::onNavigateComplete(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onNavigateComplete( szUrlBeingNavigatedTo, makeExtData() );
}
}
void CExtManager::onDocumentComplete(const wchar_t* szUrlOfDocument)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->onDocumentComplete( szUrlOfDocument, makeExtData() );
}
}
void CExtManager::close()
{
m_hashExtensions.clear();
}
void CExtManager::executeRubyCallback( const char* szCallback, const char* szCallbackBody, const char* szCallbackData, bool bWaitForResponse)
{
//RHODESAPP().callCallbackWithData(szCallback, szCallbackBody, szCallbackData, bWaitForResponse );
}
void CExtManager::executeRubyCallbackWithJsonBody( const char* szCallback, const char* szCallbackBody, const char* szCallbackData, bool bWaitForResponse)
{
//RHODESAPP().callCallbackWithJsonBody(szCallback, szCallbackBody, szCallbackData, bWaitForResponse );
}
//extern "C" VALUE rjson_tokener_parse(const char *str, char** pszError );
unsigned long CExtManager::parseJsonToRubyHash(const char* szJson)
{
//char* szError = 0;
//unsigned long valBody = rjson_tokener_parse(szJson, &szError);
//if ( valBody != 0 )
// return valBody;
//LOG(ERROR) + "Incorrect json body.Error:" + (szError ? szError : "");
//if ( szError )
// free(szError);
//return rho_ruby_get_NIL();
return 0;
}
void CExtManager::navigate(const wchar_t* szUrl)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE, (LPARAM)_wcsdup(szUrl) );
}
bool CExtManager::existsJavascript(const wchar_t* szJSFunction)
{
#if !defined(OS_WINDOWS_DESKTOP)
return false; //getAppWindow().getWebKitEngine()->isExistJavascript(szJSFunction, rho_webview_active_tab());
#else
return true;
#endif
}
void CExtManager::setBrowserGesturing(bool bEnableGesturing)
{
#if !defined(OS_WINDOWS_DESKTOP)
//getAppWindow().getWebKitEngine()->setBrowserGesturing(bEnableGesturing);
#endif
}
void CExtManager::passSipPositionToEngine()
{
#if !defined(OS_WINDOWS_DESKTOP)
//getAppWindow().getWebKitEngine()->NotifyEngineOfSipPosition();
#endif
}
void CExtManager::executeJavascript(const wchar_t* szJSFunction)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_EXECUTEJS, (LPARAM)_wcsdup(szJSFunction) );
}
StringW CExtManager::getCurrentUrl()
{
return L"";//convertToStringW(RHODESAPP().getCurrentUrl(rho_webview_active_tab()));
}
void CExtManager::historyForward()
{
//rho_webview_navigate_forward();
}
void CExtManager::historyBack()
{
//rho_webview_navigate_back();
}
void CExtManager::refreshPage(bool bFromCache)
{
//rho_webview_refresh(rho_webview_active_tab());
}
void CExtManager::stopNavigate()
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_STOPNAVIGATE, (LPARAM)rho_webview_active_tab() );
}
void CExtManager::quitApp()
{
//rho_sys_app_exit();
}
static void __minimize_restoreApp(int nParam)
{
//::ShowWindow(getMainWnd(), nParam );
}
void CExtManager::minimizeApp()
{
//rho_callInUIThread(__minimize_restoreApp, SW_MINIMIZE);
}
void CExtManager::restoreApp()
{
// rho_callInUIThread(__minimize_restoreApp, SW_RESTORE);
}
void CExtManager::resizeBrowserWindow(RECT rc)
{
//::MoveWindow( getMainWnd(), rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, TRUE );
}
void CExtManager::zoomPage(float fZoom)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMPAGE, (LPARAM)new CRhoFloatData(fZoom) );
}
void CExtManager::zoomText(int nZoom)
{
//::PostMessage( getMainWnd(), WM_COMMAND, IDM_ZOOMTEXT, (LPARAM)nZoom );
}
int CExtManager::getTextZoom() //Enum (0 to 4)
{
#if !defined(OS_WINDOWS_DESKTOP)
return 0;//getAppWindow().getWebKitEngine()->GetTextZoomOnTab(rho_webview_active_tab());
#else
return 2;
#endif
}
StringW CExtManager::getConfigPath()
{
#if defined(APP_BUILD_CAPABILITY_MOTOROLA)
return L"";//rho_wmimpl_get_configfilepath();
#else
return L"";
#endif
}
StringW CExtManager::getPageTitle(UINT iTab)
{
#if !defined(OS_WINDOWS_DESKTOP)
wchar_t szBuf[1025];
szBuf[0]=0;
//getAppWindow().getWebKitEngine()->GetTitleOnTab( szBuf, 1024, iTab );
return szBuf ? szBuf : L"";
#else
return L"";
#endif
}
extern "C" int rho_wmimpl_is_loglevel_enabled(int nLogLevel);
extern "C" bool rho_wmimpl_get_is_version2();
void CExtManager::rhoLog(ELogExtLevels eLogLevel, const char* szModule, const char* szMsg, const char* szFile, int nLine)
{
#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
bool bRE1App = false;
if (!rho_wmimpl_get_is_version2())
bRE1App = true;
if (bRE1App && !rho_wmimpl_is_loglevel_enabled(eLogLevel))
return;
#endif
int nSeverity = L_INFO;
switch (eLogLevel)
{
case eLogError:
nSeverity = L_ERROR;
break;
case eLogWarning:
nSeverity = L_WARNING;
break;
case eLogInfo:
nSeverity = L_INFO;
break;
case eLogUser:
nSeverity = L_INFO;
break;
case eLogDebug:
nSeverity = L_TRACE;
break;
}
//rhoPlainLog(szFile, nLine, nSeverity, szModule, szMsg);
}
bool CExtManager::onWndMsg(MSG& oMsg)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
if ( (it->second)->onWndMsg( oMsg ) )
return true;
}
return false;
}
bool CExtManager::onHTMLWndMsg(MSG& oMsg)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
if ( (it->second)->onHTMLWndMsg( oMsg ) )
return true;
}
return false;
}
long CExtManager::OnNavigateTimeout(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnNavigateTimeout( szUrlBeingNavigatedTo, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnSIPState(bool bSIPState)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnSIPState( bSIPState, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnAlertPopup(int nEnum, void* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnAlertPopup( nEnum, pData, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnAuthenticationRequest(int nEnum, void* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnAuthenticationRequest( nEnum, pData, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnGeolocationData(int nEnum, void* pData)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnGeolocationData( nEnum, pData, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnNavigateError(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnNavigateError( szUrlBeingNavigatedTo, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
long CExtManager::OnLicenseError(const wchar_t* szUrlBeingNavigatedTo)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
long lRes = (it->second)->OnLicenseError( szUrlBeingNavigatedTo, makeExtData() );
if ( lRes )
return lRes;
}
return 0;
}
void CExtManager::OnAppActivate(bool bActivate)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->OnAppActivate( bActivate, makeExtData() );
}
}
void CExtManager::OnWindowChanged(LPVOID lparam)
{
for ( HashtablePtr<String, IRhoExtension*>::iterator it = m_hashExtensions.begin(); it != m_hashExtensions.end(); ++it )
{
(it->second)->OnWindowChanged( lparam );
}
}
bool CExtManager::RegisterForMessageCallback(unsigned int iMsgId)
{
//return getAppWindow().getWebKitEngine()->RegisterForMessage(iMsgId);
return true;
}
bool CExtManager::DeRegisterForMessageCallback(unsigned int iMsgId)
{
//return getAppWindow().getWebKitEngine()->DeRegisterForMessage(iMsgId);
return true;
}
//DWORD CExtManager::getProcessId()
//{
//#if !defined(OS_WINDOWS_DESKTOP)
// return 0;//getAppWindow().getWebKitEngine()->GetProcessID();
//#else
// return 0;
//#endif
//}
} //namespace common
} //namespace rho
<|endoftext|> |
<commit_before>/*
* JPetWriter.cpp
*
*
* Created by Karol Stola on 13-09-02.
* Copyright 2013 __MyCompanyName__. All rights reserved.
*
*/
#include "JPetWriter.h"
//TFile* JPetWriter::fFile = NULL;
JPetWriter::JPetWriter(const char* file_name)
: fFileName(file_name, "UPDATE") // string z nazwą pliku
, fFile(fFileName.c_str()) // plik
{
if ( fFile.IsZombie() ){
ERROR("Could not open file to write.");
}
}
bool JPetWriter::Write(const TNamed& obj){
vector<TNamed> wrapper;
wrapper.push_back(obj);
Write(wrapper);
}
void JPetWriter::CloseFile(){
if (fFile.IsOpen() ) fFile.Close();
}
bool JPetWriter::Write( vector<TNamed>& obj) {
if (obj.size() == 0) {
WARNING("Vector passed is empty");
return false;
}
if ( !fFile.IsOpen() ) {
ERROR("Could not write to file. Have you closed it already?");
return false;
}
fFile.cd(fFileName.c_str()); // -> http://root.cern.ch/drupal/content/current-directory
TTree tree;
TNamed& filler = obj[0];
tree.Branch(filler.GetName(), filler.GetName(), &filler);
for (int i = 0; i < obj.size(); i++){
filler = obj[i];
tree.Fill();
}
tree.Write();
return true;
}
JPetWriter::~JPetWriter(){
CloseFile();
}
<commit_msg>usunięcie błędu w writerze<commit_after>/*
* JPetWriter.cpp
*
*
* Created by Karol Stola on 13-09-02.
* Copyright 2013 __MyCompanyName__. All rights reserved.
*
*/
#include "JPetWriter.h"
//TFile* JPetWriter::fFile = NULL;
JPetWriter::JPetWriter(const char* file_name)
: fFileName(file_name) // string z nazwą pliku
, fFile(fFileName.c_str(), "RECREATE") // plik
{
if ( fFile.IsZombie() ){
ERROR("Could not open file to write.");
}
}
bool JPetWriter::Write(const TNamed& obj){
vector<TNamed> wrapper;
wrapper.push_back(obj);
Write(wrapper);
}
void JPetWriter::CloseFile(){
if (fFile.IsOpen() ) fFile.Close();
}
bool JPetWriter::Write( vector<TNamed>& obj) {
if (obj.size() == 0) {
WARNING("Vector passed is empty");
return false;
}
if ( !fFile.IsOpen() ) {
ERROR("Could not write to file. Have you closed it already?");
return false;
}
fFile.cd(fFileName.c_str()); // -> http://root.cern.ch/drupal/content/current-directory
TTree tree;
TNamed& filler = obj[0];
tree.Branch(filler.GetName(), filler.GetName(), &filler);
for (int i = 0; i < obj.size(); i++){
filler = obj[i];
tree.Fill();
}
tree.Write();
return true;
}
JPetWriter::~JPetWriter(){
CloseFile();
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "Steady.h"
#include "FEProblem.h"
#include "Factory.h"
#include "MooseApp.h"
#include "libmesh/equation_systems.h"
template<>
InputParameters validParams<Steady>()
{
return validParams<Executioner>();
}
Steady::Steady(const std::string & name, InputParameters parameters) :
Executioner(name, parameters),
_problem(*parameters.getCheckedPointerParam<FEProblem *>("_fe_problem", "This might happen if you don't have a mesh")),
_time_step(_problem.timeStep()),
_time(_problem.time())
{
_problem.getNonlinearSystem().setDecomposition(_splitting);
if (!_restart_file_base.empty())
_problem.setRestartFile(_restart_file_base);
{
std::string ti_str = "SteadyState";
InputParameters params = _app.getFactory().getValidParams(ti_str);
_problem.addTimeIntegrator(ti_str, "ti", params);
}
}
Steady::~Steady()
{
}
Problem &
Steady::problem()
{
return _problem;
}
void
Steady::init()
{
if (_app.isRecovering())
{
_console << "\nCannot recover steady solves!\nExiting...\n" << std::endl;
return;
}
checkIntegrity();
_problem.initialSetup();
Moose::setup_perf_log.push("Output Initial Condition","Setup");
_problem.outputStep(EXEC_INITIAL);
Moose::setup_perf_log.pop("Output Initial Condition","Setup");
}
void
Steady::execute()
{
if (_app.isRecovering())
return;
preExecute();
// first step in any steady state solve is always 1 (preserving backwards compatibility)
_time_step = 1;
_time = _time_step; // need to keep _time in sync with _time_step to get correct output
#ifdef LIBMESH_ENABLE_AMR
// Define the refinement loop
unsigned int steps = _problem.adaptivity().getSteps();
for (unsigned int r_step=0; r_step<=steps; r_step++)
{
#endif //LIBMESH_ENABLE_AMR
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::PRE_AUX);
preSolve();
_problem.timestepSetup();
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::POST_AUX);
_problem.solve();
postSolve();
_problem.computeUserObjects(EXEC_TIMESTEP_END, UserObjectWarehouse::PRE_AUX);
_problem.onTimestepEnd();
_problem.computeAuxiliaryKernels(EXEC_TIMESTEP_END);
_problem.computeUserObjects(EXEC_TIMESTEP_END, UserObjectWarehouse::POST_AUX);
_problem.computeIndicatorsAndMarkers();
_problem.outputStep(EXEC_TIMESTEP_END);
#ifdef LIBMESH_ENABLE_AMR
if (r_step != steps)
{
_problem.adaptMesh();
}
_time_step++;
_time = _time_step; // need to keep _time in sync with _time_step to get correct output
}
#endif
postExecute();
}
void
Steady::checkIntegrity()
{
// check to make sure that we don't have any time kernels in this simulation (Steady State)
if (_problem.getNonlinearSystem().containsTimeKernel())
mooseError("You have specified time kernels in your steady state simulation");
}
<commit_msg>Making sure that we have symmetry in computing depend UOs in the steady timestep begin case closes #4675<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "Steady.h"
#include "FEProblem.h"
#include "Factory.h"
#include "MooseApp.h"
#include "libmesh/equation_systems.h"
template<>
InputParameters validParams<Steady>()
{
return validParams<Executioner>();
}
Steady::Steady(const std::string & name, InputParameters parameters) :
Executioner(name, parameters),
_problem(*parameters.getCheckedPointerParam<FEProblem *>("_fe_problem", "This might happen if you don't have a mesh")),
_time_step(_problem.timeStep()),
_time(_problem.time())
{
_problem.getNonlinearSystem().setDecomposition(_splitting);
if (!_restart_file_base.empty())
_problem.setRestartFile(_restart_file_base);
{
std::string ti_str = "SteadyState";
InputParameters params = _app.getFactory().getValidParams(ti_str);
_problem.addTimeIntegrator(ti_str, "ti", params);
}
}
Steady::~Steady()
{
}
Problem &
Steady::problem()
{
return _problem;
}
void
Steady::init()
{
if (_app.isRecovering())
{
_console << "\nCannot recover steady solves!\nExiting...\n" << std::endl;
return;
}
checkIntegrity();
_problem.initialSetup();
Moose::setup_perf_log.push("Output Initial Condition","Setup");
_problem.outputStep(EXEC_INITIAL);
Moose::setup_perf_log.pop("Output Initial Condition","Setup");
}
void
Steady::execute()
{
if (_app.isRecovering())
return;
preExecute();
// first step in any steady state solve is always 1 (preserving backwards compatibility)
_time_step = 1;
_time = _time_step; // need to keep _time in sync with _time_step to get correct output
#ifdef LIBMESH_ENABLE_AMR
// Define the refinement loop
unsigned int steps = _problem.adaptivity().getSteps();
for (unsigned int r_step=0; r_step<=steps; r_step++)
{
#endif //LIBMESH_ENABLE_AMR
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::PRE_AUX);
preSolve();
_problem.timestepSetup();
_problem.computeAuxiliaryKernels(EXEC_TIMESTEP_BEGIN);
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::POST_AUX);
_problem.solve();
postSolve();
_problem.computeUserObjects(EXEC_TIMESTEP_END, UserObjectWarehouse::PRE_AUX);
_problem.onTimestepEnd();
_problem.computeAuxiliaryKernels(EXEC_TIMESTEP_END);
_problem.computeUserObjects(EXEC_TIMESTEP_END, UserObjectWarehouse::POST_AUX);
_problem.computeIndicatorsAndMarkers();
_problem.outputStep(EXEC_TIMESTEP_END);
#ifdef LIBMESH_ENABLE_AMR
if (r_step != steps)
{
_problem.adaptMesh();
}
_time_step++;
_time = _time_step; // need to keep _time in sync with _time_step to get correct output
}
#endif
postExecute();
}
void
Steady::checkIntegrity()
{
// check to make sure that we don't have any time kernels in this simulation (Steady State)
if (_problem.getNonlinearSystem().containsTimeKernel())
mooseError("You have specified time kernels in your steady state simulation");
}
<|endoftext|> |
<commit_before>/*
OpenLieroX
INI reader
18-01-2008, by Albert Zeyer
code under LGPL
*/
#include "IniReader.h"
#include "FindFile.h"
#include "Debug.h"
IniReader::KeywordList IniReader::DefaultKeywords;
IniReader::IniReader(const std::string& filename, KeywordList& keywords) : m_filename(filename), m_keywords(keywords) {
if (IniReader::DefaultKeywords.empty()) {
(IniReader::DefaultKeywords)["true"] = true;
(IniReader::DefaultKeywords)["false"] = false;
}
}
IniReader::~IniReader() {}
bool IniReader::Parse() {
FILE* f = OpenGameFile(m_filename, "r");
if(f == NULL)
return false;
bool res = true;
enum ParseState {
S_DEFAULT, S_IGNORERESTLINE, S_PROPNAME, S_PROPVALUE, S_SECTION };
ParseState state = S_DEFAULT;
std::string propname;
std::string section;
std::string value;
while(!feof(f) && !ferror(f)) {
unsigned char c = 0;
if(fread(&c, 1, 1, f) == 0) break;
switch(state) {
case S_DEFAULT:
if(c >= 128) break; // just ignore unicode-stuff when we are in this state (UTF8 bytes at beginning are also handled by this)
else if(isspace(c)) break; // ignore spaces and newlines
else if(c == '#') { state = S_IGNORERESTLINE; /* this is a comment */ break; }
else if(c == '[') { state = S_SECTION; section = ""; break; }
else if(c == '=') {
warnings << "WARNING: \"=\" is not allowed as the first character in a line of " << m_filename << endl;
break; /* ignore */ }
else { state = S_PROPNAME; propname = c; break; }
case S_SECTION:
if(c == ']') {
if( ! OnNewSection(section) ) { res = false; goto parseCleanup; }
state = S_DEFAULT; NewSection(section); break; }
else if(c == '\n') {
warnings << "WARNING: section-name \"" << section << "\" of " << m_filename << " is not closed correctly" << endl;
state = S_DEFAULT; break; }
else if(isspace(c)) {
warnings << "WARNING: section-name \"" << section << "\" of " << m_filename << " contains a space" << endl;
break; /* ignore */ }
else { section += c; break; }
case S_PROPNAME:
if(c == '\n') {
warnings << "WARNING: property \"" << propname << "\" of " << m_filename << " incomplete" << endl;
state = S_DEFAULT; break; }
else if(isspace(c)) break; // just ignore spaces
else if(c == '=') { state = S_PROPVALUE; value = ""; break; }
else { propname += c; break; }
case S_PROPVALUE:
if(c == '\n' || c == '#') {
if( ! OnEntry(section, propname, value) ) { res = false; goto parseCleanup; }
NewEntryInSection(propname, value);
if(c == '#') state = S_IGNORERESTLINE; else state = S_DEFAULT;
break; }
else if(isspace(c) && value == "") break; // ignore heading spaces
else { value += c; break; }
case S_IGNORERESTLINE:
if(c == '\n') state = S_DEFAULT;
break; // ignore everything
}
}
// In case the endline is missing at the end of file, finish the parsing of the last line
if (state == S_PROPVALUE) {
if( ! OnEntry(section, propname, value) ) { res = false; goto parseCleanup; }
NewEntryInSection(propname, value);
}
// DEBUG: dump the file
/*notes << "Dump of " << m_filename << endl;
for (SectionMap::iterator it = m_sections.begin(); it != m_sections.end(); ++it) {
notes << "[" << it->first << "]" << endl;
for (Section::iterator k = it->second.begin(); k != it->second.end(); ++k)
notes << k->first << "=" << k->second << endl;
notes << endl;
}
notes << endl;*/
parseCleanup:
fclose(f);
return res;
}
void IniReader::NewSection(const std::string& name)
{
m_sections[name] = Section();
m_curSection = &m_sections[name];
}
void IniReader::NewEntryInSection(const std::string& name, const std::string& value)
{
if (!m_curSection) {
warnings << "Cannot add item " << name << " to any section, because the current section is unset" << endl;
return;
}
(*m_curSection)[name] = value;
}
bool IniReader::GetString(const std::string& section, const std::string& key, std::string& string) const
{
// Get the section
SectionMap::const_iterator sect = m_sections.find(section);
if (sect == m_sections.end())
return false;
// Get the key=value pair
Section::const_iterator item = sect->second.find(key);
if (item == sect->second.end())
return false;
string = item->second;
return true;
}
bool IniReader::ReadString(const std::string& section, const std::string& key, std::string& value, std::string defaultv) const
{
bool res = GetString(section, key, value);
if (!res)
value = defaultv;
return res;
}
bool IniReader::ReadInteger(const std::string& section, const std::string& key, int *value, int defaultv) const
{
std::string string;
*value = defaultv;
if(!GetString(section, key, string))
return false;
*value = from_string<int>(string);
return true;
}
bool IniReader::ReadFloat(const std::string §ion, const std::string &key, float *value, float defaultv) const
{
std::string string;
*value = defaultv;
if(!GetString(section, key, string))
return false;
*value = (float)atof(string);
return true;
}
bool IniReader::ReadColour(const std::string §ion, const std::string &key, Color &value, const Color &defaultv) const
{
std::string string;
value = defaultv;
if(!GetString(section, key, string))
return false;
value = StrToCol(string);
return true;
}
bool IniReader::ReadIntArray(const std::string §ion, const std::string &key, int *array, int num_items) const
{
std::string string;
if (!GetString(section, key, string))
return false;
std::vector<std::string> arr = explode(string,",");
for (int i=0; i < MIN(num_items,(int)arr.size()); i++) {
TrimSpaces(arr[i]);
array[i] = from_string<int>(arr[i]);
}
return num_items == (int)arr.size();
}
bool IniReader::ReadKeyword(const std::string §ion, const std::string &key, int *value, int defaultv) const
{
std::string string;
*value = defaultv;
if(!GetString(section, key, string))
return false;
// Try and find a keyword with matching keys
KeywordList::const_iterator f = m_keywords.find(string);
if(f != m_keywords.end()) {
//notes << filename << ":" << section << "." << key << ": " << f->first << "(" << string << ") = " << f->second << endl;
*value = f->second;
return true;
}
warnings << m_filename << ":" << section << "." << key << ": '" << string << "' is an unknown keyword" << endl;
return false;
}
bool IniReader::ReadKeyword(const std::string §ion, const std::string &key, bool *value, bool defaultv) const
{
int v = defaultv ? 1 : 0;
bool ret = ReadKeyword(section, key, &v, defaultv ? 1 : 0);
*value = v != 0;
return ret;
}
bool IniReader::ReadKeywordList(const std::string §ion, const std::string &key, int *value, int defaultv) const
{
std::string string;
*value = defaultv;
if (!GetString(section, key, string))
return false;
std::vector<std::string> split = explode(string, ",");
for (std::vector<std::string>::iterator it = split.begin(); it != split.end(); it++) {
TrimSpaces(*it);
KeywordList::const_iterator key = m_keywords.find(*it);
if (key != m_keywords.end())
*value |= key->second;
}
return true;
}
<commit_msg>inireader: ignore \r. this fixes also the game compiler<commit_after>/*
OpenLieroX
INI reader
18-01-2008, by Albert Zeyer
code under LGPL
*/
#include "IniReader.h"
#include "FindFile.h"
#include "Debug.h"
IniReader::KeywordList IniReader::DefaultKeywords;
IniReader::IniReader(const std::string& filename, KeywordList& keywords) : m_filename(filename), m_keywords(keywords) {
if (IniReader::DefaultKeywords.empty()) {
(IniReader::DefaultKeywords)["true"] = true;
(IniReader::DefaultKeywords)["false"] = false;
}
}
IniReader::~IniReader() {}
bool IniReader::Parse() {
FILE* f = OpenGameFile(m_filename, "r");
if(f == NULL)
return false;
bool res = true;
enum ParseState {
S_DEFAULT, S_IGNORERESTLINE, S_PROPNAME, S_PROPVALUE, S_SECTION };
ParseState state = S_DEFAULT;
std::string propname;
std::string section;
std::string value;
while(!feof(f) && !ferror(f)) {
unsigned char c = 0;
if(fread(&c, 1, 1, f) == 0) break;
if(c == '\r') continue; // ignore this
switch(state) {
case S_DEFAULT:
if(c >= 128) break; // just ignore unicode-stuff when we are in this state (UTF8 bytes at beginning are also handled by this)
else if(isspace(c)) break; // ignore spaces and newlines
else if(c == '#') { state = S_IGNORERESTLINE; /* this is a comment */ break; }
else if(c == '[') { state = S_SECTION; section = ""; break; }
else if(c == '=') {
warnings << "WARNING: \"=\" is not allowed as the first character in a line of " << m_filename << endl;
break; /* ignore */ }
else { state = S_PROPNAME; propname = c; break; }
case S_SECTION:
if(c == ']') {
if( ! OnNewSection(section) ) { res = false; goto parseCleanup; }
state = S_DEFAULT; NewSection(section); break; }
else if(c == '\n') {
warnings << "WARNING: section-name \"" << section << "\" of " << m_filename << " is not closed correctly" << endl;
state = S_DEFAULT; break; }
else if(isspace(c)) {
warnings << "WARNING: section-name \"" << section << "\" of " << m_filename << " contains a space" << endl;
break; /* ignore */ }
else { section += c; break; }
case S_PROPNAME:
if(c == '\n') {
warnings << "WARNING: property \"" << propname << "\" of " << m_filename << " incomplete" << endl;
state = S_DEFAULT; break; }
else if(isspace(c)) break; // just ignore spaces
else if(c == '=') { state = S_PROPVALUE; value = ""; break; }
else { propname += c; break; }
case S_PROPVALUE:
if(c == '\n' || c == '#') {
if( ! OnEntry(section, propname, value) ) { res = false; goto parseCleanup; }
NewEntryInSection(propname, value);
if(c == '#') state = S_IGNORERESTLINE; else state = S_DEFAULT;
break; }
else if(isspace(c) && value == "") break; // ignore heading spaces
else { value += c; break; }
case S_IGNORERESTLINE:
if(c == '\n') state = S_DEFAULT;
break; // ignore everything
}
}
// In case the endline is missing at the end of file, finish the parsing of the last line
if (state == S_PROPVALUE) {
if( ! OnEntry(section, propname, value) ) { res = false; goto parseCleanup; }
NewEntryInSection(propname, value);
}
// DEBUG: dump the file
/*notes << "Dump of " << m_filename << endl;
for (SectionMap::iterator it = m_sections.begin(); it != m_sections.end(); ++it) {
notes << "[" << it->first << "]" << endl;
for (Section::iterator k = it->second.begin(); k != it->second.end(); ++k)
notes << k->first << "=" << k->second << endl;
notes << endl;
}
notes << endl;*/
parseCleanup:
fclose(f);
return res;
}
void IniReader::NewSection(const std::string& name)
{
m_sections[name] = Section();
m_curSection = &m_sections[name];
}
void IniReader::NewEntryInSection(const std::string& name, const std::string& value)
{
if (!m_curSection) {
warnings << "Cannot add item " << name << " to any section, because the current section is unset" << endl;
return;
}
(*m_curSection)[name] = value;
}
bool IniReader::GetString(const std::string& section, const std::string& key, std::string& string) const
{
// Get the section
SectionMap::const_iterator sect = m_sections.find(section);
if (sect == m_sections.end())
return false;
// Get the key=value pair
Section::const_iterator item = sect->second.find(key);
if (item == sect->second.end())
return false;
string = item->second;
return true;
}
bool IniReader::ReadString(const std::string& section, const std::string& key, std::string& value, std::string defaultv) const
{
bool res = GetString(section, key, value);
if (!res)
value = defaultv;
return res;
}
bool IniReader::ReadInteger(const std::string& section, const std::string& key, int *value, int defaultv) const
{
std::string string;
*value = defaultv;
if(!GetString(section, key, string))
return false;
*value = from_string<int>(string);
return true;
}
bool IniReader::ReadFloat(const std::string §ion, const std::string &key, float *value, float defaultv) const
{
std::string string;
*value = defaultv;
if(!GetString(section, key, string))
return false;
*value = (float)atof(string);
return true;
}
bool IniReader::ReadColour(const std::string §ion, const std::string &key, Color &value, const Color &defaultv) const
{
std::string string;
value = defaultv;
if(!GetString(section, key, string))
return false;
value = StrToCol(string);
return true;
}
bool IniReader::ReadIntArray(const std::string §ion, const std::string &key, int *array, int num_items) const
{
std::string string;
if (!GetString(section, key, string))
return false;
std::vector<std::string> arr = explode(string,",");
for (int i=0; i < MIN(num_items,(int)arr.size()); i++) {
TrimSpaces(arr[i]);
array[i] = from_string<int>(arr[i]);
}
return num_items == (int)arr.size();
}
bool IniReader::ReadKeyword(const std::string §ion, const std::string &key, int *value, int defaultv) const
{
std::string string;
*value = defaultv;
if(!GetString(section, key, string))
return false;
// Try and find a keyword with matching keys
KeywordList::const_iterator f = m_keywords.find(string);
if(f != m_keywords.end()) {
//notes << filename << ":" << section << "." << key << ": " << f->first << "(" << string << ") = " << f->second << endl;
*value = f->second;
return true;
}
warnings << m_filename << ":" << section << "." << key << ": '" << string << "' is an unknown keyword" << endl;
return false;
}
bool IniReader::ReadKeyword(const std::string §ion, const std::string &key, bool *value, bool defaultv) const
{
int v = defaultv ? 1 : 0;
bool ret = ReadKeyword(section, key, &v, defaultv ? 1 : 0);
*value = v != 0;
return ret;
}
bool IniReader::ReadKeywordList(const std::string §ion, const std::string &key, int *value, int defaultv) const
{
std::string string;
*value = defaultv;
if (!GetString(section, key, string))
return false;
std::vector<std::string> split = explode(string, ",");
for (std::vector<std::string>::iterator it = split.begin(); it != split.end(); it++) {
TrimSpaces(*it);
KeywordList::const_iterator key = m_keywords.find(*it);
if (key != m_keywords.end())
*value |= key->second;
}
return true;
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstdint>
#include <cstring> // for memset
#include <fstream>
#include <iostream>
#include <ostream>
#include <visionaray/swizzle.h>
#include "tga_image.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// TGA header
//
#pragma pack(push, 1)
struct tga_header
{
uint8_t id_length;
uint8_t color_map_type;
uint8_t image_type;
uint16_t color_map_first_entry;
uint16_t color_map_num_entries;
uint8_t color_map_entry_size;
uint16_t x_origin;
uint16_t y_origin;
uint16_t width;
uint16_t height;
uint8_t bits_per_pixel;
uint8_t image_desc;
};
#pragma pack(pop)
//-------------------------------------------------------------------------------------------------
// Helper functions
//
pixel_format map_pixel_depth(uint8_t bits_per_pixel)
{
switch (bits_per_pixel)
{
case 24:
return PF_RGB8;
case 32:
return PF_RGBA8;
default:
return PF_UNSPECIFIED;
}
}
void load_true_color(
uint8_t* dst,
std::ifstream& file,
int stride,
int height
)
{
file.read(reinterpret_cast<char*>(dst), stride * height * sizeof(uint8_t));
}
//-------------------------------------------------------------------------------------------------
// tga_image
//
tga_image::tga_image(std::string const& filename)
{
std::ifstream file(filename, std::ios::in | std::ios::binary);
// Read header
tga_header header;
memset(&header, 0, sizeof(header));
file.seekg (0, file.beg);
file.read(reinterpret_cast<char*>(&header), sizeof(header));
width_ = static_cast<size_t>(header.width);
height_ = static_cast<size_t>(header.height);
format_ = map_pixel_depth(header.bits_per_pixel);
auto stride = header.width * (header.bits_per_pixel / 8);
data_.resize(stride * header.height);
// Read image data
file.seekg(sizeof(header) + header.id_length, file.beg);
switch (header.image_type)
{
default:
std::cerr << "Unsupported TGA image type (" << (int)header.image_type << '\n';
// fall-through
case 0:
// no image data
width_ = 0;
height_ = 0;
format_ = PF_UNSPECIFIED;
data_.resize(0);
break;
case 2:
load_true_color(data_.data(), file, stride, header.height);
break;
}
// Swizzle from BGR(A) to RGB(A)
if (format_ == PF_RGB8)
{
swizzle(
reinterpret_cast<vector<3, unorm<8>>*>(data_.data()),
PF_RGB8,
PF_BGR8,
data_.size() / 3
);
}
else if (format_ == PF_RGBA8)
{
swizzle(
reinterpret_cast<vector<4, unorm<8>>*>(data_.data()),
PF_RGBA8,
PF_BGRA8,
data_.size() / 4
);
}
}
} // visionaray
<commit_msg>Support TGA images with origin at top/left corner<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstdint>
#include <cstring> // for memset
#include <fstream>
#include <iostream>
#include <ostream>
#include <visionaray/swizzle.h>
#include "tga_image.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// TGA header
//
#pragma pack(push, 1)
struct tga_header
{
uint8_t id_length;
uint8_t color_map_type;
uint8_t image_type;
uint16_t color_map_first_entry;
uint16_t color_map_num_entries;
uint8_t color_map_entry_size;
uint16_t x_origin;
uint16_t y_origin;
uint16_t width;
uint16_t height;
uint8_t bits_per_pixel;
uint8_t image_desc;
};
#pragma pack(pop)
//-------------------------------------------------------------------------------------------------
// Helper functions
//
pixel_format map_pixel_depth(uint8_t bits_per_pixel)
{
switch (bits_per_pixel)
{
case 24:
return PF_RGB8;
case 32:
return PF_RGBA8;
default:
return PF_UNSPECIFIED;
}
}
void load_true_color(
uint8_t* dst,
std::ifstream& file,
int stride,
int height,
int y_origin
)
{
if (y_origin == 0)
{
// Origin is bottom/left corner - same as visionaray image format
file.read(reinterpret_cast<char*>(dst), stride * height * sizeof(uint8_t));
}
else if (y_origin == height)
{
// Origin is top/left corner - convert to bottom/left
for (int y = 0; y < height; ++y)
{
auto ptr = dst + (height - 1) * stride - y * stride;
file.read(reinterpret_cast<char*>(ptr), stride * sizeof(uint8_t));
}
}
else
{
std::cerr << "Unsupported TGA image, y-origin ("
<< y_origin << ") is neither bottom nor top\n";
}
}
//-------------------------------------------------------------------------------------------------
// tga_image
//
tga_image::tga_image(std::string const& filename)
{
std::ifstream file(filename, std::ios::in | std::ios::binary);
// Read header
tga_header header;
memset(&header, 0, sizeof(header));
file.seekg (0, file.beg);
file.read(reinterpret_cast<char*>(&header), sizeof(header));
width_ = static_cast<size_t>(header.width);
height_ = static_cast<size_t>(header.height);
format_ = map_pixel_depth(header.bits_per_pixel);
auto stride = header.width * (header.bits_per_pixel / 8);
data_.resize(stride * header.height);
// Read image data
file.seekg(sizeof(header) + header.id_length, file.beg);
switch (header.image_type)
{
default:
std::cerr << "Unsupported TGA image type (" << (int)header.image_type << ")\n";
// fall-through
case 0:
// no image data
width_ = 0;
height_ = 0;
format_ = PF_UNSPECIFIED;
data_.resize(0);
break;
case 2:
load_true_color(data_.data(), file, stride, header.height, header.y_origin);
break;
}
// Swizzle from BGR(A) to RGB(A)
if (format_ == PF_RGB8)
{
swizzle(
reinterpret_cast<vector<3, unorm<8>>*>(data_.data()),
PF_RGB8,
PF_BGR8,
data_.size() / 3
);
}
else if (format_ == PF_RGBA8)
{
swizzle(
reinterpret_cast<vector<4, unorm<8>>*>(data_.data()),
PF_RGBA8,
PF_BGRA8,
data_.size() / 4
);
}
}
} // visionaray
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "PageCoreTests.h"
#include "OgrePaging.h"
CPPUNIT_TEST_SUITE_REGISTRATION( PageCoreTests );
void PageCoreTests::setUp()
{
mRoot = OGRE_NEW Root();
mPageManager = OGRE_NEW PageManager();
mRoot->addResourceLocation("./", "FileSystem");
mSceneMgr = mRoot->createSceneManager(ST_GENERIC);
}
void PageCoreTests::tearDown()
{
OGRE_DELETE mPageManager;
OGRE_DELETE mRoot;
}
void PageCoreTests::testSimpleCreateSaveLoadWorld()
{
String worldName = "MyWorld";
String filename = "myworld.world";
String sectionName1 = "Section1";
String sectionName2 = "Section2";
PagedWorld* world = mPageManager->createWorld(worldName);
PagedWorldSection* section = world->createSection("Grid2D", mSceneMgr, sectionName1);
section = world->createSection("Grid2D", mSceneMgr, sectionName2);
// Create a page
Page* p = section->loadOrCreatePage(Vector3::ZERO);
SimplePageContentCollection* coll = static_cast<SimplePageContentCollection*>(
p->createContentCollection("Simple"));
// manually set page to loaded since we've populated it
p->setLoaded();
world->save(filename);
mPageManager->destroyWorld(world);
world = 0;
world = mPageManager->loadWorld(filename);
CPPUNIT_ASSERT_EQUAL(worldName, world->getName());
CPPUNIT_ASSERT_EQUAL((size_t)2, world->getSectionCount());
section = world->getSection(sectionName1);
CPPUNIT_ASSERT(section != 0);
section = world->getSection(sectionName2);
CPPUNIT_ASSERT(section != 0);
}
<commit_msg>Fix test compile<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "PageCoreTests.h"
#include "OgrePaging.h"
CPPUNIT_TEST_SUITE_REGISTRATION( PageCoreTests );
void PageCoreTests::setUp()
{
mRoot = OGRE_NEW Root();
mPageManager = OGRE_NEW PageManager();
mRoot->addResourceLocation("./", "FileSystem");
mSceneMgr = mRoot->createSceneManager(ST_GENERIC);
}
void PageCoreTests::tearDown()
{
OGRE_DELETE mPageManager;
OGRE_DELETE mRoot;
}
void PageCoreTests::testSimpleCreateSaveLoadWorld()
{
String worldName = "MyWorld";
String filename = "myworld.world";
String sectionName1 = "Section1";
String sectionName2 = "Section2";
PagedWorld* world = mPageManager->createWorld(worldName);
PagedWorldSection* section = world->createSection("Grid2D", mSceneMgr, sectionName1);
section = world->createSection("Grid2D", mSceneMgr, sectionName2);
// Create a page
Page* p = section->loadOrCreatePage(Vector3::ZERO);
SimplePageContentCollection* coll = static_cast<SimplePageContentCollection*>(
p->createContentCollection("Simple"));
world->save(filename);
mPageManager->destroyWorld(world);
world = 0;
world = mPageManager->loadWorld(filename);
CPPUNIT_ASSERT_EQUAL(worldName, world->getName());
CPPUNIT_ASSERT_EQUAL((size_t)2, world->getSectionCount());
section = world->getSection(sectionName1);
CPPUNIT_ASSERT(section != 0);
section = world->getSection(sectionName2);
CPPUNIT_ASSERT(section != 0);
}
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/util/fs.hpp>
#include <mapnik/map.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/debug.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
TEST_CASE("font") {
SECTION("registration") {
try
{
mapnik::logger logger;
mapnik::logger::severity_type original_severity = logger.get_severity();
// grab references to global statics of registered/cached fonts
auto const& global_mapping = mapnik::freetype_engine::get_mapping();
auto const& global_cache = mapnik::freetype_engine::get_cache();
// mapnik.Map object has parallel structure for localized fonts
mapnik::Map m(1,1);
auto const& local_mapping = m.get_font_file_mapping();
auto const& local_cache = m.get_font_memory_cache();
// should be empty to start
REQUIRE( global_mapping.empty() );
REQUIRE( global_cache.empty() );
REQUIRE( local_mapping.empty() );
REQUIRE( local_cache.empty() );
std::string fontdir("fonts/");
REQUIRE( mapnik::util::exists( fontdir ) );
REQUIRE( mapnik::util::is_directory( fontdir ) );
// test map cached fonts
REQUIRE( m.register_fonts(fontdir , true ) );
REQUIRE( m.get_font_file_mapping().size() == 22 );
REQUIRE( m.load_fonts() );
REQUIRE( m.get_font_memory_cache().size() == 22 );
// copy discards memory cache but not file mapping
mapnik::Map m2(m);
REQUIRE( m2.get_font_memory_cache().size() == 0 );
REQUIRE( m2.get_font_file_mapping().size() == 22 );
REQUIRE( m2.load_fonts() );
REQUIRE( m2.get_font_memory_cache().size() == 22 );
// test font-directory from XML
mapnik::Map m3(1,1);
mapnik::load_map_string(m3,"<Map font-directory=\"test/data/fonts/Noto/\"></Map>");
REQUIRE( m3.get_font_memory_cache().size() == 0 );
REQUIRE( m3.load_fonts() );
REQUIRE( m3.get_font_memory_cache().size() == 1 );
std::vector<std::string> face_names;
std::string foo("foo");
// fake directories
REQUIRE( !mapnik::freetype_engine::register_fonts(foo , true ) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 0 );
REQUIRE( !mapnik::freetype_engine::register_fonts(foo) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 0 );
// directories without fonts
// silence warnings here by altering the logging severity
logger.set_severity(mapnik::logger::none);
std::string src("src");
// an empty directory will not return true
// we need to register at least one font and not fail on any
// to return true
REQUIRE( mapnik::freetype_engine::register_font(src) == false );
REQUIRE( mapnik::freetype_engine::register_fonts(src, true) == false );
REQUIRE( mapnik::freetype_engine::face_names().size() == 0 );
// bogus, emtpy file that looks like font
REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/fake.ttf") == false );
REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/fake.ttf") == false );
REQUIRE( mapnik::freetype_engine::face_names().size() == 0 );
REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/intentionally-broken.ttf") == false );
REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/intentionally-broken.ttf") == false );
REQUIRE( mapnik::freetype_engine::face_names().size() == 0 );
// now restore the original severity
logger.set_severity(original_severity);
// single dejavu font in separate location
std::string dejavu_bold_oblique("test/data/fonts/DejaVuSansMono-BoldOblique.ttf");
REQUIRE( mapnik::freetype_engine::register_font(dejavu_bold_oblique) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 1 );
// now, inspect font mapping and confirm the correct 'DejaVu Sans Mono Bold Oblique' is registered
using font_file_mapping = std::map<std::string, std::pair<int,std::string> >;
font_file_mapping const& name2file = mapnik::freetype_engine::get_mapping();
bool found_dejavu = false;
for (auto const& item : name2file)
{
if (item.first == "DejaVu Sans Mono Bold Oblique")
{
found_dejavu = true;
REQUIRE( item.second.first == 0 );
REQUIRE( item.second.second == dejavu_bold_oblique );
}
}
REQUIRE( found_dejavu );
// recurse to find all dejavu fonts
REQUIRE( mapnik::freetype_engine::register_fonts(fontdir, true) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 22 );
// we should have re-registered 'DejaVu Sans Mono Bold Oblique' again,
// but now at a new path
bool found_dejavu2 = false;
for (auto const& item : name2file)
{
if (item.first == "DejaVu Sans Mono Bold Oblique")
{
found_dejavu2 = true;
REQUIRE( item.second.first == 0 );
// path should be different
REQUIRE( item.second.second != dejavu_bold_oblique );
}
}
REQUIRE( found_dejavu2 );
// now that global registry is populated
// now test that a map only loads new fonts
mapnik::Map m4(1,1);
REQUIRE( m4.register_fonts(fontdir , true ) );
REQUIRE( m4.get_font_memory_cache().size() == 0 );
REQUIRE( m4.get_font_file_mapping().size() == 22 );
REQUIRE( !m4.load_fonts() );
REQUIRE( m4.get_font_memory_cache().size() == 0 );
REQUIRE( m4.register_fonts(dejavu_bold_oblique, false) );
REQUIRE( m4.load_fonts() );
REQUIRE( m4.get_font_memory_cache().size() == 1 );
// check that we can correctly read a .ttc containing
// multiple valid faces
// https://github.com/mapnik/mapnik/issues/2274
REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc") );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 24 );
// now blindly register as many system fonts as possible
// the goal here to make sure we don't crash
// linux
mapnik::freetype_engine::register_fonts("/usr/share/fonts/", true);
mapnik::freetype_engine::register_fonts("/usr/local/share/fonts/", true);
// osx
mapnik::freetype_engine::register_fonts("/Library/Fonts/", true);
mapnik::freetype_engine::register_fonts("/System/Library/Fonts/", true);
// windows
mapnik::freetype_engine::register_fonts("C:\\Windows\\Fonts", true);
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() > 22 );
}
catch (std::exception const & ex)
{
std::clog << ex.what() << "\n";
REQUIRE(false);
}
}
}
<commit_msg>update test<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/util/fs.hpp>
#include <mapnik/map.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/debug.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
TEST_CASE("font") {
SECTION("registration") {
try
{
mapnik::logger logger;
mapnik::logger::severity_type original_severity = logger.get_severity();
// grab references to global statics of registered/cached fonts
auto const& global_mapping = mapnik::freetype_engine::get_mapping();
auto const& global_cache = mapnik::freetype_engine::get_cache();
// mapnik.Map object has parallel structure for localized fonts
mapnik::Map m(1,1);
auto const& local_mapping = m.get_font_file_mapping();
auto const& local_cache = m.get_font_memory_cache();
// should be empty to start
REQUIRE( global_mapping.empty() );
REQUIRE( global_cache.empty() );
REQUIRE( local_mapping.empty() );
REQUIRE( local_cache.empty() );
std::string fontdir("fonts/");
REQUIRE( mapnik::util::exists( fontdir ) );
REQUIRE( mapnik::util::is_directory( fontdir ) );
// test map cached fonts
REQUIRE( m.register_fonts(fontdir , true ) );
REQUIRE( m.get_font_file_mapping().size() == 22 );
REQUIRE( m.load_fonts() );
REQUIRE( m.get_font_memory_cache().size() == 22 );
// copy discards memory cache but not file mapping
mapnik::Map m2(m);
REQUIRE( m2.get_font_memory_cache().size() == 0 );
REQUIRE( m2.get_font_file_mapping().size() == 22 );
REQUIRE( m2.load_fonts() );
REQUIRE( m2.get_font_memory_cache().size() == 22 );
// test font-directory from XML
mapnik::Map m3(1,1);
mapnik::load_map_string(m3,"<Map font-directory=\"test/data/fonts/Noto/\"></Map>");
REQUIRE( m3.get_font_memory_cache().size() == 0 );
REQUIRE( m3.load_fonts() );
REQUIRE( m3.get_font_memory_cache().size() == 2 );
std::vector<std::string> face_names;
std::string foo("foo");
// fake directories
REQUIRE( !mapnik::freetype_engine::register_fonts(foo , true ) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 0 );
REQUIRE( !mapnik::freetype_engine::register_fonts(foo) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 0 );
// directories without fonts
// silence warnings here by altering the logging severity
logger.set_severity(mapnik::logger::none);
std::string src("src");
// an empty directory will not return true
// we need to register at least one font and not fail on any
// to return true
REQUIRE( mapnik::freetype_engine::register_font(src) == false );
REQUIRE( mapnik::freetype_engine::register_fonts(src, true) == false );
REQUIRE( mapnik::freetype_engine::face_names().size() == 0 );
// bogus, emtpy file that looks like font
REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/fake.ttf") == false );
REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/fake.ttf") == false );
REQUIRE( mapnik::freetype_engine::face_names().size() == 0 );
REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/intentionally-broken.ttf") == false );
REQUIRE( mapnik::freetype_engine::register_fonts("test/data/fonts/intentionally-broken.ttf") == false );
REQUIRE( mapnik::freetype_engine::face_names().size() == 0 );
// now restore the original severity
logger.set_severity(original_severity);
// single dejavu font in separate location
std::string dejavu_bold_oblique("test/data/fonts/DejaVuSansMono-BoldOblique.ttf");
REQUIRE( mapnik::freetype_engine::register_font(dejavu_bold_oblique) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 1 );
// now, inspect font mapping and confirm the correct 'DejaVu Sans Mono Bold Oblique' is registered
using font_file_mapping = std::map<std::string, std::pair<int,std::string> >;
font_file_mapping const& name2file = mapnik::freetype_engine::get_mapping();
bool found_dejavu = false;
for (auto const& item : name2file)
{
if (item.first == "DejaVu Sans Mono Bold Oblique")
{
found_dejavu = true;
REQUIRE( item.second.first == 0 );
REQUIRE( item.second.second == dejavu_bold_oblique );
}
}
REQUIRE( found_dejavu );
// recurse to find all dejavu fonts
REQUIRE( mapnik::freetype_engine::register_fonts(fontdir, true) );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 22 );
// we should have re-registered 'DejaVu Sans Mono Bold Oblique' again,
// but now at a new path
bool found_dejavu2 = false;
for (auto const& item : name2file)
{
if (item.first == "DejaVu Sans Mono Bold Oblique")
{
found_dejavu2 = true;
REQUIRE( item.second.first == 0 );
// path should be different
REQUIRE( item.second.second != dejavu_bold_oblique );
}
}
REQUIRE( found_dejavu2 );
// now that global registry is populated
// now test that a map only loads new fonts
mapnik::Map m4(1,1);
REQUIRE( m4.register_fonts(fontdir , true ) );
REQUIRE( m4.get_font_memory_cache().size() == 0 );
REQUIRE( m4.get_font_file_mapping().size() == 22 );
REQUIRE( !m4.load_fonts() );
REQUIRE( m4.get_font_memory_cache().size() == 0 );
REQUIRE( m4.register_fonts(dejavu_bold_oblique, false) );
REQUIRE( m4.load_fonts() );
REQUIRE( m4.get_font_memory_cache().size() == 1 );
// check that we can correctly read a .ttc containing
// multiple valid faces
// https://github.com/mapnik/mapnik/issues/2274
REQUIRE( mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc") );
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() == 24 );
// now blindly register as many system fonts as possible
// the goal here to make sure we don't crash
// linux
mapnik::freetype_engine::register_fonts("/usr/share/fonts/", true);
mapnik::freetype_engine::register_fonts("/usr/local/share/fonts/", true);
// osx
mapnik::freetype_engine::register_fonts("/Library/Fonts/", true);
mapnik::freetype_engine::register_fonts("/System/Library/Fonts/", true);
// windows
mapnik::freetype_engine::register_fonts("C:\\Windows\\Fonts", true);
face_names = mapnik::freetype_engine::face_names();
REQUIRE( face_names.size() > 22 );
}
catch (std::exception const & ex)
{
std::clog << ex.what() << "\n";
REQUIRE(false);
}
}
}
<|endoftext|> |
<commit_before>#include "SLAImportJob.hpp"
#include "libslic3r/Format/SL1.hpp"
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/Plater.hpp"
#include "slic3r/GUI/GUI_ObjectList.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/PresetBundle.hpp"
#include <wx/dialog.h>
#include <wx/stattext.h>
#include <wx/combobox.h>
#include <wx/filename.h>
#include <wx/filepicker.h>
namespace Slic3r { namespace GUI {
enum class Sel { modelAndProfile, profileOnly, modelOnly};
class ImportDlg: public wxDialog {
wxFilePickerCtrl *m_filepicker;
wxComboBox *m_import_dropdown, *m_quality_dropdown;
public:
ImportDlg(Plater *plater)
: wxDialog{plater, wxID_ANY, "Import SLA archive"}
{
auto szvert = new wxBoxSizer{wxVERTICAL};
auto szfilepck = new wxBoxSizer{wxHORIZONTAL};
m_filepicker = new wxFilePickerCtrl(this, wxID_ANY,
from_u8(wxGetApp().app_config->get_last_dir()), _(L("Choose SLA archive:")),
"SL1 archive files (*.sl1, *.sl1s, *.zip)|*.sl1;*.SL1;*.sl1s;*.SL1S;*.zip;*.ZIP",
wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE | wxFD_OPEN | wxFD_FILE_MUST_EXIST);
szfilepck->Add(new wxStaticText(this, wxID_ANY, _L("Import file") + ": "), 0, wxALIGN_CENTER);
szfilepck->Add(m_filepicker, 1);
szvert->Add(szfilepck, 0, wxALL | wxEXPAND, 5);
auto szchoices = new wxBoxSizer{wxHORIZONTAL};
static const std::vector<wxString> inp_choices = {
_(L("Import model and profile")),
_(L("Import profile only")),
_(L("Import model only"))
};
m_import_dropdown = new wxComboBox(
this, wxID_ANY, inp_choices[0], wxDefaultPosition, wxDefaultSize,
inp_choices.size(), inp_choices.data(), wxCB_READONLY | wxCB_DROPDOWN);
szchoices->Add(m_import_dropdown);
szchoices->Add(new wxStaticText(this, wxID_ANY, _L("Quality") + ": "), 0, wxALIGN_CENTER | wxALL, 5);
static const std::vector<wxString> qual_choices = {
_(L("Accurate")),
_(L("Balanced")),
_(L("Quick"))
};
m_quality_dropdown = new wxComboBox(
this, wxID_ANY, qual_choices[0], wxDefaultPosition, wxDefaultSize,
qual_choices.size(), qual_choices.data(), wxCB_READONLY | wxCB_DROPDOWN);
szchoices->Add(m_quality_dropdown);
m_import_dropdown->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent &) {
if (get_selection() == Sel::profileOnly)
m_quality_dropdown->Disable();
else m_quality_dropdown->Enable();
});
szvert->Add(szchoices, 0, wxALL, 5);
szvert->AddStretchSpacer(1);
auto szbtn = new wxBoxSizer(wxHORIZONTAL);
szbtn->Add(new wxButton{this, wxID_CANCEL});
szbtn->Add(new wxButton{this, wxID_OK});
szvert->Add(szbtn, 0, wxALIGN_RIGHT | wxALL, 5);
SetSizerAndFit(szvert);
}
Sel get_selection() const
{
int sel = m_import_dropdown->GetSelection();
return Sel(std::min(int(Sel::modelOnly), std::max(0, sel)));
}
Vec2i get_marchsq_windowsize() const
{
enum { Accurate, Balanced, Fast};
switch(m_quality_dropdown->GetSelection())
{
case Fast: return {8, 8};
case Balanced: return {4, 4};
default:
case Accurate:
return {2, 2};
}
}
wxString get_path() const
{
return m_filepicker->GetPath();
}
};
class SLAImportJob::priv {
public:
Plater *plater;
Sel sel = Sel::modelAndProfile;
indexed_triangle_set mesh;
DynamicPrintConfig profile;
wxString path;
Vec2i win = {2, 2};
std::string err;
priv(Plater *plt) : plater{plt} {}
};
SLAImportJob::SLAImportJob(std::shared_ptr<ProgressIndicator> pri, Plater *plater)
: PlaterJob{std::move(pri), plater}, p{std::make_unique<priv>(plater)}
{}
SLAImportJob::~SLAImportJob() = default;
void SLAImportJob::process()
{
auto progr = [this](int s) {
if (s < 100)
update_status(int(s), _(L("Importing SLA archive")));
return !was_canceled();
};
if (p->path.empty()) return;
std::string path = p->path.ToUTF8().data();
try {
switch (p->sel) {
case Sel::modelAndProfile:
p->config_substitutions = import_sla_archive(path, p->win, p->mesh, p->profile, progr);
break;
case Sel::modelOnly:
p->config_substitutions = import_sla_archive(path, p->win, p->mesh, progr);
break;
case Sel::profileOnly:
p->config_substitutions = import_sla_archive(path, p->profile);
break;
}
} catch (std::exception &ex) {
p->err = ex.what();
}
update_status(100, was_canceled() ? _(L("Importing canceled.")) :
_(L("Importing done.")));
}
void SLAImportJob::reset()
{
p->sel = Sel::modelAndProfile;
p->mesh = {};
p->profile = {};
p->win = {2, 2};
p->path.Clear();
}
void SLAImportJob::prepare()
{
reset();
ImportDlg dlg{p->plater};
if (dlg.ShowModal() == wxID_OK) {
auto path = dlg.get_path();
auto nm = wxFileName(path);
p->path = !nm.Exists(wxFILE_EXISTS_REGULAR) ? "" : nm.GetFullPath();
p->sel = dlg.get_selection();
p->win = dlg.get_marchsq_windowsize();
p->config_substitutions.clear();
} else {
p->path = "";
}
}
void SLAImportJob::finalize()
{
// Ignore the arrange result if aborted.
if (was_canceled()) return;
if (!p->err.empty()) {
show_error(p->plater, p->err);
p->err = "";
return;
}
std::string name = wxFileName(p->path).GetName().ToUTF8().data();
if (!p->profile.empty()) {
const ModelObjectPtrs& objects = p->plater->model().objects;
for (auto object : objects)
if (object->volumes.size() > 1)
{
Slic3r::GUI::show_info(nullptr,
_(L("You cannot load SLA project with a multi-part object on the bed")) + "\n\n" +
_(L("Please check your object list before preset changing.")),
_(L("Attention!")) );
return;
}
DynamicPrintConfig config = {};
config.apply(SLAFullPrintConfig::defaults());
config += std::move(p->profile);
wxGetApp().preset_bundle->load_config_model(name, std::move(config));
wxGetApp().load_current_presets();
}
if (!p->mesh.empty()) {
bool is_centered = false;
p->plater->sidebar().obj_list()->load_mesh_object(TriangleMesh{p->mesh},
name, is_centered);
}
if (! p->config_substitutions.empty())
show_substitutions_info(p->config_substitutions, p->path.ToUTF8().data());
reset();
}
}} // namespace Slic3r::GUI
<commit_msg>Ammended the previous commit (SL1 / SL1S in file picker)<commit_after>#include "SLAImportJob.hpp"
#include "libslic3r/Format/SL1.hpp"
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/Plater.hpp"
#include "slic3r/GUI/GUI_ObjectList.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/PresetBundle.hpp"
#include <wx/dialog.h>
#include <wx/stattext.h>
#include <wx/combobox.h>
#include <wx/filename.h>
#include <wx/filepicker.h>
namespace Slic3r { namespace GUI {
enum class Sel { modelAndProfile, profileOnly, modelOnly};
class ImportDlg: public wxDialog {
wxFilePickerCtrl *m_filepicker;
wxComboBox *m_import_dropdown, *m_quality_dropdown;
public:
ImportDlg(Plater *plater)
: wxDialog{plater, wxID_ANY, "Import SLA archive"}
{
auto szvert = new wxBoxSizer{wxVERTICAL};
auto szfilepck = new wxBoxSizer{wxHORIZONTAL};
m_filepicker = new wxFilePickerCtrl(this, wxID_ANY,
from_u8(wxGetApp().app_config->get_last_dir()), _(L("Choose SLA archive:")),
"SL1 / SL1S archive files (*.sl1, *.sl1s, *.zip)|*.sl1;*.SL1;*.sl1s;*.SL1S;*.zip;*.ZIP",
wxDefaultPosition, wxDefaultSize, wxFLP_DEFAULT_STYLE | wxFD_OPEN | wxFD_FILE_MUST_EXIST);
szfilepck->Add(new wxStaticText(this, wxID_ANY, _L("Import file") + ": "), 0, wxALIGN_CENTER);
szfilepck->Add(m_filepicker, 1);
szvert->Add(szfilepck, 0, wxALL | wxEXPAND, 5);
auto szchoices = new wxBoxSizer{wxHORIZONTAL};
static const std::vector<wxString> inp_choices = {
_(L("Import model and profile")),
_(L("Import profile only")),
_(L("Import model only"))
};
m_import_dropdown = new wxComboBox(
this, wxID_ANY, inp_choices[0], wxDefaultPosition, wxDefaultSize,
inp_choices.size(), inp_choices.data(), wxCB_READONLY | wxCB_DROPDOWN);
szchoices->Add(m_import_dropdown);
szchoices->Add(new wxStaticText(this, wxID_ANY, _L("Quality") + ": "), 0, wxALIGN_CENTER | wxALL, 5);
static const std::vector<wxString> qual_choices = {
_(L("Accurate")),
_(L("Balanced")),
_(L("Quick"))
};
m_quality_dropdown = new wxComboBox(
this, wxID_ANY, qual_choices[0], wxDefaultPosition, wxDefaultSize,
qual_choices.size(), qual_choices.data(), wxCB_READONLY | wxCB_DROPDOWN);
szchoices->Add(m_quality_dropdown);
m_import_dropdown->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent &) {
if (get_selection() == Sel::profileOnly)
m_quality_dropdown->Disable();
else m_quality_dropdown->Enable();
});
szvert->Add(szchoices, 0, wxALL, 5);
szvert->AddStretchSpacer(1);
auto szbtn = new wxBoxSizer(wxHORIZONTAL);
szbtn->Add(new wxButton{this, wxID_CANCEL});
szbtn->Add(new wxButton{this, wxID_OK});
szvert->Add(szbtn, 0, wxALIGN_RIGHT | wxALL, 5);
SetSizerAndFit(szvert);
}
Sel get_selection() const
{
int sel = m_import_dropdown->GetSelection();
return Sel(std::min(int(Sel::modelOnly), std::max(0, sel)));
}
Vec2i get_marchsq_windowsize() const
{
enum { Accurate, Balanced, Fast};
switch(m_quality_dropdown->GetSelection())
{
case Fast: return {8, 8};
case Balanced: return {4, 4};
default:
case Accurate:
return {2, 2};
}
}
wxString get_path() const
{
return m_filepicker->GetPath();
}
};
class SLAImportJob::priv {
public:
Plater *plater;
Sel sel = Sel::modelAndProfile;
indexed_triangle_set mesh;
DynamicPrintConfig profile;
wxString path;
Vec2i win = {2, 2};
std::string err;
priv(Plater *plt) : plater{plt} {}
};
SLAImportJob::SLAImportJob(std::shared_ptr<ProgressIndicator> pri, Plater *plater)
: PlaterJob{std::move(pri), plater}, p{std::make_unique<priv>(plater)}
{}
SLAImportJob::~SLAImportJob() = default;
void SLAImportJob::process()
{
auto progr = [this](int s) {
if (s < 100)
update_status(int(s), _(L("Importing SLA archive")));
return !was_canceled();
};
if (p->path.empty()) return;
std::string path = p->path.ToUTF8().data();
try {
switch (p->sel) {
case Sel::modelAndProfile:
p->config_substitutions = import_sla_archive(path, p->win, p->mesh, p->profile, progr);
break;
case Sel::modelOnly:
p->config_substitutions = import_sla_archive(path, p->win, p->mesh, progr);
break;
case Sel::profileOnly:
p->config_substitutions = import_sla_archive(path, p->profile);
break;
}
} catch (std::exception &ex) {
p->err = ex.what();
}
update_status(100, was_canceled() ? _(L("Importing canceled.")) :
_(L("Importing done.")));
}
void SLAImportJob::reset()
{
p->sel = Sel::modelAndProfile;
p->mesh = {};
p->profile = {};
p->win = {2, 2};
p->path.Clear();
}
void SLAImportJob::prepare()
{
reset();
ImportDlg dlg{p->plater};
if (dlg.ShowModal() == wxID_OK) {
auto path = dlg.get_path();
auto nm = wxFileName(path);
p->path = !nm.Exists(wxFILE_EXISTS_REGULAR) ? "" : nm.GetFullPath();
p->sel = dlg.get_selection();
p->win = dlg.get_marchsq_windowsize();
p->config_substitutions.clear();
} else {
p->path = "";
}
}
void SLAImportJob::finalize()
{
// Ignore the arrange result if aborted.
if (was_canceled()) return;
if (!p->err.empty()) {
show_error(p->plater, p->err);
p->err = "";
return;
}
std::string name = wxFileName(p->path).GetName().ToUTF8().data();
if (!p->profile.empty()) {
const ModelObjectPtrs& objects = p->plater->model().objects;
for (auto object : objects)
if (object->volumes.size() > 1)
{
Slic3r::GUI::show_info(nullptr,
_(L("You cannot load SLA project with a multi-part object on the bed")) + "\n\n" +
_(L("Please check your object list before preset changing.")),
_(L("Attention!")) );
return;
}
DynamicPrintConfig config = {};
config.apply(SLAFullPrintConfig::defaults());
config += std::move(p->profile);
wxGetApp().preset_bundle->load_config_model(name, std::move(config));
wxGetApp().load_current_presets();
}
if (!p->mesh.empty()) {
bool is_centered = false;
p->plater->sidebar().obj_list()->load_mesh_object(TriangleMesh{p->mesh},
name, is_centered);
}
if (! p->config_substitutions.empty())
show_substitutions_info(p->config_substitutions, p->path.ToUTF8().data());
reset();
}
}} // namespace Slic3r::GUI
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2012 by INdT
*
* This program 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
* 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 Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
* @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
*/
#include "scriptbehavior.h"
#include <QtQml/QQmlExpression>
ScriptBehavior::ScriptBehavior(QObject *parent)
: Behavior(parent)
, m_expression(0)
{
}
void ScriptBehavior::update(const int &delta) {
Q_UNUSED(delta);
if (m_expression) {
m_expression->evaluate();
}
}
QQmlScriptString ScriptBehavior::script() const
{
return m_script;
}
void ScriptBehavior::setScript(const QQmlScriptString &script)
{
if (m_script.stringLiteral() != script.stringLiteral()) {
m_script = script;
if (m_expression)
delete m_expression;
m_expression = new QQmlExpression(m_script);
emit scriptChanged();
}
}
<commit_msg>Don't compare QQmlScriptString before setting it. There seems to be a bug in Qt when getting the scriptString from QML that breaks comparison. Setting it does actually work though. This fixes issue #22.<commit_after>/**
* Copyright (C) 2012 by INdT
*
* This program 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
* 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 Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
* @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
*/
#include "scriptbehavior.h"
#include <QtQml/QQmlExpression>
ScriptBehavior::ScriptBehavior(QObject *parent)
: Behavior(parent)
, m_expression(0)
{
}
void ScriptBehavior::update(const int &delta) {
Q_UNUSED(delta);
if (m_expression) {
m_expression->evaluate();
}
}
QQmlScriptString ScriptBehavior::script() const
{
return m_script;
}
void ScriptBehavior::setScript(const QQmlScriptString &script)
{
m_script = script;
if (m_expression)
delete m_expression;
m_expression = new QQmlExpression(m_script);
emit scriptChanged();
}
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_PMAP_HPP_
#define CONCURRENCY_PMAP_HPP_
#include "arch/runtime/coroutines.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/semaphore.hpp"
template <class callable_t, class value_t>
struct pmap_runner_one_arg_t {
value_t i;
const callable_t *c;
int *outstanding;
cond_t *to_signal;
co_semaphore_t *semaphore;
pmap_runner_one_arg_t(value_t _i, const callable_t *_c, int *_outstanding,
cond_t *_to_signal, co_semaphore_t *_semaphore = NULL)
: i(_i), c(_c), outstanding(_outstanding), to_signal(_to_signal),
semaphore(_semaphore) { }
void operator()() {
(*c)(i);
(*outstanding)--;
if (semaphore != NULL) {
semaphore->unlock();
}
if (*outstanding == 0) {
to_signal->pulse();
}
}
};
template <class callable_t, class value_t>
void spawn_pmap_runner_one_arg(value_t i, const callable_t *c, int *outstanding, cond_t *to_signal) {
coro_t::spawn_now_dangerously(pmap_runner_one_arg_t<callable_t, value_t>(i, c, outstanding, to_signal));
}
template <class callable_t>
void pmap(int begin, int end, const callable_t &c) {
guarantee(begin >= 0); // We don't want `end - begin` to overflow, do we?
guarantee(begin <= end);
if (begin == end) {
return;
}
cond_t cond;
int outstanding = (end - begin);
for (int i = begin; i < end - 1; ++i) {
coro_t::spawn_now_dangerously(pmap_runner_one_arg_t<callable_t, int>(i, &c, &outstanding, &cond));
}
pmap_runner_one_arg_t<callable_t, int> runner(end - 1, &c, &outstanding, &cond);
runner();
cond.wait();
}
template <class callable_t>
void pmap(int count, const callable_t &c) {
pmap(0, count, c);
}
template <class callable_t, class iterator_t>
void pmap(iterator_t start, iterator_t end, const callable_t &c) {
cond_t cond;
int outstanding = 1;
while (start != end) {
++outstanding;
spawn_pmap_runner_one_arg(*start, &c, &outstanding, &cond);
++start;
}
--outstanding;
if (outstanding) {
cond.wait();
}
}
template <class callable_t>
void throttled_pmap(int begin, int end, const callable_t &c, int64_t capacity) {
guarantee(capacity > 0);
guarantee(begin >= 0); // We don't want `end - begin` to overflow, do we?
guarantee(begin <= end);
if (begin == end) {
return;
}
static_semaphore_t semaphore(capacity);
cond_t cond;
int outstanding = (end - begin);
for (int i = begin; i < end - 1; ++i) {
semaphore.co_lock();
coro_t::spawn_now_dangerously(
pmap_runner_one_arg_t<callable_t, int>(i, &c, &outstanding, &cond,
&semaphore));
}
semaphore.co_lock();
pmap_runner_one_arg_t<callable_t, int> runner(end - 1, &c, &outstanding, &cond,
&semaphore);
runner();
cond.wait();
}
template <class callable_t>
void throttled_pmap(int count, const callable_t &c, int64_t capacity) {
throttled_pmap(0, count, c, capacity);
}
#endif /* CONCURRENCY_PMAP_HPP_ */
<commit_msg>Made throttled_pmap not use co_semaphore_t.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_PMAP_HPP_
#define CONCURRENCY_PMAP_HPP_
#include "arch/runtime/coroutines.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/semaphore.hpp"
template <class callable_t, class value_t>
struct pmap_runner_one_arg_t {
value_t i;
const callable_t *c;
int *outstanding;
cond_t *to_signal;
static_semaphore_t *semaphore;
pmap_runner_one_arg_t(value_t _i, const callable_t *_c, int *_outstanding,
cond_t *_to_signal, static_semaphore_t *_semaphore = NULL)
: i(_i), c(_c), outstanding(_outstanding), to_signal(_to_signal),
semaphore(_semaphore) { }
void operator()() {
(*c)(i);
(*outstanding)--;
if (semaphore != NULL) {
semaphore->unlock();
}
if (*outstanding == 0) {
to_signal->pulse();
}
}
};
template <class callable_t, class value_t>
void spawn_pmap_runner_one_arg(value_t i, const callable_t *c, int *outstanding, cond_t *to_signal) {
coro_t::spawn_now_dangerously(pmap_runner_one_arg_t<callable_t, value_t>(i, c, outstanding, to_signal));
}
template <class callable_t>
void pmap(int begin, int end, const callable_t &c) {
guarantee(begin >= 0); // We don't want `end - begin` to overflow, do we?
guarantee(begin <= end);
if (begin == end) {
return;
}
cond_t cond;
int outstanding = (end - begin);
for (int i = begin; i < end - 1; ++i) {
coro_t::spawn_now_dangerously(pmap_runner_one_arg_t<callable_t, int>(i, &c, &outstanding, &cond));
}
pmap_runner_one_arg_t<callable_t, int> runner(end - 1, &c, &outstanding, &cond);
runner();
cond.wait();
}
template <class callable_t>
void pmap(int count, const callable_t &c) {
pmap(0, count, c);
}
template <class callable_t, class iterator_t>
void pmap(iterator_t start, iterator_t end, const callable_t &c) {
cond_t cond;
int outstanding = 1;
while (start != end) {
++outstanding;
spawn_pmap_runner_one_arg(*start, &c, &outstanding, &cond);
++start;
}
--outstanding;
if (outstanding) {
cond.wait();
}
}
template <class callable_t>
void throttled_pmap(int begin, int end, const callable_t &c, int64_t capacity) {
guarantee(capacity > 0);
guarantee(begin >= 0); // We don't want `end - begin` to overflow, do we?
guarantee(begin <= end);
if (begin == end) {
return;
}
static_semaphore_t semaphore(capacity);
cond_t cond;
int outstanding = (end - begin);
for (int i = begin; i < end - 1; ++i) {
semaphore.co_lock();
coro_t::spawn_now_dangerously(
pmap_runner_one_arg_t<callable_t, int>(i, &c, &outstanding, &cond,
&semaphore));
}
semaphore.co_lock();
pmap_runner_one_arg_t<callable_t, int> runner(end - 1, &c, &outstanding, &cond,
&semaphore);
runner();
cond.wait();
}
template <class callable_t>
void throttled_pmap(int count, const callable_t &c, int64_t capacity) {
throttled_pmap(0, count, c, capacity);
}
#endif /* CONCURRENCY_PMAP_HPP_ */
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 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 <bitcoin/bitcoin/config/authority.hpp>
#include <cstdint>
#include <string>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/regex.hpp>
#include <bitcoin/bitcoin/formats/base16.hpp>
#include <bitcoin/bitcoin/primitives.hpp>
#include <bitcoin/bitcoin/utility/assert.hpp>
#include <bitcoin/bitcoin/utility/string.hpp>
namespace libbitcoin {
namespace config {
using namespace boost;
using namespace boost::asio;
using namespace boost::program_options;
using boost::format;
// host: [2001:db8::2] or 2001:db8::2 or 1.2.240.1
// returns: [2001:db8::2] or [2001:db8::2] or 1.2.240.1
static std::string to_host_name(const std::string& host)
{
if (host.find(":") == std::string::npos || host.find("[") == 0)
return host;
const auto hostname = format("[%1%]") % host;
return hostname.str();
}
// host: [2001:db8::2] or 2001:db8::2 or 1.2.240.1
static std::string to_authority(const std::string& host, uint16_t port)
{
std::stringstream authority;
authority << to_host_name(host);
if (port > 0)
authority << ":" << port;
return authority.str();
}
static std::string to_ipv6(const std::string& ipv4_address)
{
return std::string("::ffff:") + ipv4_address;
}
static ip::address_v6 to_ipv6(const ip::address_v4& ipv4_address)
{
// Create an IPv6 mapped IPv4 address via serialization.
const auto ipv6 = to_ipv6(ipv4_address.to_string());
return ip::address_v6::from_string(ipv6);
}
static ip::address_v6 to_ipv6(const ip::address& ip_address)
{
if (ip_address.is_v6())
return ip_address.to_v6();
BITCOIN_ASSERT_MSG(ip_address.is_v4(),
"The address must be either IPv4 or IPv6.");
return to_ipv6(ip_address.to_v4());
}
static std::string to_ipv4_hostname(const ip::address& ip_address)
{
// std::regex requires gcc 4.9, so we are using boost::regex for now.
static const regex regular("::ffff:([0-9\\.]+)");
const auto address = ip_address.to_string();
sregex_iterator it(address.begin(), address.end(), regular), end;
if (it == end)
return "";
const auto& match = *it;
return match[1];
}
static std::string to_ipv6_hostname(const ip::address& ip_address)
{
// IPv6 URLs use a bracketed IPv6 address, see rfc2732.
const auto hostname = format("[%1%]") % to_ipv6(ip_address);
return hostname.str();
}
authority::authority()
: port_(0)
{
}
authority::authority(const authority& other)
: authority(other.ip_, other.port_)
{
}
// authority: [2001:db8::2]:port or 1.2.240.1:port
authority::authority(const std::string& authority)
{
std::stringstream(authority) >> *this;
}
// This is the format returned from peers on the bitcoin network.
authority::authority(const network_address_type& net)
: authority(net.ip, net.port)
{
}
authority::authority(const ip_address_type& ip, uint16_t port)
: ip_(ip::address_v6(ip)), port_(port)
{
}
// host: [2001:db8::2] or 2001:db8::2 or 1.2.240.1
authority::authority(const std::string& host, uint16_t port)
: authority(to_authority(host, port))
{
}
authority::authority(const ip::address& ip, uint16_t port)
: ip_(to_ipv6(ip)), port_(port)
{
}
authority::authority(const ip::tcp::endpoint& endpoint)
: authority(endpoint.address(), endpoint.port())
{
}
ip_address_type authority::ip() const
{
return ip_.to_bytes();
}
uint16_t authority::port() const
{
return port_;
}
std::string authority::to_hostname() const
{
auto ipv4_hostname = to_ipv4_hostname(ip_);
return ipv4_hostname.empty() ? to_ipv6_hostname(ip_) : ipv4_hostname;
}
network_address_type authority::to_network_address() const
{
static constexpr uint32_t services = 0;
static constexpr uint64_t timestamp = 0;
const network_address_type network_address
{
timestamp, services, ip(), port(),
};
return network_address;
}
std::string authority::to_string() const
{
std::stringstream value;
value << *this;
return value.str();
}
bool authority::operator==(const authority& other) const
{
return port() == other.port() && ip() == other.ip();
}
bool authority::operator!=(const authority& other) const
{
return !(*this == other);
}
std::istream& operator>>(std::istream& input, authority& argument)
{
std::string value;
input >> value;
// std::regex requires gcc 4.9, so we are using boost::regex for now.
static const regex regular(
"^(([0-9\\.]+)|\\[([0-9a-f:\\.]+)])(:([0-9]{1,5}))?$");
sregex_iterator it(value.begin(), value.end(), regular), end;
if (it == end)
{
BOOST_THROW_EXCEPTION(invalid_option_value(value));
}
const auto& match = *it;
std::string port(match[5]);
std::string ip_address(match[3]);
if (ip_address.empty())
ip_address = to_ipv6(match[2]);
try
{
argument.ip_ = ip::address_v6::from_string(ip_address);
argument.port_ = port.empty() ? 0 : lexical_cast<uint16_t>(port);
}
catch (const boost::exception&)
{
BOOST_THROW_EXCEPTION(invalid_option_value(value));
}
return input;
}
std::ostream& operator<<(std::ostream& output, const authority& argument)
{
output << to_authority(argument.to_hostname(), argument.port());
return output;
}
} // namespace config
} // namespace libbitcoin
<commit_msg>Explicitly convert boost::ip::address_v6 to/from bc::ip_address_type.<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 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 <bitcoin/bitcoin/config/authority.hpp>
#include <cstdint>
#include <string>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/regex.hpp>
#include <bitcoin/bitcoin/formats/base16.hpp>
#include <bitcoin/bitcoin/primitives.hpp>
#include <bitcoin/bitcoin/utility/assert.hpp>
#include <bitcoin/bitcoin/utility/string.hpp>
namespace libbitcoin {
namespace config {
using namespace boost;
using namespace boost::asio;
using namespace boost::program_options;
using boost::format;
// host: [2001:db8::2] or 2001:db8::2 or 1.2.240.1
// returns: [2001:db8::2] or [2001:db8::2] or 1.2.240.1
static std::string to_host_name(const std::string& host)
{
if (host.find(":") == std::string::npos || host.find("[") == 0)
return host;
const auto hostname = format("[%1%]") % host;
return hostname.str();
}
// host: [2001:db8::2] or 2001:db8::2 or 1.2.240.1
static std::string to_authority(const std::string& host, uint16_t port)
{
std::stringstream authority;
authority << to_host_name(host);
if (port > 0)
authority << ":" << port;
return authority.str();
}
static std::string to_ipv6(const std::string& ipv4_address)
{
return std::string("::ffff:") + ipv4_address;
}
static ip::address_v6 to_ipv6(const ip::address_v4& ipv4_address)
{
// Create an IPv6 mapped IPv4 address via serialization.
const auto ipv6 = to_ipv6(ipv4_address.to_string());
return ip::address_v6::from_string(ipv6);
}
static ip::address_v6 to_ipv6(const ip::address& ip_address)
{
if (ip_address.is_v6())
return ip_address.to_v6();
BITCOIN_ASSERT_MSG(ip_address.is_v4(),
"The address must be either IPv4 or IPv6.");
return to_ipv6(ip_address.to_v4());
}
static std::string to_ipv4_hostname(const ip::address& ip_address)
{
// std::regex requires gcc 4.9, so we are using boost::regex for now.
static const regex regular("::ffff:([0-9\\.]+)");
const auto address = ip_address.to_string();
sregex_iterator it(address.begin(), address.end(), regular), end;
if (it == end)
return "";
const auto& match = *it;
return match[1];
}
static std::string to_ipv6_hostname(const ip::address& ip_address)
{
// IPv6 URLs use a bracketed IPv6 address, see rfc2732.
const auto hostname = format("[%1%]") % to_ipv6(ip_address);
return hostname.str();
}
authority::authority()
: port_(0)
{
}
authority::authority(const authority& other)
: authority(other.ip_, other.port_)
{
}
// authority: [2001:db8::2]:port or 1.2.240.1:port
authority::authority(const std::string& authority)
{
std::stringstream(authority) >> *this;
}
// This is the format returned from peers on the bitcoin network.
authority::authority(const network_address_type& net)
: authority(net.ip, net.port)
{
}
static ip::address_v6 to_boost_address(const ip_address_type& in)
{
ip::address_v6::bytes_type bytes;
BITCOIN_ASSERT(bytes.size() == in.size());
std::copy(in.begin(), in.end(), bytes.begin());
const ip::address_v6 out(bytes);
return out;
}
static ip_address_type to_bc_address(const ip::address_v6& in)
{
ip_address_type out;
const auto bytes = in.to_bytes();
BITCOIN_ASSERT(bytes.size() == out.size());
std::copy(bytes.begin(), bytes.end(), out.begin());
return out;
}
authority::authority(const ip_address_type& ip, uint16_t port)
: ip_(to_boost_address(ip)), port_(port)
{
}
// host: [2001:db8::2] or 2001:db8::2 or 1.2.240.1
authority::authority(const std::string& host, uint16_t port)
: authority(to_authority(host, port))
{
}
authority::authority(const ip::address& ip, uint16_t port)
: ip_(to_ipv6(ip)), port_(port)
{
}
authority::authority(const ip::tcp::endpoint& endpoint)
: authority(endpoint.address(), endpoint.port())
{
}
ip_address_type authority::ip() const
{
return to_bc_address(ip_);
}
uint16_t authority::port() const
{
return port_;
}
std::string authority::to_hostname() const
{
auto ipv4_hostname = to_ipv4_hostname(ip_);
return ipv4_hostname.empty() ? to_ipv6_hostname(ip_) : ipv4_hostname;
}
network_address_type authority::to_network_address() const
{
static constexpr uint32_t services = 0;
static constexpr uint64_t timestamp = 0;
const network_address_type network_address
{
timestamp, services, ip(), port(),
};
return network_address;
}
std::string authority::to_string() const
{
std::stringstream value;
value << *this;
return value.str();
}
bool authority::operator==(const authority& other) const
{
return port() == other.port() && ip() == other.ip();
}
bool authority::operator!=(const authority& other) const
{
return !(*this == other);
}
std::istream& operator>>(std::istream& input, authority& argument)
{
std::string value;
input >> value;
// std::regex requires gcc 4.9, so we are using boost::regex for now.
static const regex regular(
"^(([0-9\\.]+)|\\[([0-9a-f:\\.]+)])(:([0-9]{1,5}))?$");
sregex_iterator it(value.begin(), value.end(), regular), end;
if (it == end)
{
BOOST_THROW_EXCEPTION(invalid_option_value(value));
}
const auto& match = *it;
std::string port(match[5]);
std::string ip_address(match[3]);
if (ip_address.empty())
ip_address = to_ipv6(match[2]);
try
{
argument.ip_ = ip::address_v6::from_string(ip_address);
argument.port_ = port.empty() ? 0 : lexical_cast<uint16_t>(port);
}
catch (const boost::exception&)
{
BOOST_THROW_EXCEPTION(invalid_option_value(value));
}
return input;
}
std::ostream& operator<<(std::ostream& output, const authority& argument)
{
output << to_authority(argument.to_hostname(), argument.port());
return output;
}
} // namespace config
} // namespace libbitcoin
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
//#include <codecvt>
//#include <cstddef>
#include <locale>
#include <string>
#include <iomanip>
#include <ctime>
#include "cp-neural.h"
using std::wcout; using std::wstring;
using std::cerr; using std::vector;
class Text {
private:
bool isinit=false;
bool readDataFile(string inputfile) {
std::wifstream txtfile(inputfile, std::ios::binary);
if (!txtfile.is_open()) {
return false;
}
txtfile.imbue(std::locale("en_US.UTF8"));
wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),
std::istreambuf_iterator<wchar_t>());
txtfile.close();
text=ttext;
filename=inputfile;
return true;
}
public:
wstring text;
string filename;
std::map<wchar_t,int> freq;
std::map<wchar_t,int> w2v;
std::map<int,wchar_t> v2w;
Text(string filename) {
if (readDataFile(filename)) {
for (auto wc : text) {
freq[wc]++;
}
int it=0;
for (auto wc : freq) {
w2v[wc.first]=it;
v2w[it]=wc.first;
++it;
}
isinit=true;
cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl;
}
}
~Text() {
}
bool isInit() {
return isinit;
}
int vocsize() {
if (!isinit) return 0;
return v2w.size();
}
wstring sample(int len) {
int p=std::rand()%(text.size()-len);
return text.substr(p,len);
}
};
int main(int argc, char *argv[]) {
std::setlocale (LC_ALL, "");
wcout << L"Rnn-Readär" << std::endl;
bool allOk=true;
if (argc!=2) {
cerr << "rnnreader <path-to-text-file>" << endl;
exit(-1);
}
Text txt(argv[1]);
if (!txt.isInit()) {
cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl;
exit(-1);
}
wcout << L"Text size: " << txt.text.size() << endl;
wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl;
/* for (auto f : txt.freq) {
int c=(int)f.first;
wstring wc(1,f.first);
wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl;
}
*/
Color::Modifier red(Color::FG_RED);
Color::Modifier green(Color::FG_GREEN);
Color::Modifier def(Color::FG_DEFAULT);
int T=30;
int N=txt.text.size() / (T+1);
cerr << N << " Max datassets" << endl;
MatrixN Xr(N,T);
MatrixN yr(N,T);
wstring chunk,chunky;
int n=0;
for (int i=0; i<N; i++) {
wstring smp = txt.sample(T+1);
chunk=smp.substr(0,T);
chunky=smp.substr(1,T);
for (int t=0; t<T; t++) {
Xr(i,t)=txt.w2v[chunk[t]];
yr(i,t)=txt.w2v[chunky[t]];
}
++n;
}
int maxN = 100000;
if (n>maxN) n=maxN;
int n1=n*0.9;
int dn=(n-n1)/2;
if (n1+2*dn > n) {
cerr << "Math doesn't work out." << endl;
}
cerr << n1 << " datasets" << endl;
/* MatrixN X(n1,T);
MatrixN y(n1,T);
MatrixN Xv(dn,T);
MatrixN yv(dn,T);
MatrixN Xt(dn,T);
MatrixN yt(dn,T);
*/
MatrixN X=Xr.block(0,0,n1,T);
MatrixN y=yr.block(0,0,n1,T);
MatrixN Xv=Xr.block(n1,0,dn,T);
MatrixN yv=yr.block(n1,0,dn,T);
MatrixN Xt=Xr.block(n1+dn,0,dn,T);
MatrixN yt=yr.block(n1+dn,0,dn,T);
std::srand(std::time(0));
cpInitCompute("Rnnreader");
registerLayers();
LayerBlock lb(R"({"name":"rnnreader","init":"normal"})"_json);
int VS=txt.vocsize();
int H=128;
int BS=64;
float clip=2.0;
//int D=64;
// CpParams cp0;
// cp0.setPar("inputShape",vector<int>{T});
// cp0.setPar("V",VS);
// cp0.setPar("D",D);
// cp0.setPar("clip",clip);
// cp0.setPar("init",(string)"orthonormal");
// lb.addLayer("WordEmbedding","WE0",cp0,{"input"});
string rnntype="LSTM"; // or "RNN"
cerr << "RNN-type: " << rnntype << endl;
json j0;
string oName{"OH0"};
j0["inputShape"]=vector<int>{T};
j0["V"]=VS;
lb.addLayer("OneHot",oName,j0,{"input"});
int layer_depth=2;
string nName;
json j1;
j1["inputShape"]=vector<int>{VS,T};
j1["N"]=BS;
j1["H"]=H;
j1["forgetgateinitones"]=false;
j1["clip"]=clip;
for (auto l=0; l<layer_depth; l++) {
nName="lstm"+std::to_string(l);
lb.addLayer(rnntype,nName,j1,{oName});
oName=nName;
}
json j10;
j10["inputShape"]=vector<int>{H,T};
j10["M"]=VS;
lb.addLayer("TemporalAffine","af1",j10,{oName});
json j11;
j11["inputShape"]=vector<int>{VS,T};
lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"});
if (!lb.checkTopology(true)) {
allOk=false;
cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl;
} else {
cerr << green << "Topology-check for LayerBlock: ok." << def << endl;
}
//json jc;
//lb.getLayerConfiguration(jc);
//cerr << jc.dump(4) << endl;
// preseverstates no longer necessary for training!
json jo(R"({"verbose":true,"shuffle":false,"preservestates":false,"epsilon":1e-8})"_json);
jo["learning_rate"]=(floatN)1e-3; //2.2e-2);
floatN dep=2.0;
floatN sep=0.0;
jo["epochs"]=(floatN)dep;
jo["batch_size"]=BS;
for (int i=0; i<10000; i++) {
jo["startepoch"]=(floatN)sep;
t_cppl states;
t_cppl statesv;
states["y"] = new MatrixN(y);
statesv["y"] = new MatrixN(yv);
floatN cAcc=lb.train(X, &states, Xv, &statesv, "Adam", jo);
cppl_delete(&states);
cppl_delete(&statesv);
sep+=dep;
int pos=rand() % 1000 + 5000;
wstring instr=txt.text.substr(pos,T);
MatrixN xg(1,T);
for (int i=0; i<T; i++) {
xg(0,i)=txt.w2v[instr[i]];
}
wstring sout{};
Layer* plstm0=lb.layerMap["lstm0"];
t_cppl statesg{};
plstm0->genZeroStates(&statesg, 1);
for (int g=0; g<1000; g++) {
t_cppl cache{};
MatrixN probst=lb.forward(xg,&cache, &statesg);
MatrixN probsd=MatrixN(T,VS);
for (int t=0; t<T; t++) {
for (int v=0; v<VS; v++) {
probsd(t,v)=probst(0,t*VS+v);
}
}
int li=-1;
for (int t=0; t<T; t++) {
vector<floatN> probs(VS);
vector<floatN> index(VS);
for (int v=0; v<VS; v++) {
probs[v]=probsd(t,v);
index[v]=v;
}
li=(int)index[randomChoice(index, probs)];
//wchar_t cw=txt.v2w[li];
//wcout << cw;
}
//wcout << endl;
cppl_delete(&cache);
for (int t=0; t<T-1; t++) {
xg(0,t)=xg(0,t+1);
}
xg(0,T-1)=li;
sout += txt.v2w[li];
}
wcout << "output: " << sout << endl;
cppl_delete(&statesg);
}
cpExitCompute();
}
<commit_msg>stricter clipping<commit_after>#include <iostream>
#include <fstream>
//#include <codecvt>
//#include <cstddef>
#include <locale>
#include <string>
#include <iomanip>
#include <ctime>
#include "cp-neural.h"
using std::wcout; using std::wstring;
using std::cerr; using std::vector;
class Text {
private:
bool isinit=false;
bool readDataFile(string inputfile) {
std::wifstream txtfile(inputfile, std::ios::binary);
if (!txtfile.is_open()) {
return false;
}
txtfile.imbue(std::locale("en_US.UTF8"));
wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),
std::istreambuf_iterator<wchar_t>());
txtfile.close();
text=ttext;
filename=inputfile;
return true;
}
public:
wstring text;
string filename;
std::map<wchar_t,int> freq;
std::map<wchar_t,int> w2v;
std::map<int,wchar_t> v2w;
Text(string filename) {
if (readDataFile(filename)) {
for (auto wc : text) {
freq[wc]++;
}
int it=0;
for (auto wc : freq) {
w2v[wc.first]=it;
v2w[it]=wc.first;
++it;
}
isinit=true;
cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl;
}
}
~Text() {
}
bool isInit() {
return isinit;
}
int vocsize() {
if (!isinit) return 0;
return v2w.size();
}
wstring sample(int len) {
int p=std::rand()%(text.size()-len);
return text.substr(p,len);
}
};
int main(int argc, char *argv[]) {
std::setlocale (LC_ALL, "");
wcout << L"Rnn-Readär" << std::endl;
bool allOk=true;
if (argc!=2) {
cerr << "rnnreader <path-to-text-file>" << endl;
exit(-1);
}
Text txt(argv[1]);
if (!txt.isInit()) {
cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl;
exit(-1);
}
wcout << L"Text size: " << txt.text.size() << endl;
wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl;
/* for (auto f : txt.freq) {
int c=(int)f.first;
wstring wc(1,f.first);
wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl;
}
*/
Color::Modifier red(Color::FG_RED);
Color::Modifier green(Color::FG_GREEN);
Color::Modifier def(Color::FG_DEFAULT);
int T=30;
int N=txt.text.size() / (T+1);
cerr << N << " Max datassets" << endl;
MatrixN Xr(N,T);
MatrixN yr(N,T);
wstring chunk,chunky;
int n=0;
for (int i=0; i<N; i++) {
wstring smp = txt.sample(T+1);
chunk=smp.substr(0,T);
chunky=smp.substr(1,T);
for (int t=0; t<T; t++) {
Xr(i,t)=txt.w2v[chunk[t]];
yr(i,t)=txt.w2v[chunky[t]];
}
++n;
}
int maxN = 100000;
if (n>maxN) n=maxN;
int n1=n*0.9;
int dn=(n-n1)/2;
if (n1+2*dn > n) {
cerr << "Math doesn't work out." << endl;
}
cerr << n1 << " datasets" << endl;
/* MatrixN X(n1,T);
MatrixN y(n1,T);
MatrixN Xv(dn,T);
MatrixN yv(dn,T);
MatrixN Xt(dn,T);
MatrixN yt(dn,T);
*/
MatrixN X=Xr.block(0,0,n1,T);
MatrixN y=yr.block(0,0,n1,T);
MatrixN Xv=Xr.block(n1,0,dn,T);
MatrixN yv=yr.block(n1,0,dn,T);
MatrixN Xt=Xr.block(n1+dn,0,dn,T);
MatrixN yt=yr.block(n1+dn,0,dn,T);
std::srand(std::time(0));
cpInitCompute("Rnnreader");
registerLayers();
LayerBlock lb(R"({"name":"rnnreader","init":"normal","initfactor":0.01})"_json);
int VS=txt.vocsize();
int H=128;
int BS=64;
float clip=2.0;
//int D=64;
// CpParams cp0;
// cp0.setPar("inputShape",vector<int>{T});
// cp0.setPar("V",VS);
// cp0.setPar("D",D);
// cp0.setPar("clip",clip);
// cp0.setPar("init",(string)"orthonormal");
// lb.addLayer("WordEmbedding","WE0",cp0,{"input"});
string rnntype="LSTM"; // or "RNN"
cerr << "RNN-type: " << rnntype << endl;
json j0;
string oName{"OH0"};
j0["inputShape"]=vector<int>{T};
j0["V"]=VS;
lb.addLayer("OneHot",oName,j0,{"input"});
int layer_depth=2;
string nName;
json j1;
j1["inputShape"]=vector<int>{VS,T};
j1["N"]=BS;
j1["H"]=H;
j1["forgetgateinitones"]=false;
j1["clip"]=clip;
for (auto l=0; l<layer_depth; l++) {
nName="lstm"+std::to_string(l);
lb.addLayer(rnntype,nName,j1,{oName});
oName=nName;
}
json j10;
j10["inputShape"]=vector<int>{H,T};
j10["M"]=VS;
lb.addLayer("TemporalAffine","af1",j10,{oName});
json j11;
j11["inputShape"]=vector<int>{VS,T};
lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"});
if (!lb.checkTopology(true)) {
allOk=false;
cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl;
} else {
cerr << green << "Topology-check for LayerBlock: ok." << def << endl;
}
//json jc;
//lb.getLayerConfiguration(jc);
//cerr << jc.dump(4) << endl;
// preseverstates no longer necessary for training!
json jo(R"({"verbose":true,"shuffle":false,"preservestates":false,"epsilon":1e-8})"_json);
jo["learning_rate"]=(floatN)1e-3; //2.2e-2);
floatN dep=2.0;
floatN sep=0.0;
jo["epochs"]=(floatN)dep;
jo["batch_size"]=BS;
for (int i=0; i<10000; i++) {
jo["startepoch"]=(floatN)sep;
t_cppl states;
t_cppl statesv;
states["y"] = new MatrixN(y);
statesv["y"] = new MatrixN(yv);
floatN cAcc=lb.train(X, &states, Xv, &statesv, "Adam", jo);
cppl_delete(&states);
cppl_delete(&statesv);
sep+=dep;
int pos=rand() % 1000 + 5000;
wstring instr=txt.text.substr(pos,T);
MatrixN xg(1,T);
for (int i=0; i<T; i++) {
xg(0,i)=txt.w2v[instr[i]];
}
wstring sout{};
Layer* plstm0=lb.layerMap["lstm0"];
t_cppl statesg{};
plstm0->genZeroStates(&statesg, 1);
for (int g=0; g<1000; g++) {
t_cppl cache{};
MatrixN probst=lb.forward(xg,&cache, &statesg);
MatrixN probsd=MatrixN(T,VS);
for (int t=0; t<T; t++) {
for (int v=0; v<VS; v++) {
probsd(t,v)=probst(0,t*VS+v);
}
}
int li=-1;
for (int t=0; t<T; t++) {
vector<floatN> probs(VS);
vector<floatN> index(VS);
for (int v=0; v<VS; v++) {
probs[v]=probsd(t,v);
index[v]=v;
}
li=(int)index[randomChoice(index, probs)];
//wchar_t cw=txt.v2w[li];
//wcout << cw;
}
//wcout << endl;
cppl_delete(&cache);
for (int t=0; t<T-1; t++) {
xg(0,t)=xg(0,t+1);
}
xg(0,T-1)=li;
sout += txt.v2w[li];
}
wcout << "output: " << sout << endl;
cppl_delete(&statesg);
}
cpExitCompute();
}
<|endoftext|> |
<commit_before>/*
* DynamicHyperbolicGenerator.cpp
*
* Created on: 29.07.2014
* Author: moritzl
*/
#include <cmath>
#include "DynamicHyperbolicGenerator.h"
#include "HyperbolicGenerator.h"
#include "../geometric/HyperbolicSpace.h"
using std::vector;
namespace NetworKit {
DynamicHyperbolicGenerator::DynamicHyperbolicGenerator() {
// TODO Auto-generated constructor stub
}
DynamicHyperbolicGenerator::DynamicHyperbolicGenerator(count n, double initialFactor, double alpha, double stretch, double moveEachStep, double factorgrowth, double moveDistance) {
nodes = n;
currentfactor = initialFactor;
this->alpha = alpha;
this->stretch = stretch;
this->moveEachStep = moveEachStep;
this->factorgrowth = factorgrowth;
this->moveDistance = moveDistance;
this->initialized = false;
}
DynamicHyperbolicGenerator::DynamicHyperbolicGenerator(vector<double> &angles, vector<double> &radii, double R, double initialFactor, double moveEachStep, double factorgrowth, double moveDistance) {
this->angles = angles;
this->radii = radii;
this->nodes = angles.size();
assert(radii.size() == nodes);
double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);
quad = Quadtree<index>(r);
currentfactor = initialFactor;
this->alpha = 1;//not needed any more
this->stretch = 1;//not needed any more
this->moveEachStep = moveEachStep;
this->factorgrowth = factorgrowth;
this->moveDistance = moveDistance;
this->initialized = true;
for (index i = 0; i < nodes; i++) {
assert(radii[i] < r);
quad.addContent(i, angles[i], radii[i]);
}
INFO("Filled Quadtree");
}
DynamicHyperbolicGenerator::~DynamicHyperbolicGenerator() {
// TODO Auto-generated destructor stub
}
void DynamicHyperbolicGenerator::initializeQuadTree() {
if (initialized) return;
else initialized = true;
double R = stretch*acosh((double)nodes/(2*M_PI)+1);
angles.resize(nodes);
radii.resize(nodes);
double rad_nom = (cosh(R)-1);
double rad_denom = (cosh(R)+1);
double r = sqrt(rad_nom/rad_denom);
quad = Quadtree<index>(r);
HyperbolicSpace::fillPoints(&angles, &radii, stretch, alpha);
INFO("Generated Points");
for (index i = 0; i < nodes; i++) {
assert(radii[i] < R);
quad.addContent(i, angles[i], radii[i]);
}
INFO("Filled Quadtree");
}
Graph DynamicHyperbolicGenerator::getGraph() {
if (!initialized) initializeQuadTree();//this is horribly expensive, since it constructs a new Quadtree
double R = stretch*acosh((double)nodes/(2*M_PI)+1);
double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);
/**
* The next call is unnecessarily expensive, since it constructs a new QuadTree.
* Reduces code duplication, though.
*/
return HyperbolicGenerator::generate(&angles, &radii, r, currentfactor*R);
}
std::vector<GraphEvent> DynamicHyperbolicGenerator::generate(count nSteps) {
if (!initialized) initializeQuadTree();
assert(quad.size() == nodes);
vector<GraphEvent> result;
double R = stretch*acosh((double)nodes/(2*M_PI)+1);
for (index step = 0; step < nSteps; step++) {
count oldStreamMarker = result.size();
assert(factorgrowth == 0 || moveEachStep == 0 || moveDistance == 0);
if (factorgrowth != 0) {
//nodes are stationary, growing factors
double newfactor = currentfactor + factorgrowth;
/**
* most efficient way: get all neighbours in the beginning, sort them by hyperbolic distance, move along edge array. TODO: implement
*/
#pragma omp parallel for
for (index i = 0; i < nodes; i++) {
assert(R*newfactor > R*currentfactor);
vector<index> oldset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor);
//we only add new edges, don't remove any. The order of the points should be the same
vector<index> newset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*newfactor);
assert(newset.size() >= oldset.size());
std::sort(oldset.begin(), oldset.end());
std::sort(newset.begin(), newset.end());
vector<index> difference(newset.size());
auto it = std::set_difference(newset.begin(), newset.end(), oldset.begin(), oldset.end(), difference.begin());
difference.resize(it - difference.begin());
#pragma omp critical
{
for (auto edge : difference) {
if (i < edge) {
result.emplace_back(GraphEvent::EDGE_ADDITION, i, edge);
}
}
}
}
currentfactor = newfactor;
}
else {
vector<index> toWiggle;
vector<vector<index> > oldNeighbours;
//TODO: One could parallelize this.
for (index i = 0; i < nodes; i++) {
if (Aux::Random::real(1) < moveEachStep) {
toWiggle.push_back(i);
oldNeighbours.push_back(quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor));
}
}
//#pragma omp parallel for
for (index j = 0; j < toWiggle.size(); j++) {
//wiggle this node!
double hyperbolicRadius = HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[toWiggle[j]]);
//angular movement
double maxcdf = cosh(R);
double mincdf = 1;
double currcdf = cosh(hyperbolicRadius);
double offset = moveEachStep*50;
double random = Aux::Random::real(currcdf-offset, currcdf+offset);
if (random > maxcdf) {
random -= 2*(random - maxcdf);
}
if (random < mincdf) {
random += 2*(mincdf - random);
}
double newradius = acosh(random)/alpha;
//assert(abs(newradius - hyperbolicRadius) < moveEachStep);
if (newradius == R) newradius = std::nextafter(newradius, std::numeric_limits<double>::lowest());
assert(newradius < R);
assert(newradius >= 0);
double angleMovement = Aux::Random::real(-moveEachStep/hyperbolicRadius, moveEachStep/hyperbolicRadius);
double newphi = angles[toWiggle[j]] + angleMovement;
if (newphi < 0) newphi += (floor(-newphi/(2*M_PI))+1)*2*M_PI;
if (newphi > 2*M_PI) newphi -= floor(newphi/(2*M_PI))*2*M_PI;
//bounce off the boundary
newradius = HyperbolicSpace::hyperbolicRadiusToEuclidean(newradius);
if (newradius >= HyperbolicSpace::hyperbolicRadiusToEuclidean(R)) newradius = std::nextafter(newradius, std::numeric_limits<double>::lowest());
//#pragma omp critical (quadtree)
{
bool removed = quad.removeContent(toWiggle[j], angles[toWiggle[j]], radii[toWiggle[j]]);
assert(removed);
angles[toWiggle[j]] = newphi;
radii[toWiggle[j]] = newradius;
quad.addContent(toWiggle[j], newphi, newradius);
}
}
//now get the new edges and see what changed
#pragma omp parallel for
for (index j = 0; j < toWiggle.size(); j++) {
vector<index> newNeighbours = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[toWiggle[j]], radii[toWiggle[j]]), R*currentfactor);
std::sort(oldNeighbours[j].begin(), oldNeighbours[j].end());
std::sort(newNeighbours.begin(), newNeighbours.end());
vector<index> newEdges(newNeighbours.size());
auto it = std::set_difference(newNeighbours.begin(), newNeighbours.end(), oldNeighbours[j].begin(), oldNeighbours[j].end(), newEdges.begin());
newEdges.erase(it, newEdges.end());//trim empty space
vector<index> brokenEdges(oldNeighbours[j].size() - (newNeighbours.size() - newEdges.size()));//this should be the number of broken edges
it = std::set_difference(oldNeighbours[j].begin(), oldNeighbours[j].end(), newNeighbours.begin(), newNeighbours.end(), brokenEdges.begin());
assert(it == brokenEdges.end());
#pragma omp critical
{
for (index edge : newEdges) {
result.emplace_back(GraphEvent::EDGE_ADDITION, toWiggle[j], edge);
}
for (index edge : brokenEdges) {
result.emplace_back(GraphEvent::EDGE_REMOVAL, toWiggle[j], edge);
}
}
}
//make sure no duplicates happen
for (auto it = result.begin()+oldStreamMarker; it < result.end(); it++) {
if (it->u > it->v) std::swap(it->u, it->v);
}
std::sort(result.begin()+oldStreamMarker, result.end(), GraphEvent::compare);
auto end = std::unique(result.begin()+oldStreamMarker, result.end(), GraphEvent::equal);
result.erase(end, result.end());
}
result.push_back(GraphEvent(GraphEvent::TIME_STEP));
}
return result;
}
} /* namespace NetworKit */
<commit_msg>added comments, moved comparison out of critical section<commit_after>/*
* DynamicHyperbolicGenerator.cpp
*
* Created on: 29.07.2014
* Author: moritzl
*/
#include <cmath>
#include "DynamicHyperbolicGenerator.h"
#include "HyperbolicGenerator.h"
#include "../geometric/HyperbolicSpace.h"
using std::vector;
namespace NetworKit {
DynamicHyperbolicGenerator::DynamicHyperbolicGenerator() {
// TODO Auto-generated constructor stub
}
DynamicHyperbolicGenerator::DynamicHyperbolicGenerator(count n, double initialFactor, double alpha, double stretch, double moveEachStep, double factorgrowth, double moveDistance) {
nodes = n;
currentfactor = initialFactor;
this->alpha = alpha;
this->stretch = stretch;
this->moveEachStep = moveEachStep;
this->factorgrowth = factorgrowth;
this->moveDistance = moveDistance;
this->initialized = false;
}
DynamicHyperbolicGenerator::DynamicHyperbolicGenerator(vector<double> &angles, vector<double> &radii, double R, double initialFactor, double moveEachStep, double factorgrowth, double moveDistance) {
this->angles = angles;
this->radii = radii;
this->nodes = angles.size();
assert(radii.size() == nodes);
double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);
quad = Quadtree<index>(r);
currentfactor = initialFactor;
this->alpha = 1;//not needed any more
this->stretch = 1;//not needed any more
this->moveEachStep = moveEachStep;
this->factorgrowth = factorgrowth;
this->moveDistance = moveDistance;
this->initialized = true;
for (index i = 0; i < nodes; i++) {
assert(radii[i] < r);
quad.addContent(i, angles[i], radii[i]);
}
INFO("Filled Quadtree");
}
DynamicHyperbolicGenerator::~DynamicHyperbolicGenerator() {
// TODO Auto-generated destructor stub
}
void DynamicHyperbolicGenerator::initializeQuadTree() {
if (initialized) return;
else initialized = true;
double R = stretch*acosh((double)nodes/(2*M_PI)+1);
angles.resize(nodes);
radii.resize(nodes);
double rad_nom = (cosh(R)-1);
double rad_denom = (cosh(R)+1);
double r = sqrt(rad_nom/rad_denom);
quad = Quadtree<index>(r);
HyperbolicSpace::fillPoints(&angles, &radii, stretch, alpha);
INFO("Generated Points");
for (index i = 0; i < nodes; i++) {
assert(radii[i] < R);
quad.addContent(i, angles[i], radii[i]);
}
INFO("Filled Quadtree");
}
Graph DynamicHyperbolicGenerator::getGraph() {
if (!initialized) initializeQuadTree();//this is horribly expensive, since it constructs a new Quadtree
double R = stretch*acosh((double)nodes/(2*M_PI)+1);
double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);
/**
* The next call is unnecessarily expensive, since it constructs a new QuadTree.
* Reduces code duplication, though.
*/
return HyperbolicGenerator::generate(&angles, &radii, r, currentfactor*R);
}
std::vector<GraphEvent> DynamicHyperbolicGenerator::generate(count nSteps) {
if (!initialized) initializeQuadTree();
assert(quad.size() == nodes);
vector<GraphEvent> result;
double R = stretch*acosh((double)nodes/(2*M_PI)+1);
double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);
for (index step = 0; step < nSteps; step++) {
count oldStreamMarker = result.size();
assert(factorgrowth == 0 || moveEachStep == 0 || moveDistance == 0);
if (factorgrowth != 0) {
//nodes are stationary, growing factors
double newfactor = currentfactor + factorgrowth;
/**
* TODO: get all neighbours in the beginning, sort them by hyperbolic distance, move along edge array.
*/
#pragma omp parallel for
for (index i = 0; i < nodes; i++) {
assert(R*newfactor > R*currentfactor);
vector<index> oldset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor);
//we only add new edges, don't remove any. The order of the points should be the same
vector<index> newset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*newfactor);
assert(newset.size() >= oldset.size());
std::sort(oldset.begin(), oldset.end());
std::sort(newset.begin(), newset.end());
vector<index> difference(newset.size());
//get new edges
auto it = std::set_difference(newset.begin(), newset.end(), oldset.begin(), oldset.end(), difference.begin());
//keep only those pointing to higher node indices, we don't want any multiedges
it = std::remove_if(difference.begin(), it, [i](index edge){return i >= edge;});
difference.resize(it - difference.begin());
#pragma omp critical
{
for (auto edge : difference) {
result.emplace_back(GraphEvent::EDGE_ADDITION, i, edge);
}
}
}
currentfactor = newfactor;
}
else {
vector<index> toWiggle;
vector<vector<index> > oldNeighbours;
//TODO: One could parallelize this.
for (index i = 0; i < nodes; i++) {
if (Aux::Random::real(1) < moveEachStep) {
toWiggle.push_back(i);
oldNeighbours.push_back(quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor));
}
}
/**
* Tried to parallelize this, didn't bring any benefit.
* Not surprising, since most of the work - manipulating the QuadTree - needs to be done in a critical section
*/
for (index j = 0; j < toWiggle.size(); j++) {
//wiggle this node!
double hyperbolicRadius = HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[toWiggle[j]]);
//angular movement
double maxcdf = cosh(R);
double mincdf = 1;
double currcdf = cosh(hyperbolicRadius);
double offset = moveEachStep*50;
double random = Aux::Random::real(currcdf-offset, currcdf+offset);
if (random > maxcdf) {
random -= 2*(random - maxcdf);
}
if (random < mincdf) {
random += 2*(mincdf - random);
}
double newradius = acosh(random)/alpha;
//assert(abs(newradius - hyperbolicRadius) < moveEachStep);
if (newradius == R) newradius = std::nextafter(newradius, std::numeric_limits<double>::lowest());
assert(newradius < R);
assert(newradius >= 0);
double angleMovement = Aux::Random::real(-moveEachStep/hyperbolicRadius, moveEachStep/hyperbolicRadius);
double newphi = angles[toWiggle[j]] + angleMovement;
if (newphi < 0) newphi += (floor(-newphi/(2*M_PI))+1)*2*M_PI;
if (newphi > 2*M_PI) newphi -= floor(newphi/(2*M_PI))*2*M_PI;
//bounce off the boundary
newradius = HyperbolicSpace::hyperbolicRadiusToEuclidean(newradius);
if (newradius >= r) newradius = std::nextafter(newradius, std::numeric_limits<double>::lowest());
//updating Quadtree
bool removed = quad.removeContent(toWiggle[j], angles[toWiggle[j]], radii[toWiggle[j]]);
assert(removed);
angles[toWiggle[j]] = newphi;
radii[toWiggle[j]] = newradius;
quad.addContent(toWiggle[j], newphi, newradius);
}
//now get the new edges and see what changed
#pragma omp parallel for
for (index j = 0; j < toWiggle.size(); j++) {
vector<index> newNeighbours = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[toWiggle[j]], radii[toWiggle[j]]), R*currentfactor);
std::sort(oldNeighbours[j].begin(), oldNeighbours[j].end());
std::sort(newNeighbours.begin(), newNeighbours.end());
vector<index> newEdges(newNeighbours.size());
auto it = std::set_difference(newNeighbours.begin(), newNeighbours.end(), oldNeighbours[j].begin(), oldNeighbours[j].end(), newEdges.begin());
newEdges.erase(it, newEdges.end());//trim empty space
vector<index> brokenEdges(oldNeighbours[j].size() - (newNeighbours.size() - newEdges.size()));//this should be the number of broken edges
it = std::set_difference(oldNeighbours[j].begin(), oldNeighbours[j].end(), newNeighbours.begin(), newNeighbours.end(), brokenEdges.begin());
assert(it == brokenEdges.end());
#pragma omp critical
{
for (index edge : newEdges) {
result.emplace_back(GraphEvent::EDGE_ADDITION, toWiggle[j], edge);
}
for (index edge : brokenEdges) {
result.emplace_back(GraphEvent::EDGE_REMOVAL, toWiggle[j], edge);
}
}
}
/**
* since we didn't know whether the other endpoint of an edge was wiggled or not, we may
* have added some of them twice.
* Remove the doubles:
*/
for (auto it = result.begin()+oldStreamMarker; it < result.end(); it++) {
if (it->u > it->v) std::swap(it->u, it->v);
}
std::sort(result.begin()+oldStreamMarker, result.end(), GraphEvent::compare);
auto end = std::unique(result.begin()+oldStreamMarker, result.end(), GraphEvent::equal);
result.erase(end, result.end());
}
result.push_back(GraphEvent(GraphEvent::TIME_STEP));
}
return result;
}
} /* namespace NetworKit */
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <codecvt>
//#include <cstddef>
#include <locale>
#include <clocale>
#include <string>
#include <iomanip>
#include <ctime>
#include "cp-neural.h"
using std::wcout; using std::wstring;
using std::cerr; using std::vector;
class Text {
private:
bool isinit=false;
bool readDataFile(string inputfile) {
std::wifstream txtfile(inputfile, std::ios::binary);
if (!txtfile.is_open()) {
return false;
}
txtfile.imbue(std::locale("en_US.UTF-8"));
wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),
std::istreambuf_iterator<wchar_t>());
txtfile.close();
text=ttext;
filename=inputfile;
return true;
}
public:
wstring text;
string filename;
std::map<wchar_t,int> freq;
std::map<wchar_t,int> w2v;
std::map<int,wchar_t> v2w;
Text(string filename) {
if (readDataFile(filename)) {
for (auto wc : text) {
freq[wc]++;
}
int it=0;
for (auto wc : freq) {
w2v[wc.first]=it;
v2w[it]=wc.first;
++it;
}
isinit=true;
cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl;
}
}
~Text() {
}
bool isInit() {
return isinit;
}
int vocsize() {
if (!isinit) return 0;
return (int)v2w.size();
}
wstring sample(int len) {
int p=std::rand()%(text.size()-len);
return text.substr(p,len);
}
};
void currentDateTime(wstring& timestr) {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf);
}
int main(int argc, char *argv[]) {
#ifndef __APPLE__
std::setlocale(LC_ALL, "");
#else
setlocale(LC_ALL, "");
std::wcout.imbue(std::locale("en_US.UTF-8"));
#endif
wcout << L"Rnn-Readär" << std::endl;
bool allOk=true;
if (argc!=2) {
cerr << L"rnnreader <path-to-text-file>" << endl;
exit(-1);
}
Text txt(argv[1]);
if (!txt.isInit()) {
cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl;
exit(-1);
}
wcout << L"Text size: " << txt.text.size() << endl;
wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl;
/* for (auto f : txt.freq) {
int c=(int)f.first;
wstring wc(1,f.first);
wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl;
}
*/
Color::Modifier red(Color::FG_RED);
Color::Modifier green(Color::FG_GREEN);
Color::Modifier def(Color::FG_DEFAULT);
int T=96;
int N=(int)txt.text.size() / (T+1);
cerr << N << " Max datasets" << endl;
MatrixN Xr(N,T);
MatrixN yr(N,T);
wstring chunk,chunky;
int n=0;
for (int i=0; i<N; i++) {
wstring smp = txt.sample(T+1);
chunk=smp.substr(0,T);
chunky=smp.substr(1,T);
for (int t=0; t<T; t++) {
Xr(i,t)=txt.w2v[chunk[t]];
yr(i,t)=txt.w2v[chunky[t]];
}
++n;
}
int maxN = 100000;
if (n>maxN) n=maxN;
int n1=n*0.9;
int dn=(n-n1)/2;
if (n1+2*dn > n) {
cerr << "Math doesn't work out." << endl;
}
cerr << n1 << " datasets, " << dn << " test-sets, " << dn << " validation-sets" << endl;
/* MatrixN X(n1,T);
MatrixN y(n1,T);
MatrixN Xv(dn,T);
MatrixN yv(dn,T);
MatrixN Xt(dn,T);
MatrixN yt(dn,T);
*/
MatrixN X=Xr.block(0,0,n1,T);
MatrixN y=yr.block(0,0,n1,T);
MatrixN Xv=Xr.block(n1,0,dn,T);
MatrixN yv=yr.block(n1,0,dn,T);
MatrixN Xt=Xr.block(n1+dn,0,dn,T);
MatrixN yt=yr.block(n1+dn,0,dn,T);
unsigned int ctm=(unsigned int)std::time(0);
std::srand(ctm);
cpInitCompute("Rnnreader");
registerLayers();
LayerBlock lb(R"({"name":"rnnreader","init":"orthonormal"})"_json);
int VS=txt.vocsize();
int H=384;
int BS=128;
float clip=5.0;
//int D=64;
// CpParams cp0;
// cp0.setPar("inputShape",vector<int>{T});
// cp0.setPar("V",VS);
// cp0.setPar("D",D);
// cp0.setPar("clip",clip);
// cp0.setPar("init",(string)"orthonormal");
// lb.addLayer("WordEmbedding","WE0",cp0,{"input"});
string rnntype="LSTM"; // or "RNN"
cerr << "RNN-type: " << rnntype << endl;
json j0;
string oName{"OH0"};
j0["inputShape"]=vector<int>{T};
j0["V"]=VS;
lb.addLayer("OneHot",oName,j0,{"input"});
string nName;
json j1;
j1["inputShape"]=vector<int>{VS,T};
j1["N"]=BS;
j1["H"]=H;
j1["forgetgateinitones"]=true;
//j1["forgetbias"]=0.10;
j1["clip"]=clip;
int layer_depth1=4;
j1["H"]=H;
for (auto l=0; l<layer_depth1; l++) {
if (l>0) j1["inputShape"]=vector<int>{H,T};
nName="lstm"+std::to_string(l);
lb.addLayer(rnntype,nName,j1,{oName});
oName=nName;
}
json j10;
j10["inputShape"]=vector<int>{H,T};
j10["M"]=VS;
lb.addLayer("TemporalAffine","af1",j10,{oName});
json j11;
j11["inputShape"]=vector<int>{VS,T};
lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"});
if (!lb.checkTopology(true)) {
allOk=false;
cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl;
} else {
cerr << green << "Topology-check for LayerBlock: ok." << def << endl;
}
//json jc;
//lb.getLayerConfiguration(jc);
//cerr << jc.dump(4) << endl;
// preseverstates no longer necessary for training!
json jo(R"({"verbose":true,"shuffle":false,"preservestates":false,"notests":false,"nofragmentbatches":true,"epsilon":1e-8})"_json);
jo["lossfactor"]=1.0/(floatN)T; // Allows to normalize the loss with T.
jo["learning_rate"]=(floatN)2e-2; //2.2e-2);
floatN dep=200.0;
floatN sep=0.0;
jo["epochs"]=(floatN)dep;
jo["batch_size"]=BS;
for (int i=0; i<1; i++) {
jo["startepoch"]=(floatN)sep;
t_cppl states;
t_cppl statesv;
states["y"] = new MatrixN(y);
statesv["y"] = new MatrixN(yv);
lb.train(X, &states, Xv, &statesv, "Adam", jo);
cppl_delete(&states);
cppl_delete(&statesv);
sep+=dep;
int pos=rand() % 1000 + 5000;
wstring instr=txt.text.substr(pos,T);
MatrixN xg(1,T);
for (int i=0; i<T; i++) {
xg(0,i)=txt.w2v[instr[i]];
}
wstring sout{};
Layer* plstm0=lb.layerMap["lstm0"];
t_cppl statesg{};
plstm0->genZeroStates(&statesg, 1);
int g,t,v;
for (g=0; g<2500; g++) {
t_cppl cache{};
MatrixN probst=lb.forward(xg,&cache, &statesg);
MatrixN probsd=MatrixN(T,VS);
for (t=0; t<T; t++) {
for (v=0; v<VS; v++) {
probsd(t,v)=probst(0,t*VS+v);
}
}
int li=-1;
for (t=0; t<T; t++) {
vector<floatN> probs(VS);
vector<floatN> index(VS);
for (v=0; v<VS; v++) {
probs[v]=probsd(t,v);
index[v]=v;
}
li=(int)index[randomChoice(index, probs)];
}
cppl_delete(&cache);
for (int t=0; t<T-1; t++) {
xg(0,t)=xg(0,t+1);
}
xg(0,T-1)=li;
sout += txt.v2w[li];
}
wcout << "output: " << sout << endl;
wstring timestr;
currentDateTime(timestr);
std::wofstream fl("rnnreader.txt", std::ios_base::app);
fl << "---- " << timestr << ", ep:" << sep << " ---" << endl;
fl << sout << endl;
fl.close();
cppl_delete(&statesg);
}
}
<commit_msg>Larger model 6 layers<commit_after>#include <iostream>
#include <fstream>
#include <codecvt>
//#include <cstddef>
#include <locale>
#include <clocale>
#include <string>
#include <iomanip>
#include <ctime>
#include "cp-neural.h"
using std::wcout; using std::wstring;
using std::cerr; using std::vector;
class Text {
private:
bool isinit=false;
bool readDataFile(string inputfile) {
std::wifstream txtfile(inputfile, std::ios::binary);
if (!txtfile.is_open()) {
return false;
}
txtfile.imbue(std::locale("en_US.UTF-8"));
wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),
std::istreambuf_iterator<wchar_t>());
txtfile.close();
text=ttext;
filename=inputfile;
return true;
}
public:
wstring text;
string filename;
std::map<wchar_t,int> freq;
std::map<wchar_t,int> w2v;
std::map<int,wchar_t> v2w;
Text(string filename) {
if (readDataFile(filename)) {
for (auto wc : text) {
freq[wc]++;
}
int it=0;
for (auto wc : freq) {
w2v[wc.first]=it;
v2w[it]=wc.first;
++it;
}
isinit=true;
cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl;
}
}
~Text() {
}
bool isInit() {
return isinit;
}
int vocsize() {
if (!isinit) return 0;
return (int)v2w.size();
}
wstring sample(int len) {
int p=std::rand()%(text.size()-len);
return text.substr(p,len);
}
};
void currentDateTime(wstring& timestr) {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf);
}
int main(int argc, char *argv[]) {
#ifndef __APPLE__
std::setlocale(LC_ALL, "");
#else
setlocale(LC_ALL, "");
std::wcout.imbue(std::locale("en_US.UTF-8"));
#endif
wcout << L"Rnn-Readär" << std::endl;
bool allOk=true;
if (argc!=2) {
cerr << L"rnnreader <path-to-text-file>" << endl;
exit(-1);
}
Text txt(argv[1]);
if (!txt.isInit()) {
cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl;
exit(-1);
}
wcout << L"Text size: " << txt.text.size() << endl;
wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl;
/* for (auto f : txt.freq) {
int c=(int)f.first;
wstring wc(1,f.first);
wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl;
}
*/
Color::Modifier red(Color::FG_RED);
Color::Modifier green(Color::FG_GREEN);
Color::Modifier def(Color::FG_DEFAULT);
int T=96;
int N=(int)txt.text.size() / (T+1);
cerr << N << " Max datasets" << endl;
MatrixN Xr(N,T);
MatrixN yr(N,T);
wstring chunk,chunky;
int n=0;
for (int i=0; i<N; i++) {
wstring smp = txt.sample(T+1);
chunk=smp.substr(0,T);
chunky=smp.substr(1,T);
for (int t=0; t<T; t++) {
Xr(i,t)=txt.w2v[chunk[t]];
yr(i,t)=txt.w2v[chunky[t]];
}
++n;
}
int maxN = 100000;
if (n>maxN) n=maxN;
int n1=n*0.9;
int dn=(n-n1)/2;
if (n1+2*dn > n) {
cerr << "Math doesn't work out." << endl;
}
cerr << n1 << " datasets, " << dn << " test-sets, " << dn << " validation-sets" << endl;
/* MatrixN X(n1,T);
MatrixN y(n1,T);
MatrixN Xv(dn,T);
MatrixN yv(dn,T);
MatrixN Xt(dn,T);
MatrixN yt(dn,T);
*/
MatrixN X=Xr.block(0,0,n1,T);
MatrixN y=yr.block(0,0,n1,T);
MatrixN Xv=Xr.block(n1,0,dn,T);
MatrixN yv=yr.block(n1,0,dn,T);
MatrixN Xt=Xr.block(n1+dn,0,dn,T);
MatrixN yt=yr.block(n1+dn,0,dn,T);
unsigned int ctm=(unsigned int)std::time(0);
std::srand(ctm);
cpInitCompute("Rnnreader");
registerLayers();
LayerBlock lb(R"({"name":"rnnreader","init":"orthonormal"})"_json);
int VS=txt.vocsize();
int H=384;
int BS=128;
float clip=5.0;
//int D=64;
// CpParams cp0;
// cp0.setPar("inputShape",vector<int>{T});
// cp0.setPar("V",VS);
// cp0.setPar("D",D);
// cp0.setPar("clip",clip);
// cp0.setPar("init",(string)"orthonormal");
// lb.addLayer("WordEmbedding","WE0",cp0,{"input"});
string rnntype="LSTM"; // or "RNN"
cerr << "RNN-type: " << rnntype << endl;
json j0;
string oName{"OH0"};
j0["inputShape"]=vector<int>{T};
j0["V"]=VS;
lb.addLayer("OneHot",oName,j0,{"input"});
string nName;
json j1;
j1["inputShape"]=vector<int>{VS,T};
j1["N"]=BS;
j1["H"]=H;
j1["forgetgateinitones"]=true;
//j1["forgetbias"]=0.10;
j1["clip"]=clip;
int layer_depth1=6;
j1["H"]=H;
for (auto l=0; l<layer_depth1; l++) {
if (l>0) j1["inputShape"]=vector<int>{H,T};
nName="lstm"+std::to_string(l);
lb.addLayer(rnntype,nName,j1,{oName});
oName=nName;
}
json j10;
j10["inputShape"]=vector<int>{H,T};
j10["M"]=VS;
lb.addLayer("TemporalAffine","af1",j10,{oName});
json j11;
j11["inputShape"]=vector<int>{VS,T};
lb.addLayer("TemporalSoftmax","sm1",j11,{"af1"});
if (!lb.checkTopology(true)) {
allOk=false;
cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl;
} else {
cerr << green << "Topology-check for LayerBlock: ok." << def << endl;
}
//json jc;
//lb.getLayerConfiguration(jc);
//cerr << jc.dump(4) << endl;
// preseverstates no longer necessary for training!
json jo(R"({"verbose":true,"shuffle":false,"preservestates":false,"notests":false,"nofragmentbatches":true,"epsilon":1e-8})"_json);
jo["lossfactor"]=1.0/(floatN)T; // Allows to normalize the loss with T.
jo["learning_rate"]=(floatN)2e-2; //2.2e-2);
floatN dep=100.0;
floatN sep=0.0;
jo["epochs"]=(floatN)dep;
jo["batch_size"]=BS;
for (int i=0; i<10; i++) {
jo["startepoch"]=(floatN)sep;
t_cppl states;
t_cppl statesv;
states["y"] = new MatrixN(y);
statesv["y"] = new MatrixN(yv);
lb.train(X, &states, Xv, &statesv, "Adam", jo);
cppl_delete(&states);
cppl_delete(&statesv);
sep+=dep;
int pos=rand() % 1000 + 5000;
wstring instr=txt.text.substr(pos,T);
MatrixN xg(1,T);
for (int i=0; i<T; i++) {
xg(0,i)=txt.w2v[instr[i]];
}
wstring sout{};
Layer* plstm0=lb.layerMap["lstm0"];
t_cppl statesg{};
plstm0->genZeroStates(&statesg, 1);
int g,t,v;
for (g=0; g<2500; g++) {
t_cppl cache{};
MatrixN probst=lb.forward(xg,&cache, &statesg);
MatrixN probsd=MatrixN(T,VS);
for (t=0; t<T; t++) {
for (v=0; v<VS; v++) {
probsd(t,v)=probst(0,t*VS+v);
}
}
int li=-1;
for (t=0; t<T; t++) {
vector<floatN> probs(VS);
vector<floatN> index(VS);
for (v=0; v<VS; v++) {
probs[v]=probsd(t,v);
index[v]=v;
}
li=(int)index[randomChoice(index, probs)];
}
cppl_delete(&cache);
for (int t=0; t<T-1; t++) {
xg(0,t)=xg(0,t+1);
}
xg(0,T-1)=li;
sout += txt.v2w[li];
}
wcout << "output: " << sout << endl;
wstring timestr;
currentDateTime(timestr);
std::wofstream fl("rnnreader.txt", std::ios_base::app);
fl << "---- " << timestr << ", ep:" << sep << " ---" << endl;
fl << sout << endl;
fl.close();
cppl_delete(&statesg);
}
}
<|endoftext|> |
<commit_before>
#include "animatedSprite.hpp"
AnimatedSprite::AnimatedSprite() :
sprite(),
textureLoaded(false),
currentState(0),
currentFrame(0),
reversed(false),
rectDirty(true),
type(CYCLE)
{
}
AnimatedSprite::AnimatedSprite(const sf::Texture& texture) :
sprite(texture),
textureLoaded(true),
currentState(0),
currentFrame(0),
reversed(false),
rectDirty(true),
type(CYCLE)
{
}
void AnimatedSprite::setTexture(const sf::Texture& texture)
{
sprite.setTexture(texture, true);
textureLoaded = true;
if(currentState < spriteMapping.size() && currentFrame < spriteMapping[currentState].size())
{
rect.left = spriteMapping[currentState][currentFrame].first;
rect.top = spriteMapping[currentState][currentFrame].second;
rectDirty = true;
}
}
void AnimatedSprite::addState(const SpriteState& state)
{
spriteMapping.push_back(state);
}
void AnimatedSprite::setState(int ID)
{
setState(ID, 0);
}
void AnimatedSprite::setState(int ID, int frame)
{
if(ID >= 0 && ID < spriteMapping.size() && frame >= 0 && frame < spriteMapping[ID].size())
{
currentState = ID;
currentFrame = frame;
rect.left = spriteMapping[currentState][currentFrame].first;
rect.top = spriteMapping[currentState][currentFrame].second;
rectDirty = true;
}
}
void AnimatedSprite::setSpriteSize(int width, int height)
{
rectDirty = true;
rect.width = width;
rect.height = height;
}
void AnimatedSprite::setSpriteSize(sf::Vector2i size)
{
setSpriteSize(size.x, size.y);
}
void AnimatedSprite::setTimePerFrame(float seconds)
{
timePerFrame = sf::seconds(seconds);
}
void AnimatedSprite::setTimePerFrame(int milliseconds)
{
timePerFrame = sf::milliseconds(milliseconds);
}
void AnimatedSprite::setRotationType(RotationType type, bool resetReversed)
{
this->type = type;
if(resetReversed)
{
reversed = false;
}
}
void AnimatedSprite::updateSprite(sf::Time dt)
{
time += dt;
while(time > timePerFrame)
{
switch(type)
{
case CYCLE:
currentFrame = (currentFrame + 1) % spriteMapping[currentState].size();
break;
case REVERSE:
currentFrame = currentFrame + (reversed ? -1 : 1);
if(currentFrame < 0 || currentFrame >= spriteMapping[currentState].size())
{
currentFrame = currentFrame + (reversed ? 2 : -2);
reversed = !reversed;
}
break;
default:
break;
}
rect.left = spriteMapping[currentState][currentFrame].first;
rect.top = spriteMapping[currentState][currentFrame].second;
rectDirty = true;
time -= timePerFrame;
}
}
bool AnimatedSprite::isInitialized()
{
return textureLoaded && spriteMapping.size() > 0;
}
void AnimatedSprite::draw(sf::RenderTarget& target, sf::RenderStates states)
{
assert(isInitialized());
states.transform *= getTransform()
if(rectDirty)
{
sprite.setTextureRect(rect);
rectDirty = false;
}
target.draw(sprite, states);
}
<commit_msg>Fixed missing semicolon<commit_after>
#include "animatedSprite.hpp"
AnimatedSprite::AnimatedSprite() :
sprite(),
textureLoaded(false),
currentState(0),
currentFrame(0),
reversed(false),
rectDirty(true),
type(CYCLE)
{
}
AnimatedSprite::AnimatedSprite(const sf::Texture& texture) :
sprite(texture),
textureLoaded(true),
currentState(0),
currentFrame(0),
reversed(false),
rectDirty(true),
type(CYCLE)
{
}
void AnimatedSprite::setTexture(const sf::Texture& texture)
{
sprite.setTexture(texture, true);
textureLoaded = true;
if(currentState < spriteMapping.size() && currentFrame < spriteMapping[currentState].size())
{
rect.left = spriteMapping[currentState][currentFrame].first;
rect.top = spriteMapping[currentState][currentFrame].second;
rectDirty = true;
}
}
void AnimatedSprite::addState(const SpriteState& state)
{
spriteMapping.push_back(state);
}
void AnimatedSprite::setState(int ID)
{
setState(ID, 0);
}
void AnimatedSprite::setState(int ID, int frame)
{
if(ID >= 0 && ID < spriteMapping.size() && frame >= 0 && frame < spriteMapping[ID].size())
{
currentState = ID;
currentFrame = frame;
rect.left = spriteMapping[currentState][currentFrame].first;
rect.top = spriteMapping[currentState][currentFrame].second;
rectDirty = true;
}
}
void AnimatedSprite::setSpriteSize(int width, int height)
{
rectDirty = true;
rect.width = width;
rect.height = height;
}
void AnimatedSprite::setSpriteSize(sf::Vector2i size)
{
setSpriteSize(size.x, size.y);
}
void AnimatedSprite::setTimePerFrame(float seconds)
{
timePerFrame = sf::seconds(seconds);
}
void AnimatedSprite::setTimePerFrame(int milliseconds)
{
timePerFrame = sf::milliseconds(milliseconds);
}
void AnimatedSprite::setRotationType(RotationType type, bool resetReversed)
{
this->type = type;
if(resetReversed)
{
reversed = false;
}
}
void AnimatedSprite::updateSprite(sf::Time dt)
{
time += dt;
while(time > timePerFrame)
{
switch(type)
{
case CYCLE:
currentFrame = (currentFrame + 1) % spriteMapping[currentState].size();
break;
case REVERSE:
currentFrame = currentFrame + (reversed ? -1 : 1);
if(currentFrame < 0 || currentFrame >= spriteMapping[currentState].size())
{
currentFrame = currentFrame + (reversed ? 2 : -2);
reversed = !reversed;
}
break;
default:
break;
}
rect.left = spriteMapping[currentState][currentFrame].first;
rect.top = spriteMapping[currentState][currentFrame].second;
rectDirty = true;
time -= timePerFrame;
}
}
bool AnimatedSprite::isInitialized()
{
return textureLoaded && spriteMapping.size() > 0;
}
void AnimatedSprite::draw(sf::RenderTarget& target, sf::RenderStates states)
{
assert(isInitialized());
states.transform *= getTransform();
if(rectDirty)
{
sprite.setTextureRect(rect);
rectDirty = false;
}
target.draw(sprite, states);
}
<|endoftext|> |
<commit_before>#ifndef PLATFORM_IRQ_MANAGER_HPP
#define PLATFORM_IRQ_MANAGER_HPP
#include <stm32f4xx.h>
#include <core_cm4.h>
#include <functional>
using IRQn_t = IRQn_Type;
// Manages irqs
// TODO: singleton obviously
class IRQ_manager
{
public:
// TODO: setup VTOR?
IRQ_manager() = delete;
~IRQ_manager() = delete;
static void init()
{
auto defaultHandler = []() { for(;;); };
for (auto &h : m_handlers) {
h = defaultHandler;
}
__enable_irq();
}
static int subscribe(IRQn_t IRQn, const std::function< void() > &handler)
{
// TODO: error check
m_handlers[IRQn] = handler;
return 0;
}
static int unsubscribe(IRQn_t IRQn)
{
m_handlers[IRQn] = nullptr;
return 0;
}
static int mask(IRQn_t IRQn)
{
NVIC_DisableIRQ(IRQn);
// TODO
return 0;
}
static int unmask(IRQn_t IRQn)
{
NVIC_EnableIRQ(IRQn);
// TODO
return 0;
}
static int clear(IRQn_t IRQn)
{
NVIC_ClearPendingIRQ(static_cast< IRQn_t > (IRQn));
return 0;
}
private:
// Prevent optimizing out an ISR routine
__attribute__ ((used)) static void ISR()
{
volatile int IRQn;
asm volatile (
"mrs %0, ipsr" : "=r" (IRQn)
);
// IPSR holds exception numbers starting from 0
// Valid IRQ number starts from -15
// See Cortex-M4 processors documentation
// http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/CHDBIBGJ.html
IRQn -= 16;
if (m_handlers[IRQn]) {
// TODO: Is it needed?
mask(static_cast< IRQn_t >(IRQn));
m_handlers[IRQn]();
return;
}
for(;;); // Default handler, TODO: change to something more useful
}
// Registered IRQ handlers
// TODO: magic numbers
static std::function< void() > m_handlers[82];
};
#endif
<commit_msg>Atomic subscribe\unsubscribe in IRQ manager<commit_after>#ifndef PLATFORM_IRQ_MANAGER_HPP
#define PLATFORM_IRQ_MANAGER_HPP
#include <stm32f4xx.h>
#include <core_cm4.h>
#include <functional>
using IRQn_t = IRQn_Type;
// Manages irqs
// TODO: singleton obviously
class IRQ_manager
{
public:
// TODO: setup VTOR?
IRQ_manager() = delete;
~IRQ_manager() = delete;
static void init()
{
for (auto &h : m_handlers) {
h = default_handler;
}
__enable_irq();
}
static int subscribe(IRQn_t IRQn, const std::function< void() > &handler)
{
// TODO: error check
__disable_irq();
m_handlers[IRQn] = handler;
__enable_irq();
return 0;
}
static int unsubscribe(IRQn_t IRQn)
{
__disable_irq();
m_handlers[IRQn] = default_handler;
__enable_irq();
return 0;
}
static int mask(IRQn_t IRQn)
{
NVIC_DisableIRQ(IRQn);
// TODO
return 0;
}
static int unmask(IRQn_t IRQn)
{
NVIC_EnableIRQ(IRQn);
// TODO
return 0;
}
static int clear(IRQn_t IRQn)
{
NVIC_ClearPendingIRQ(static_cast< IRQn_t > (IRQn));
return 0;
}
private:
// Prevent optimizing out an ISR routine
__attribute__ ((used)) static void ISR()
{
volatile int IRQn;
asm volatile (
"mrs %0, ipsr" : "=r" (IRQn)
);
// IPSR holds exception numbers starting from 0
// Valid IRQ number starts from -15
// See Cortex-M4 processors documentation
// http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/CHDBIBGJ.html
IRQn -= 16;
// TODO: Is it needed?
mask(static_cast< IRQn_t >(IRQn));
m_handlers[IRQn]();
}
static void default_handler()
{
__disable_irq();
for(;;);
}
// Registered IRQ handlers
// TODO: magic numbers
static std::function< void() > m_handlers[82];
};
#endif
<|endoftext|> |
<commit_before>#include <boost/assign/list_of.hpp>
#include <libport/lexical-cast.hh>
#include <boost/preprocessor.hpp>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/program-name.hh>
#include <libport/safe-container.hh>
#include <libport/time.hh>
#include <libport/unit-test.hh>
using boost::assign::list_of;
using libport::test_suite;
template<typename T>
std::vector<T>
tov(boost::assign_detail::generic_list<T>& l)
{
return std::vector<T>(l.begin(), l.end());
}
#define tolist(a, b) tov(list_of BOOST_PP_TUPLE_TO_SEQ(a, b))
template<typename T, typename U>
bool
check_list(T& l1, U l2)
{
typename U::iterator i2 = l2.begin();
foreach (typename T::value_type& v, l1)
{
if (i2 == l2.end())
{
BOOST_TEST_MESSAGE("second list too short");
goto fail;
}
if (v != *i2)
{
BOOST_TEST_MESSAGE("item differ: " << v << " vs. " << *i2);
goto fail;
}
++i2;
}
if (i2 != l2.end())
{
BOOST_TEST_MESSAGE("first list too short");
goto fail;
}
return true;
fail:
foreach(typename T::value_type& v, l1)
std::cerr << v << " ";
std::cerr << std::endl;
foreach(typename U::value_type v, l2)
std::cerr << v << " ";
std::cerr << std::endl;
return false;
}
// Check basic behavior
void test()
{
libport::SafeContainer<std::list, int> s;
std::list<int> b = list_of(3)(4)(5)(6)(7)(8)(9)(10)(11);
foreach(int i, b)
s.push_back(i);
s.push_front(2);
s.push_front(1);
s.push_back(12);
s.push_back(13);
BOOST_CHECK(check_list(s, tolist(13, (1,2,3,4,5,6,7,8,9,10,11,12,13))));
std::vector<int> tv;
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
tv.push_back(*i);
if (*i == 12)
s.erase(i);
}
std::vector<int> expect = tolist(13, (1,2,3,4,5,6,7,8,9,10,11,12,13));
check_list(tv, expect);
BOOST_CHECK(check_list(s, tolist(12, (1,2,3,4,5,6,7,8,9,10,11,13))));
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
if (*i == 9)
s.erase(std::find(s.begin(), s.end(), 9));
}
BOOST_CHECK(check_list(s, tolist(11, (1,2,3,4,5,6,7,8,10,11,13))));
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
if (*i == 8)
{
s.erase(std::find(s.begin(), s.end(), 8));
s.erase(std::find(s.begin(), s.end(), 10));
s.erase(std::find(s.begin(), s.end(), 7));
}
}
BOOST_CHECK(check_list(s, tolist(8, (1,2,3,4,5,6,11,13))));
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
if (*i == 1)
s.erase(i);
}
BOOST_CHECK(check_list(s, tolist(7, (2,3,4,5,6,11,13))));
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
tv.push_back(*i);
if (*i == 13)
s.erase(i);
}
BOOST_CHECK(check_list(tv, tolist(7, (2,3,4,5,6,11, 13))));
BOOST_CHECK(check_list(s, tolist(6, (2,3,4,5,6,11))));
}
// Check that everything still works when making multiple turns of the flags.
void test2()
{
libport::SafeContainer<std::list, int> s;
std::list<int> b = list_of(3)(4)(5)(6)(7)(8)(9)(10)(11);
foreach(int i, b)
s.push_back(i);
std::vector<int> tv;
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
for(int i=0; i<100; ++i)
{
int sum;
foreach(int j, s)
sum += j;
}
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
for(int i=0; i<100; ++i)
{
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
tv.push_back(*i);
if (*i == 11) s.erase(i);
}
s.push_back(11);
BOOST_CHECK(check_list(s, tv));
}
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
std::vector<int> v(b.begin(), b.end());
/// keep v and s in sync, randomly remove elements
for (int i=0; i<1000; ++i)
{
int item = rand()% v.size();
int p = 0;
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i, ++p)
{
tv.push_back(*i);
if (p == item) s.erase(i);
}
BOOST_CHECK(check_list(v, tv));
v.erase(v.begin()+item);
BOOST_CHECK(check_list(s, v));
v.push_back(rand());
s.push_back(v.back());
}
s.clear();
foreach(int i, b)
s.push_back(i);
BOOST_CHECK_EQUAL(s.size(), 9u);
std::list<int> ins = list_of(100)(101)(102);
libport::SafeContainer<std::list, int>::iterator i = s.begin();
i++;i++;i++;
s.insert(i, ins.begin(), ins.end());
BOOST_CHECK(check_list(s, tolist(12, (3,4,5,100,101,102,6,7,8,9,10,11))));
std::vector<int> iv(s.begin(), s.end());
BOOST_CHECK(check_list(s, iv));
BOOST_CHECK(check_list(iv, tolist(12, (3,4,5,100,101,102,6,7,8,9,10,11))));
s.clear();
s.insert(s.begin(), iv.begin(), iv.end());
BOOST_CHECK(check_list(s, tolist(12, (3,4,5,100,101,102,6,7,8,9,10,11))));
s.clear();
// Check we can iterate on an empty list.
foreach(int i, s)
(void)i;
}
// Interrupt iteration
void test3()
{
libport::SafeContainer<std::list, int> s;
std::vector<int> b =
list_of(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)(14)(15);
foreach(int i, b)
s.push_back(i);
std::vector<int> tv;
for (int i=0; i<1000; ++i)
{
int item = rand()% b.size();
int p = 0;
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i, ++p)
{
if (p == item) break;
tv.push_back(*i);
}
BOOST_CHECK(check_list(tv, std::vector<int>(b.begin(), b.begin() + item)));
}
}
// Check multiple iterators in parallel
void test4()
{
std::vector<int> b =
list_of(0)(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)(14)(15);
std::vector<int> tv;
for (int i_=0; i_<100; ++i_)
{
libport::SafeContainer<std::list, int> s;
foreach(int i, b)
s.push_back(i);
std::vector<libport::SafeContainer<std::list, int>::iterator> iters;
iters.resize(20);
std::vector<int> ipos;
std::vector<std::vector<int> > effective;
// Store some iterators at various positions.
BOOST_CHECK(true);
for (int piter=0; piter<10; ++piter)
{
std::cerr << "start iteration " << piter << std::endl;
effective.push_back(std::vector<int>());
int item = rand()% b.size();
int p = 0;
iters[piter] = s.begin();
BOOST_CHECK(true);
libport::SafeContainer<std::list, int>::iterator &i = iters[piter];
for (; i != s.end(); ++i, ++p)
{
effective[piter].push_back(*i);
if (p == item) break;
}
BOOST_CHECK(true);
ipos.push_back(item);
}
// Remove random elements
std::vector<int> removed;
for (int i=0; i<5; ++i)
{
int item = rand()% b.size();
int p = 0;
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i, ++p)
if (p == item)
{
removed.push_back(*i);
s.erase(i);
break;
}
}
BOOST_CHECK(true);
// Finish iteration
for (int piter=0; piter<10; ++piter)
{
std::cerr <<"finish iteration " << piter << std::endl;
effective[piter].push_back(-1);
libport::SafeContainer<std::list, int>::iterator &i = iters[piter];
if (i != s.end())
i++;
while (i != s.end())
{
effective[piter].push_back(*i);
++i;
}
}
BOOST_CHECK(true);
// Compute expected output and compare
for (int piter=0; piter<10; ++piter)
{
std::vector<int> expect;
for (int i=0; i<=ipos[piter]; ++i)
expect.push_back(b[i]);
expect.push_back(-1);
for (unsigned i=ipos[piter]+1; i< b.size(); ++i)
if (!libport::has(removed, b[i]))
expect.push_back(b[i]);
BOOST_CHECK(check_list(expect, effective[piter]));
}
}
}
test_suite*
init_test_suite()
{
int t = time(0);
if (getenv("SEED"))
t = boost::lexical_cast<int>(getenv("SEED"));
std::cerr <<"seed is " << t << std::endl;
srand(t);
libport::program_initialize("safe-container");
test_suite* suite = BOOST_TEST_SUITE("libport::SafeContainer test suite");
suite->add(BOOST_TEST_CASE(test));
suite->add(BOOST_TEST_CASE(test2));
suite->add(BOOST_TEST_CASE(test3));
suite->add(BOOST_TEST_CASE(test4));
return suite;
}
<commit_msg>Skip safe container test in debug mode.<commit_after>#include <boost/assign/list_of.hpp>
#include <libport/lexical-cast.hh>
#include <boost/preprocessor.hpp>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/program-name.hh>
#include <libport/safe-container.hh>
#include <libport/sysexits.hh>
#include <libport/time.hh>
#include <libport/unit-test.hh>
using boost::assign::list_of;
using libport::test_suite;
template<typename T>
std::vector<T>
tov(boost::assign_detail::generic_list<T>& l)
{
return std::vector<T>(l.begin(), l.end());
}
#define tolist(a, b) tov(list_of BOOST_PP_TUPLE_TO_SEQ(a, b))
template<typename T, typename U>
bool
check_list(T& l1, U l2)
{
typename U::iterator i2 = l2.begin();
foreach (typename T::value_type& v, l1)
{
if (i2 == l2.end())
{
BOOST_TEST_MESSAGE("second list too short");
goto fail;
}
if (v != *i2)
{
BOOST_TEST_MESSAGE("item differ: " << v << " vs. " << *i2);
goto fail;
}
++i2;
}
if (i2 != l2.end())
{
BOOST_TEST_MESSAGE("first list too short");
goto fail;
}
return true;
fail:
foreach(typename T::value_type& v, l1)
std::cerr << v << " ";
std::cerr << std::endl;
foreach(typename U::value_type v, l2)
std::cerr << v << " ";
std::cerr << std::endl;
return false;
}
// Check basic behavior
void test()
{
libport::SafeContainer<std::list, int> s;
std::list<int> b = list_of(3)(4)(5)(6)(7)(8)(9)(10)(11);
foreach(int i, b)
s.push_back(i);
s.push_front(2);
s.push_front(1);
s.push_back(12);
s.push_back(13);
BOOST_CHECK(check_list(s, tolist(13, (1,2,3,4,5,6,7,8,9,10,11,12,13))));
std::vector<int> tv;
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
tv.push_back(*i);
if (*i == 12)
s.erase(i);
}
std::vector<int> expect = tolist(13, (1,2,3,4,5,6,7,8,9,10,11,12,13));
check_list(tv, expect);
BOOST_CHECK(check_list(s, tolist(12, (1,2,3,4,5,6,7,8,9,10,11,13))));
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
if (*i == 9)
s.erase(std::find(s.begin(), s.end(), 9));
}
BOOST_CHECK(check_list(s, tolist(11, (1,2,3,4,5,6,7,8,10,11,13))));
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
if (*i == 8)
{
s.erase(std::find(s.begin(), s.end(), 8));
s.erase(std::find(s.begin(), s.end(), 10));
s.erase(std::find(s.begin(), s.end(), 7));
}
}
BOOST_CHECK(check_list(s, tolist(8, (1,2,3,4,5,6,11,13))));
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
if (*i == 1)
s.erase(i);
}
BOOST_CHECK(check_list(s, tolist(7, (2,3,4,5,6,11,13))));
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
tv.push_back(*i);
if (*i == 13)
s.erase(i);
}
BOOST_CHECK(check_list(tv, tolist(7, (2,3,4,5,6,11, 13))));
BOOST_CHECK(check_list(s, tolist(6, (2,3,4,5,6,11))));
}
// Check that everything still works when making multiple turns of the flags.
void test2()
{
libport::SafeContainer<std::list, int> s;
std::list<int> b = list_of(3)(4)(5)(6)(7)(8)(9)(10)(11);
foreach(int i, b)
s.push_back(i);
std::vector<int> tv;
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
for(int i=0; i<100; ++i)
{
int sum;
foreach(int j, s)
sum += j;
}
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
for(int i=0; i<100; ++i)
{
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i)
{
tv.push_back(*i);
if (*i == 11) s.erase(i);
}
s.push_back(11);
BOOST_CHECK(check_list(s, tv));
}
BOOST_CHECK(check_list(s, tolist(9, (3,4,5,6,7,8,9,10,11))));
std::vector<int> v(b.begin(), b.end());
/// keep v and s in sync, randomly remove elements
for (int i=0; i<1000; ++i)
{
int item = rand()% v.size();
int p = 0;
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i, ++p)
{
tv.push_back(*i);
if (p == item) s.erase(i);
}
BOOST_CHECK(check_list(v, tv));
v.erase(v.begin()+item);
BOOST_CHECK(check_list(s, v));
v.push_back(rand());
s.push_back(v.back());
}
s.clear();
foreach(int i, b)
s.push_back(i);
BOOST_CHECK_EQUAL(s.size(), 9u);
std::list<int> ins = list_of(100)(101)(102);
libport::SafeContainer<std::list, int>::iterator i = s.begin();
i++;i++;i++;
s.insert(i, ins.begin(), ins.end());
BOOST_CHECK(check_list(s, tolist(12, (3,4,5,100,101,102,6,7,8,9,10,11))));
std::vector<int> iv(s.begin(), s.end());
BOOST_CHECK(check_list(s, iv));
BOOST_CHECK(check_list(iv, tolist(12, (3,4,5,100,101,102,6,7,8,9,10,11))));
s.clear();
s.insert(s.begin(), iv.begin(), iv.end());
BOOST_CHECK(check_list(s, tolist(12, (3,4,5,100,101,102,6,7,8,9,10,11))));
s.clear();
// Check we can iterate on an empty list.
foreach(int i, s)
(void)i;
}
// Interrupt iteration
void test3()
{
libport::SafeContainer<std::list, int> s;
std::vector<int> b =
list_of(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)(14)(15);
foreach(int i, b)
s.push_back(i);
std::vector<int> tv;
for (int i=0; i<1000; ++i)
{
int item = rand()% b.size();
int p = 0;
tv.clear();
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i, ++p)
{
if (p == item) break;
tv.push_back(*i);
}
BOOST_CHECK(check_list(tv, std::vector<int>(b.begin(), b.begin() + item)));
}
}
// Check multiple iterators in parallel
void test4()
{
std::vector<int> b =
list_of(0)(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)(14)(15);
std::vector<int> tv;
for (int i_=0; i_<100; ++i_)
{
libport::SafeContainer<std::list, int> s;
foreach(int i, b)
s.push_back(i);
std::vector<libport::SafeContainer<std::list, int>::iterator> iters;
iters.resize(20);
std::vector<int> ipos;
std::vector<std::vector<int> > effective;
// Store some iterators at various positions.
BOOST_CHECK(true);
for (int piter=0; piter<10; ++piter)
{
std::cerr << "start iteration " << piter << std::endl;
effective.push_back(std::vector<int>());
int item = rand()% b.size();
int p = 0;
iters[piter] = s.begin();
BOOST_CHECK(true);
libport::SafeContainer<std::list, int>::iterator &i = iters[piter];
for (; i != s.end(); ++i, ++p)
{
effective[piter].push_back(*i);
if (p == item) break;
}
BOOST_CHECK(true);
ipos.push_back(item);
}
// Remove random elements
std::vector<int> removed;
for (int i=0; i<5; ++i)
{
int item = rand()% b.size();
int p = 0;
for (libport::SafeContainer<std::list, int>::iterator i = s.begin();
i != s.end(); ++i, ++p)
if (p == item)
{
removed.push_back(*i);
s.erase(i);
break;
}
}
BOOST_CHECK(true);
// Finish iteration
for (int piter=0; piter<10; ++piter)
{
std::cerr <<"finish iteration " << piter << std::endl;
effective[piter].push_back(-1);
libport::SafeContainer<std::list, int>::iterator &i = iters[piter];
if (i != s.end())
i++;
while (i != s.end())
{
effective[piter].push_back(*i);
++i;
}
}
BOOST_CHECK(true);
// Compute expected output and compare
for (int piter=0; piter<10; ++piter)
{
std::vector<int> expect;
for (int i=0; i<=ipos[piter]; ++i)
expect.push_back(b[i]);
expect.push_back(-1);
for (unsigned i=ipos[piter]+1; i< b.size(); ++i)
if (!libport::has(removed, b[i]))
expect.push_back(b[i]);
BOOST_CHECK(check_list(expect, effective[piter]));
}
}
}
test_suite*
init_test_suite()
{
#ifndef NDEBUG
// Safe containers do not work with _GLIBCXX_DEBUG. Matthieu should
// fix this as soon as he gets the time (somewhere around 2013).
exit(EX_SKIP);
#endif
int t = time(0);
if (getenv("SEED"))
t = boost::lexical_cast<int>(getenv("SEED"));
std::cerr <<"seed is " << t << std::endl;
srand(t);
libport::program_initialize("safe-container");
test_suite* suite = BOOST_TEST_SUITE("libport::SafeContainer test suite");
suite->add(BOOST_TEST_CASE(test));
suite->add(BOOST_TEST_CASE(test2));
suite->add(BOOST_TEST_CASE(test3));
suite->add(BOOST_TEST_CASE(test4));
return suite;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "private/qdeclarativepropertycache_p.h"
#include "private/qdeclarativeengine_p.h"
#include "private/qdeclarativebinding_p.h"
#include <QtCore/qdebug.h>
Q_DECLARE_METATYPE(QScriptValue)
QT_BEGIN_NAMESPACE
QDeclarativePropertyCache::Data::Flags QDeclarativePropertyCache::Data::flagsForProperty(const QMetaProperty &p, QDeclarativeEngine *engine)
{
int propType = p.userType();
Flags flags;
if (p.isConstant())
flags |= Data::IsConstant;
if (p.isWritable())
flags |= Data::IsWritable;
if (p.isResettable())
flags |= Data::IsResettable;
if (propType == qMetaTypeId<QDeclarativeBinding *>()) {
flags |= Data::IsQmlBinding;
} else if (propType == qMetaTypeId<QScriptValue>()) {
flags |= Data::IsQScriptValue;
} else if (p.isEnumType()) {
flags |= Data::IsEnumType;
} else {
QDeclarativeMetaType::TypeCategory cat = engine ? QDeclarativeEnginePrivate::get(engine)->typeCategory(propType)
: QDeclarativeMetaType::typeCategory(propType);
if (cat == QDeclarativeMetaType::Object)
flags |= Data::IsQObjectDerived;
else if (cat == QDeclarativeMetaType::List)
flags |= Data::IsQList;
}
return flags;
}
void QDeclarativePropertyCache::Data::load(const QMetaProperty &p, QDeclarativeEngine *engine)
{
propType = p.userType();
coreIndex = p.propertyIndex();
notifyIndex = p.notifySignalIndex();
flags = flagsForProperty(p, engine);
revision = p.revision();
}
void QDeclarativePropertyCache::Data::load(const QMetaMethod &m)
{
coreIndex = m.methodIndex();
relatedIndex = -1;
flags |= Data::IsFunction;
if (m.methodType() == QMetaMethod::Signal)
flags |= Data::IsSignal;
propType = QVariant::Invalid;
const char *returnType = m.typeName();
if (returnType)
propType = QMetaType::type(returnType);
QList<QByteArray> params = m.parameterTypes();
if (!params.isEmpty())
flags |= Data::HasArguments;
revision = m.revision();
}
/*!
Creates a new empty QDeclarativePropertyCache.
*/
QDeclarativePropertyCache::QDeclarativePropertyCache(QDeclarativeEngine *e)
: QDeclarativeCleanup(e), engine(e)
{
Q_ASSERT(engine);
}
/*!
Creates a new QDeclarativePropertyCache of \a metaObject.
*/
QDeclarativePropertyCache::QDeclarativePropertyCache(QDeclarativeEngine *e, const QMetaObject *metaObject)
: QDeclarativeCleanup(e), engine(e)
{
Q_ASSERT(engine);
Q_ASSERT(metaObject);
update(engine, metaObject);
}
QDeclarativePropertyCache::~QDeclarativePropertyCache()
{
clear();
}
void QDeclarativePropertyCache::clear()
{
for (int ii = 0; ii < indexCache.count(); ++ii) {
if (indexCache.at(ii)) indexCache.at(ii)->release();
}
for (int ii = 0; ii < methodIndexCache.count(); ++ii) {
RData *data = methodIndexCache.at(ii);
if (data) data->release();
}
for (StringCache::ConstIterator iter = stringCache.begin();
iter != stringCache.end(); ++iter) {
RData *data = (*iter);
data->release();
}
for (IdentifierCache::ConstIterator iter = identifierCache.begin();
iter != identifierCache.end(); ++iter) {
RData *data = (*iter);
data->release();
}
indexCache.clear();
methodIndexCache.clear();
stringCache.clear();
identifierCache.clear();
}
QDeclarativePropertyCache::Data QDeclarativePropertyCache::create(const QMetaObject *metaObject,
const QString &property)
{
Q_ASSERT(metaObject);
QDeclarativePropertyCache::Data rv;
{
const QMetaObject *cmo = metaObject;
while (cmo) {
int idx = metaObject->indexOfProperty(property.toUtf8());
if (idx != -1) {
QMetaProperty p = metaObject->property(idx);
if (p.isScriptable()) {
rv.load(metaObject->property(idx));
return rv;
} else {
while (cmo && cmo->propertyOffset() >= idx)
cmo = cmo->superClass();
}
} else {
cmo = 0;
}
}
}
int methodCount = metaObject->methodCount();
for (int ii = methodCount - 1; ii >= 3; --ii) { // >=3 to block the destroyed signal and deleteLater() slot
QMetaMethod m = metaObject->method(ii);
if (m.access() == QMetaMethod::Private)
continue;
QString methodName = QString::fromUtf8(m.signature());
int parenIdx = methodName.indexOf(QLatin1Char('('));
Q_ASSERT(parenIdx != -1);
QStringRef methodNameRef = methodName.leftRef(parenIdx);
if (methodNameRef == property) {
rv.load(m);
return rv;
}
}
return rv;
}
QDeclarativePropertyCache *QDeclarativePropertyCache::copy() const
{
QDeclarativePropertyCache *cache = new QDeclarativePropertyCache(engine);
cache->indexCache = indexCache;
cache->methodIndexCache = methodIndexCache;
cache->stringCache = stringCache;
cache->identifierCache = identifierCache;
cache->allowedRevisionCache = allowedRevisionCache;
for (int ii = 0; ii < indexCache.count(); ++ii) {
if (indexCache.at(ii)) indexCache.at(ii)->addref();
}
for (int ii = 0; ii < methodIndexCache.count(); ++ii) {
if (methodIndexCache.at(ii)) methodIndexCache.at(ii)->addref();
}
for (StringCache::ConstIterator iter = stringCache.begin(); iter != stringCache.end(); ++iter)
(*iter)->addref();
for (IdentifierCache::ConstIterator iter = identifierCache.begin(); iter != identifierCache.end(); ++iter)
(*iter)->addref();
return cache;
}
void QDeclarativePropertyCache::append(QDeclarativeEngine *engine, const QMetaObject *metaObject,
Data::Flag propertyFlags, Data::Flag methodFlags, Data::Flag signalFlags)
{
append(engine, metaObject, -1, propertyFlags, methodFlags, signalFlags);
}
void QDeclarativePropertyCache::append(QDeclarativeEngine *engine, const QMetaObject *metaObject,
int revision,
Data::Flag propertyFlags, Data::Flag methodFlags, Data::Flag signalFlags)
{
Q_UNUSED(revision);
allowedRevisionCache.append(0);
QDeclarativeEnginePrivate *enginePriv = QDeclarativeEnginePrivate::get(engine);
int methodCount = metaObject->methodCount();
// 3 to block the destroyed signal and the deleteLater() slot
int methodOffset = qMax(3, metaObject->methodOffset());
methodIndexCache.resize(methodCount);
for (int ii = methodOffset; ii < methodCount; ++ii) {
QMetaMethod m = metaObject->method(ii);
if (m.access() == QMetaMethod::Private)
continue;
QString methodName = QString::fromUtf8(m.signature());
int parenIdx = methodName.indexOf(QLatin1Char('('));
Q_ASSERT(parenIdx != -1);
methodName = methodName.left(parenIdx);
RData *data = new RData;
data->identifier = enginePriv->objectClass->createPersistentIdentifier(methodName);
methodIndexCache[ii] = data;
data->load(m);
if (m.methodType() == QMetaMethod::Slot || m.methodType() == QMetaMethod::Method)
data->flags |= methodFlags;
else if (m.methodType() == QMetaMethod::Signal)
data->flags |= signalFlags;
data->metaObjectOffset = allowedRevisionCache.count() - 1;
if (stringCache.contains(methodName)) {
RData *old = stringCache[methodName];
// We only overload methods in the same class, exactly like C++
if (old->flags & Data::IsFunction && old->coreIndex >= methodOffset)
data->relatedIndex = old->coreIndex;
data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
data->overrideIndex = old->coreIndex;
stringCache[methodName]->release();
identifierCache[data->identifier.identifier]->release();
}
stringCache.insert(methodName, data);
identifierCache.insert(data->identifier.identifier, data);
data->addref();
data->addref();
}
int propCount = metaObject->propertyCount();
int propOffset = metaObject->propertyOffset();
indexCache.resize(propCount);
for (int ii = propOffset; ii < propCount; ++ii) {
QMetaProperty p = metaObject->property(ii);
if (!p.isScriptable())
continue;
QString propName = QString::fromUtf8(p.name());
RData *data = new RData;
data->identifier = enginePriv->objectClass->createPersistentIdentifier(propName);
indexCache[ii] = data;
data->load(p, engine);
data->flags |= propertyFlags;
data->metaObjectOffset = allowedRevisionCache.count() - 1;
if (stringCache.contains(propName)) {
RData *old = stringCache[propName];
data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
data->overrideIndex = old->coreIndex;
stringCache[propName]->release();
identifierCache[data->identifier.identifier]->release();
}
stringCache.insert(propName, data);
identifierCache.insert(data->identifier.identifier, data);
data->addref();
data->addref();
}
}
void QDeclarativePropertyCache::updateRecur(QDeclarativeEngine *engine, const QMetaObject *metaObject)
{
if (!metaObject)
return;
updateRecur(engine, metaObject->superClass());
append(engine, metaObject);
}
void QDeclarativePropertyCache::update(QDeclarativeEngine *engine, const QMetaObject *metaObject)
{
Q_ASSERT(engine);
Q_ASSERT(metaObject);
clear();
// Optimization to prevent unnecessary reallocation of lists
indexCache.reserve(metaObject->propertyCount());
methodIndexCache.reserve(metaObject->methodCount());
updateRecur(engine,metaObject);
}
QDeclarativePropertyCache::Data *
QDeclarativePropertyCache::property(int index) const
{
if (index < 0 || index >= indexCache.count())
return 0;
return indexCache.at(index);
}
QDeclarativePropertyCache::Data *
QDeclarativePropertyCache::method(int index) const
{
if (index < 0 || index >= methodIndexCache.count())
return 0;
return methodIndexCache.at(index);
}
QDeclarativePropertyCache::Data *
QDeclarativePropertyCache::property(const QString &str) const
{
return stringCache.value(str);
}
QString QDeclarativePropertyCache::Data::name(QObject *object)
{
if (!object)
return QString();
return name(object->metaObject());
}
QString QDeclarativePropertyCache::Data::name(const QMetaObject *metaObject)
{
if (!metaObject || coreIndex == -1)
return QString();
if (flags & IsFunction) {
QMetaMethod m = metaObject->method(coreIndex);
QString name = QString::fromUtf8(m.signature());
int parenIdx = name.indexOf(QLatin1Char('('));
if (parenIdx != -1)
name = name.left(parenIdx);
return name;
} else {
QMetaProperty p = metaObject->property(coreIndex);
return QString::fromUtf8(p.name());
}
}
QStringList QDeclarativePropertyCache::propertyNames() const
{
return stringCache.keys();
}
QDeclarativePropertyCache::Data *QDeclarativePropertyCache::property(QDeclarativeEngine *engine, QObject *obj,
const QScriptDeclarativeClass::Identifier &name, Data &local)
{
QDeclarativePropertyCache::Data *rv = 0;
QDeclarativeEnginePrivate *enginePrivate = QDeclarativeEnginePrivate::get(engine);
QDeclarativePropertyCache *cache = 0;
QDeclarativeData *ddata = QDeclarativeData::get(obj);
if (ddata && ddata->propertyCache && ddata->propertyCache->qmlEngine() == engine)
cache = ddata->propertyCache;
if (!cache) {
cache = enginePrivate->cache(obj);
if (cache && ddata && !ddata->propertyCache) { cache->addref(); ddata->propertyCache = cache; }
}
if (cache) {
rv = cache->property(name);
} else {
local = QDeclarativePropertyCache::create(obj->metaObject(), enginePrivate->objectClass->toString(name));
if (local.isValid())
rv = &local;
}
return rv;
}
QDeclarativePropertyCache::Data *QDeclarativePropertyCache::property(QDeclarativeEngine *engine, QObject *obj,
const QString &name, Data &local)
{
QDeclarativePropertyCache::Data *rv = 0;
if (!engine) {
local = QDeclarativePropertyCache::create(obj->metaObject(), name);
if (local.isValid())
rv = &local;
} else {
QDeclarativeEnginePrivate *enginePrivate = QDeclarativeEnginePrivate::get(engine);
QDeclarativePropertyCache *cache = 0;
QDeclarativeData *ddata = QDeclarativeData::get(obj);
if (ddata && ddata->propertyCache && ddata->propertyCache->qmlEngine() == engine)
cache = ddata->propertyCache;
if (!cache) {
cache = enginePrivate->cache(obj);
if (cache && ddata && !ddata->propertyCache) { cache->addref(); ddata->propertyCache = cache; }
}
if (cache) {
rv = cache->property(name);
} else {
local = QDeclarativePropertyCache::create(obj->metaObject(), name);
if (local.isValid())
rv = &local;
}
}
return rv;
}
QT_END_NAMESPACE
<commit_msg>Fix qdeclarativeecmascript test failure.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "private/qdeclarativepropertycache_p.h"
#include "private/qdeclarativeengine_p.h"
#include "private/qdeclarativebinding_p.h"
#include <QtCore/qdebug.h>
Q_DECLARE_METATYPE(QScriptValue)
QT_BEGIN_NAMESPACE
QDeclarativePropertyCache::Data::Flags QDeclarativePropertyCache::Data::flagsForProperty(const QMetaProperty &p, QDeclarativeEngine *engine)
{
int propType = p.userType();
Flags flags;
if (p.isConstant())
flags |= Data::IsConstant;
if (p.isWritable())
flags |= Data::IsWritable;
if (p.isResettable())
flags |= Data::IsResettable;
if (propType == qMetaTypeId<QDeclarativeBinding *>()) {
flags |= Data::IsQmlBinding;
} else if (propType == qMetaTypeId<QScriptValue>()) {
flags |= Data::IsQScriptValue;
} else if (p.isEnumType()) {
flags |= Data::IsEnumType;
} else {
QDeclarativeMetaType::TypeCategory cat = engine ? QDeclarativeEnginePrivate::get(engine)->typeCategory(propType)
: QDeclarativeMetaType::typeCategory(propType);
if (cat == QDeclarativeMetaType::Object)
flags |= Data::IsQObjectDerived;
else if (cat == QDeclarativeMetaType::List)
flags |= Data::IsQList;
}
return flags;
}
void QDeclarativePropertyCache::Data::load(const QMetaProperty &p, QDeclarativeEngine *engine)
{
propType = p.userType();
coreIndex = p.propertyIndex();
notifyIndex = p.notifySignalIndex();
flags = flagsForProperty(p, engine);
revision = p.revision();
}
void QDeclarativePropertyCache::Data::load(const QMetaMethod &m)
{
coreIndex = m.methodIndex();
relatedIndex = -1;
flags |= Data::IsFunction;
if (m.methodType() == QMetaMethod::Signal)
flags |= Data::IsSignal;
propType = QVariant::Invalid;
const char *returnType = m.typeName();
if (returnType)
propType = QMetaType::type(returnType);
QList<QByteArray> params = m.parameterTypes();
if (!params.isEmpty())
flags |= Data::HasArguments;
revision = m.revision();
}
/*!
Creates a new empty QDeclarativePropertyCache.
*/
QDeclarativePropertyCache::QDeclarativePropertyCache(QDeclarativeEngine *e)
: QDeclarativeCleanup(e), engine(e)
{
Q_ASSERT(engine);
}
/*!
Creates a new QDeclarativePropertyCache of \a metaObject.
*/
QDeclarativePropertyCache::QDeclarativePropertyCache(QDeclarativeEngine *e, const QMetaObject *metaObject)
: QDeclarativeCleanup(e), engine(e)
{
Q_ASSERT(engine);
Q_ASSERT(metaObject);
update(engine, metaObject);
}
QDeclarativePropertyCache::~QDeclarativePropertyCache()
{
clear();
}
void QDeclarativePropertyCache::clear()
{
for (int ii = 0; ii < indexCache.count(); ++ii) {
if (indexCache.at(ii)) indexCache.at(ii)->release();
}
for (int ii = 0; ii < methodIndexCache.count(); ++ii) {
RData *data = methodIndexCache.at(ii);
if (data) data->release();
}
for (StringCache::ConstIterator iter = stringCache.begin();
iter != stringCache.end(); ++iter) {
RData *data = (*iter);
data->release();
}
for (IdentifierCache::ConstIterator iter = identifierCache.begin();
iter != identifierCache.end(); ++iter) {
RData *data = (*iter);
data->release();
}
indexCache.clear();
methodIndexCache.clear();
stringCache.clear();
identifierCache.clear();
}
QDeclarativePropertyCache::Data QDeclarativePropertyCache::create(const QMetaObject *metaObject,
const QString &property)
{
Q_ASSERT(metaObject);
QDeclarativePropertyCache::Data rv;
{
const QMetaObject *cmo = metaObject;
while (cmo) {
int idx = metaObject->indexOfProperty(property.toUtf8());
if (idx != -1) {
QMetaProperty p = metaObject->property(idx);
if (p.isScriptable()) {
rv.load(metaObject->property(idx));
return rv;
} else {
while (cmo && cmo->propertyOffset() >= idx)
cmo = cmo->superClass();
}
} else {
cmo = 0;
}
}
}
int methodCount = metaObject->methodCount();
// >=QObject::staticMetaObject.methodCount() to block the destroyed signal and deleteLater() slot
// and other QObject methods.
for (int ii = methodCount - 1; ii >= QObject::staticMetaObject.methodCount(); --ii) {
QMetaMethod m = metaObject->method(ii);
if (m.access() == QMetaMethod::Private)
continue;
QString methodName = QString::fromUtf8(m.signature());
int parenIdx = methodName.indexOf(QLatin1Char('('));
Q_ASSERT(parenIdx != -1);
QStringRef methodNameRef = methodName.leftRef(parenIdx);
if (methodNameRef == property) {
rv.load(m);
return rv;
}
}
return rv;
}
QDeclarativePropertyCache *QDeclarativePropertyCache::copy() const
{
QDeclarativePropertyCache *cache = new QDeclarativePropertyCache(engine);
cache->indexCache = indexCache;
cache->methodIndexCache = methodIndexCache;
cache->stringCache = stringCache;
cache->identifierCache = identifierCache;
cache->allowedRevisionCache = allowedRevisionCache;
for (int ii = 0; ii < indexCache.count(); ++ii) {
if (indexCache.at(ii)) indexCache.at(ii)->addref();
}
for (int ii = 0; ii < methodIndexCache.count(); ++ii) {
if (methodIndexCache.at(ii)) methodIndexCache.at(ii)->addref();
}
for (StringCache::ConstIterator iter = stringCache.begin(); iter != stringCache.end(); ++iter)
(*iter)->addref();
for (IdentifierCache::ConstIterator iter = identifierCache.begin(); iter != identifierCache.end(); ++iter)
(*iter)->addref();
return cache;
}
void QDeclarativePropertyCache::append(QDeclarativeEngine *engine, const QMetaObject *metaObject,
Data::Flag propertyFlags, Data::Flag methodFlags, Data::Flag signalFlags)
{
append(engine, metaObject, -1, propertyFlags, methodFlags, signalFlags);
}
void QDeclarativePropertyCache::append(QDeclarativeEngine *engine, const QMetaObject *metaObject,
int revision,
Data::Flag propertyFlags, Data::Flag methodFlags, Data::Flag signalFlags)
{
Q_UNUSED(revision);
allowedRevisionCache.append(0);
QDeclarativeEnginePrivate *enginePriv = QDeclarativeEnginePrivate::get(engine);
int methodCount = metaObject->methodCount();
// QObject::staticMetaObject.methodCount() to block the destroyed signal and the deleteLater() slot
int methodOffset = qMax(QObject::staticMetaObject.methodCount(), metaObject->methodOffset());
methodIndexCache.resize(methodCount);
for (int ii = methodOffset; ii < methodCount; ++ii) {
QMetaMethod m = metaObject->method(ii);
if (m.access() == QMetaMethod::Private)
continue;
QString methodName = QString::fromUtf8(m.signature());
int parenIdx = methodName.indexOf(QLatin1Char('('));
Q_ASSERT(parenIdx != -1);
methodName = methodName.left(parenIdx);
RData *data = new RData;
data->identifier = enginePriv->objectClass->createPersistentIdentifier(methodName);
methodIndexCache[ii] = data;
data->load(m);
if (m.methodType() == QMetaMethod::Slot || m.methodType() == QMetaMethod::Method)
data->flags |= methodFlags;
else if (m.methodType() == QMetaMethod::Signal)
data->flags |= signalFlags;
data->metaObjectOffset = allowedRevisionCache.count() - 1;
if (stringCache.contains(methodName)) {
RData *old = stringCache[methodName];
// We only overload methods in the same class, exactly like C++
if (old->flags & Data::IsFunction && old->coreIndex >= methodOffset)
data->relatedIndex = old->coreIndex;
data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
data->overrideIndex = old->coreIndex;
stringCache[methodName]->release();
identifierCache[data->identifier.identifier]->release();
}
stringCache.insert(methodName, data);
identifierCache.insert(data->identifier.identifier, data);
data->addref();
data->addref();
}
int propCount = metaObject->propertyCount();
int propOffset = metaObject->propertyOffset();
indexCache.resize(propCount);
for (int ii = propOffset; ii < propCount; ++ii) {
QMetaProperty p = metaObject->property(ii);
if (!p.isScriptable())
continue;
QString propName = QString::fromUtf8(p.name());
RData *data = new RData;
data->identifier = enginePriv->objectClass->createPersistentIdentifier(propName);
indexCache[ii] = data;
data->load(p, engine);
data->flags |= propertyFlags;
data->metaObjectOffset = allowedRevisionCache.count() - 1;
if (stringCache.contains(propName)) {
RData *old = stringCache[propName];
data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
data->overrideIndex = old->coreIndex;
stringCache[propName]->release();
identifierCache[data->identifier.identifier]->release();
}
stringCache.insert(propName, data);
identifierCache.insert(data->identifier.identifier, data);
data->addref();
data->addref();
}
}
void QDeclarativePropertyCache::updateRecur(QDeclarativeEngine *engine, const QMetaObject *metaObject)
{
if (!metaObject)
return;
updateRecur(engine, metaObject->superClass());
append(engine, metaObject);
}
void QDeclarativePropertyCache::update(QDeclarativeEngine *engine, const QMetaObject *metaObject)
{
Q_ASSERT(engine);
Q_ASSERT(metaObject);
clear();
// Optimization to prevent unnecessary reallocation of lists
indexCache.reserve(metaObject->propertyCount());
methodIndexCache.reserve(metaObject->methodCount());
updateRecur(engine,metaObject);
}
QDeclarativePropertyCache::Data *
QDeclarativePropertyCache::property(int index) const
{
if (index < 0 || index >= indexCache.count())
return 0;
return indexCache.at(index);
}
QDeclarativePropertyCache::Data *
QDeclarativePropertyCache::method(int index) const
{
if (index < 0 || index >= methodIndexCache.count())
return 0;
return methodIndexCache.at(index);
}
QDeclarativePropertyCache::Data *
QDeclarativePropertyCache::property(const QString &str) const
{
return stringCache.value(str);
}
QString QDeclarativePropertyCache::Data::name(QObject *object)
{
if (!object)
return QString();
return name(object->metaObject());
}
QString QDeclarativePropertyCache::Data::name(const QMetaObject *metaObject)
{
if (!metaObject || coreIndex == -1)
return QString();
if (flags & IsFunction) {
QMetaMethod m = metaObject->method(coreIndex);
QString name = QString::fromUtf8(m.signature());
int parenIdx = name.indexOf(QLatin1Char('('));
if (parenIdx != -1)
name = name.left(parenIdx);
return name;
} else {
QMetaProperty p = metaObject->property(coreIndex);
return QString::fromUtf8(p.name());
}
}
QStringList QDeclarativePropertyCache::propertyNames() const
{
return stringCache.keys();
}
QDeclarativePropertyCache::Data *QDeclarativePropertyCache::property(QDeclarativeEngine *engine, QObject *obj,
const QScriptDeclarativeClass::Identifier &name, Data &local)
{
QDeclarativePropertyCache::Data *rv = 0;
QDeclarativeEnginePrivate *enginePrivate = QDeclarativeEnginePrivate::get(engine);
QDeclarativePropertyCache *cache = 0;
QDeclarativeData *ddata = QDeclarativeData::get(obj);
if (ddata && ddata->propertyCache && ddata->propertyCache->qmlEngine() == engine)
cache = ddata->propertyCache;
if (!cache) {
cache = enginePrivate->cache(obj);
if (cache && ddata && !ddata->propertyCache) { cache->addref(); ddata->propertyCache = cache; }
}
if (cache) {
rv = cache->property(name);
} else {
local = QDeclarativePropertyCache::create(obj->metaObject(), enginePrivate->objectClass->toString(name));
if (local.isValid())
rv = &local;
}
return rv;
}
QDeclarativePropertyCache::Data *QDeclarativePropertyCache::property(QDeclarativeEngine *engine, QObject *obj,
const QString &name, Data &local)
{
QDeclarativePropertyCache::Data *rv = 0;
if (!engine) {
local = QDeclarativePropertyCache::create(obj->metaObject(), name);
if (local.isValid())
rv = &local;
} else {
QDeclarativeEnginePrivate *enginePrivate = QDeclarativeEnginePrivate::get(engine);
QDeclarativePropertyCache *cache = 0;
QDeclarativeData *ddata = QDeclarativeData::get(obj);
if (ddata && ddata->propertyCache && ddata->propertyCache->qmlEngine() == engine)
cache = ddata->propertyCache;
if (!cache) {
cache = enginePrivate->cache(obj);
if (cache && ddata && !ddata->propertyCache) { cache->addref(); ddata->propertyCache = cache; }
}
if (cache) {
rv = cache->property(name);
} else {
local = QDeclarativePropertyCache::create(obj->metaObject(), name);
if (local.isValid())
rv = &local;
}
}
return rv;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>//
// NSolver::refine_grid.cpp
//
// Created by Lei Qiao on 15/8/9.
// A work based on deal.II tutorial step-33.
//
#include <NSolver/solver/NSolver.h>
namespace NSFEMSolver
{
using namespace dealii;
// @sect4{NSolver::refine_grid}
// Here, we use the refinement indicators computed before and refine the
// mesh. At the beginning, we loop over all cells and mark those that we
// think should be refined:
template <int dim>
void
NSolver<dim>::refine_grid()
{
switch (parameters->refinement_indicator)
{
case Parameters::Refinement<dim>::Gradient:
{
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active(),
endc = dof_handler.end();
for (unsigned int cell_no=0; cell!=endc; ++cell, ++cell_no)
if (cell->is_locally_owned())
{
cell->clear_coarsen_flag();
cell->clear_refine_flag();
if ((cell->level() < parameters->max_refine_level) &&
(std::fabs (refinement_indicators (cell_no)) > parameters->shock_val))
{
cell->set_refine_flag();
}
else if ((cell->level() > 0) &&
(std::fabs (refinement_indicators (cell_no)) < 0.75*parameters->shock_val))
{
cell->set_coarsen_flag();
}
}
break;
}
case Parameters::Refinement<dim>::Kelly:
{
parallel::distributed::GridRefinement::
refine_and_coarsen_fixed_number (triangulation,
refinement_indicators,
parameters->refine_fraction,
parameters->coarsen_fraction,
parameters->max_cells);
break;
}
default:
{
Assert (false, ExcNotImplemented());
break;
}
}
// clear all flags for cells that we don't locally own
// to avoid unnecessary operations
{
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active();
const typename DoFHandler<dim>::active_cell_iterator
endc = dof_handler.end();
for (; cell != endc; ++cell)
if (!cell->is_locally_owned())
{
cell->clear_refine_flag();
cell->clear_coarsen_flag();
}
}
// Then we need to transfer the various solution vectors from the old to
// the new grid while we do the refinement. The SolutionTransfer class is
// our friend here; it has a fairly extensive documentation, including
// examples, so we won't comment much on the following code. The last
// three lines simply re-set the sizes of some other vectors to the now
// correct size:
NSVector tmp_vector;
tmp_vector.reinit (old_solution, true);
tmp_vector = predictor;
// transfer_in needs vectors with ghost cells.
std::vector<const NSVector * > transfer_in;
transfer_in.push_back (&old_solution);
transfer_in.push_back (&tmp_vector);
parallel::distributed::SolutionTransfer<dim, NSVector> soltrans (dof_handler);
triangulation.prepare_coarsening_and_refinement();
soltrans.prepare_for_coarsening_and_refinement (transfer_in);
triangulation.execute_coarsening_and_refinement();
setup_system();
// Transfer data out
{
std::vector<NSVector * > transfer_out;
NSVector interpolated_old_solution (predictor);
NSVector interpolated_predictor (predictor);
// transfer_out needs vectors without ghost cells.
transfer_out.push_back (&interpolated_old_solution);
transfer_out.push_back (&interpolated_predictor);
soltrans.interpolate (transfer_out);
old_solution = interpolated_old_solution;
predictor = interpolated_predictor;
current_solution = old_solution;
}
}
#include "NSolver.inst"
}
<commit_msg>use new refine_and_coarsen_fixed_number() in NSolver<commit_after>//
// NSolver::refine_grid.cpp
//
// Created by Lei Qiao on 15/8/9.
// A work based on deal.II tutorial step-33.
//
#include <NSolver/solver/NSolver.h>
namespace NSFEMSolver
{
using namespace dealii;
// @sect4{NSolver::refine_grid}
// Here, we use the refinement indicators computed before and refine the
// mesh. At the beginning, we loop over all cells and mark those that we
// think should be refined:
template <int dim>
void
NSolver<dim>::refine_grid()
{
switch (parameters->refinement_indicator)
{
case Parameters::Refinement<dim>::Gradient:
{
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active(),
endc = dof_handler.end();
for (unsigned int cell_no=0; cell!=endc; ++cell, ++cell_no)
if (cell->is_locally_owned())
{
cell->clear_coarsen_flag();
cell->clear_refine_flag();
if ((cell->level() < parameters->max_refine_level) &&
(std::fabs (refinement_indicators (cell_no)) > parameters->shock_val))
{
cell->set_refine_flag();
}
else if ((cell->level() > 0) &&
(std::fabs (refinement_indicators (cell_no)) < 0.75*parameters->shock_val))
{
cell->set_coarsen_flag();
}
}
break;
}
case Parameters::Refinement<dim>::Kelly:
{
NSFEMSolver::Tools::
refine_and_coarsen_fixed_number (triangulation,
refinement_indicators,
parameters);
break;
}
default:
{
Assert (false, ExcNotImplemented());
break;
}
}
// clear all flags for cells that we don't locally own
// to avoid unnecessary operations
{
typename DoFHandler<dim>::active_cell_iterator
cell = dof_handler.begin_active();
const typename DoFHandler<dim>::active_cell_iterator
endc = dof_handler.end();
for (; cell != endc; ++cell)
if (!cell->is_locally_owned())
{
cell->clear_refine_flag();
cell->clear_coarsen_flag();
}
}
// Then we need to transfer the various solution vectors from the old to
// the new grid while we do the refinement. The SolutionTransfer class is
// our friend here; it has a fairly extensive documentation, including
// examples, so we won't comment much on the following code. The last
// three lines simply re-set the sizes of some other vectors to the now
// correct size:
NSVector tmp_vector;
tmp_vector.reinit (old_solution, true);
tmp_vector = predictor;
// transfer_in needs vectors with ghost cells.
std::vector<const NSVector * > transfer_in;
transfer_in.push_back (&old_solution);
transfer_in.push_back (&tmp_vector);
parallel::distributed::SolutionTransfer<dim, NSVector> soltrans (dof_handler);
triangulation.prepare_coarsening_and_refinement();
soltrans.prepare_for_coarsening_and_refinement (transfer_in);
triangulation.execute_coarsening_and_refinement();
setup_system();
// Transfer data out
{
std::vector<NSVector * > transfer_out;
NSVector interpolated_old_solution (predictor);
NSVector interpolated_predictor (predictor);
// transfer_out needs vectors without ghost cells.
transfer_out.push_back (&interpolated_old_solution);
transfer_out.push_back (&interpolated_predictor);
soltrans.interpolate (transfer_out);
old_solution = interpolated_old_solution;
predictor = interpolated_predictor;
current_solution = old_solution;
}
}
#include "NSolver.inst"
}
<|endoftext|> |
<commit_before>/*
* Using Erasthostenes' sieve, print the first 2,000,000 numbers
* darkturo 2014
*/
#include <iostream>
#include <fstream>
#include <bitset>
#include <ctime>
#include <limits>
#include <boost/spirit/include/karma.hpp>
#define TIMEDIFF(start, stop) 1000.0 * (stop - start)/CLOCKS_PER_SEC
#define BUFFER_SIZE 512
template <int MaxNumber>
class ErasthostenesSieve
{
std::bitset<MaxNumber> listOfNaturals;
std::ofstream output;
int counter;
#ifdef __Darwin__
char buffer[BUFFER_SIZE];
char * p_input;
#endif
public:
ErasthostenesSieve() :
output("primesEveryWhere.txt", std::ios::out | std::ios::trunc),
#ifdef __Darwin__
counter(0),
p_input(buffer)
#else
counter(0)
#endif
{
listOfNaturals.set();
listOfNaturals.set(0, false); // 1 is not prime
}
~ErasthostenesSieve()
{
#ifdef __Darwin__
if (p_input != buffer)
output.write(buffer, p_input - buffer); // flush
#endif
output.close();
}
int applyTheSieve()
{
int base = 2;
print( base );
for (base = 3; base * base < MaxNumber; base += 2 )
{
if (not listOfNaturals[base - 1])
continue;
print( base );
for (int pivot = base + base ; pivot <= MaxNumber; pivot += base)
{
listOfNaturals.set(pivot - 1, false);
}
}
for (; base <= MaxNumber; base += 2)
{
if (listOfNaturals[base - 1])
print( base );
}
return counter;
}
private:
inline void print(int number)
{
doPrint(number);
counter ++;
}
#ifdef __Darwin__
inline void doPrint(int number)
{
boost::spirit::karma::generate(p_input, boost::spirit::int_, number);
*p_input++ = '\n';
if (p_input - buffer > BUFFER_SIZE - 8)
{
output.write(buffer, p_input - buffer);
p_input = buffer;
memset(buffer, 0u, BUFFER_SIZE);
}
}
#else
inline void doPrint(int number)
{
char buffer[16];
memset(buffer, 0u, sizeof(buffer));
char * x = buffer;
boost::spirit::karma::generate(x, boost::spirit::int_, number);
output << buffer << "\n";
}
#endif
};
int main(int argc, char ** argv)
{
const int MaxNumber = 32452843;
clock_t t1, t2;
t1 = std::clock();
ErasthostenesSieve<MaxNumber> siever;
int printedPrimes = siever.applyTheSieve();
t2 = std::clock();
// Summary
std::cout.precision(std::numeric_limits<double>::digits10);
std::cerr << "Used " << std::fixed << TIMEDIFF(t1, t2)
<< " msecs to calculate " << printedPrimes
<< " primes." << std::endl;
}
<commit_msg>Add mmap to heisenberg programm when compiling for linux<commit_after>/*
* Using Erasthostenes' sieve, print the first 2,000,000 numbers
* darkturo 2014
*/
#include <iostream>
#include <fstream>
#include <bitset>
#include <ctime>
#include <limits>
#include <boost/spirit/include/karma.hpp>
#ifdef __Linux__
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#define FILESIZE 17245905
#endif
#define TIMEDIFF(start, stop) 1000.0 * (stop - start)/CLOCKS_PER_SEC
#define BUFFER_SIZE 512
template <int MaxNumber>
class ErasthostenesSieve
{
std::bitset<MaxNumber> listOfNaturals;
std::ofstream output;
int counter;
#ifdef __Darwin__
char buffer[BUFFER_SIZE];
char * p_input;
#else
char * p_map;
#endif
public:
ErasthostenesSieve() :
#ifdef __Darwin__
output("primesEveryWhere.txt", std::ios::out | std::ios::trunc),
counter(0),
p_input(buffer)
#else
counter(0)
#endif
{
listOfNaturals.set();
listOfNaturals.set(0, false); // 1 is not prime
#ifdef __Linux__
output_fd = open("primesEveryWhere.txt", O_RDWR | O_CREAT | O_TRUNC, (mode_t)0664);
lseek(output_fd, FILESIZE-1, SEEK_SET);
write(output_fd, "", 1);
p_map = (char*)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, output_fd, 0);
p_input = p_map;
#endif
}
~ErasthostenesSieve()
{
#ifdef __Darwin__
if (p_input != buffer)
output.write(buffer, p_input - buffer); // flush
output.close();
#else
munmap(p_map, p_input - p_map);
close(output_fd);
#endif
}
int applyTheSieve()
{
int base = 2;
print( base );
for (base = 3; base * base < MaxNumber; base += 2 )
{
if (not listOfNaturals[base - 1])
continue;
print( base );
for (int pivot = base + base ; pivot <= MaxNumber; pivot += base)
{
listOfNaturals.set(pivot - 1, false);
}
}
for (; base <= MaxNumber; base += 2)
{
if (listOfNaturals[base - 1])
print( base );
}
return counter;
}
private:
#ifdef __Darwin__
inline void print(int number)
{
doPrint(number);
counter ++;
}
inline void doPrint(int number)
{
boost::spirit::karma::generate(p_input, boost::spirit::int_, number);
*p_input++ = '\n';
if (p_input - buffer > BUFFER_SIZE - 8)
{
output.write(buffer, p_input - buffer);
p_input = buffer;
memset(buffer, 0u, BUFFER_SIZE);
}
}
#else
inline void print(int number)
{
boost::spirit::karma::generate(p_input, boost::spirit::int_, number);
*p_input++ = '\n';
counter ++;
}
#endif
};
int main(int argc, char ** argv)
{
const int MaxNumber = 32452843;
clock_t t1, t2;
t1 = std::clock();
ErasthostenesSieve<MaxNumber> siever;
int printedPrimes = siever.applyTheSieve();
t2 = std::clock();
// Summary
std::cout.precision(std::numeric_limits<double>::digits10);
std::cerr << "Used " << std::fixed << TIMEDIFF(t1, t2)
<< " msecs to calculate " << printedPrimes
<< " primes." << std::endl;
}
<|endoftext|> |
<commit_before>/*
Implementation of the Compiler class.
*/
#include <cctype> //character comparison functions
#include <stdexcept>
#include "compiler.hh"
namespace ds_compiler {
const size_t Compiler::NUM_REGISTERS = 8;
const char Compiler::ERR_CHAR = '\0';
const std::unordered_set<char> ADD_OPS({'+', '-'});
const std::unordered_set<char> MULT_OPS();
//constructors
Compiler::Compiler ()
: m_is (&std::cin), m_os (&std::cout)
{
}
Compiler::Compiler (std::istream *new_is, std::ostream *new_os)
: m_is (new_is), m_os (new_os)
{
}
void Compiler::compile_intermediate () const {
try {
expression();
} catch (std::exception &ex) {
std::cerr << ex.what() << '\n';
}
}
void Compiler::compile_full () const {
compile_start();
compile_intermediate();
compile_end();
}
void Compiler::compile_start () const {
//emit lines for necessary includes
emit_line("#include <stack>");
emit_line("#include <vector>");
emit_line("#include <iostream>");
emit_line("#include <string>");
//create a stack and vector for registers
std::string stack_init = "static std::stack<int> cpu_stack;";
std::string registers_init = "static std::vector<int> cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0);";
emit_line(stack_init);
emit_line(registers_init);
//emit definition of a function for easier stack handling
emit_line("int cpu_pop() {");
emit_line("int val = cpu_stack.top();");
emit_line("cpu_stack.pop();");
emit_line("return val; }");
//emit lines for int main() {
emit_line("int main () {");
}
void Compiler::compile_end () const {
//dump register contents
emit_line("std::cout << \"Register contents\\n\";");
emit_line(
std::string("for (int i = 0; i < ") + std::to_string(NUM_REGISTERS) + "; ++i)"
);
emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';");
//emit lines for closing main
emit_line("return 0;");
emit_line("}");
}
//cradle methods
void Compiler::report_error(const std::string err) const {
os() << '\n';
os() << "Error: " << err << '\n';
}
void Compiler::abort(const std::string err) const {
report_error(err);
throw std::runtime_error("Compilation failed.\n");
}
void Compiler::expected(const std::string expect) const {
abort(expect + " expected.\n");
}
//overload to handle single characters;
//prevents having to construct a string whenever calling expected()
void Compiler::expected(const char c) const {
expected(std::string(1, c));
}
//checks if next character matches; if so, consume that character
void Compiler::match(const char c) const {
if (is().peek() == c) {
is().get();
} else {
expected(c);
}
}
void Compiler::expression () const {
term();
emit_line(
"cpu_stack.at(1) = cpu_stack.at(0);"
);
switch (is().peek()) {
case '+':
add();
break;
case '-':
subtract();
break;
default:
expected("Addop");
}
}
void Compiler::term () const {
char expr = get_num();
if (expr != ERR_CHAR) {
emit_line(
std::string("cpu_registers.at(0) = ") + expr + ";"
);
}
}
// gets a valid identifier from input stream
char Compiler::get_name () const {
if (!std::isalpha(is().peek())) {
expected("Name");
return ERR_CHAR;
} else {
return std::toupper(is().get());
}
}
//gets a number
char Compiler::get_num () const {
if (!std::isdigit(is().peek())) {
expected("Integer");
return ERR_CHAR;
} else {
return is().get();
}
}
//output a string
void Compiler::emit (std::string s) const {
os() << s;
}
//output a string with newline
void Compiler::emit_line (std::string s) const {
emit(s);
emit("\n");
}
//helper members to allow using stream syntax with *is, *os
void Compiler::add () const {
match('+');
term();
emit_line(
std::string("cpu_registers.at(0) = cpu_registers.at(1) + cpu_registers.at(0);")
);
}
void Compiler::subtract () const {
match('-');
term();
emit_line(
std::string("cpu_registers.at(0) = cpu_registers.at(1) - cpu_registers.at(0);")
);
}
static bool is_in(const std::unordered_set<char> us, const char elem) {
return us.find(elem) != us.end();
}
void Compiler::set_is (std::istream *new_is) {
m_is = new_is;
}
void Compiler::set_os (std::ostream *new_os) {
m_os = new_os;
}
std::istream& Compiler::is() const {
return *m_is;
}
std::ostream& Compiler::os() const {
return *m_os;
}
} //end namespace<commit_msg>expression() now handles <term> [<addop> <term>]*<commit_after>/*
Implementation of the Compiler class.
*/
#include <cctype> //character comparison functions
#include <stdexcept>
#include "compiler.hh"
namespace ds_compiler {
const size_t Compiler::NUM_REGISTERS = 8;
const char Compiler::ERR_CHAR = '\0';
const std::unordered_set<char> Compiler::ADD_OPS({'+', '-'});
const std::unordered_set<char> Compiler::MULT_OPS;
//constructors
Compiler::Compiler ()
: m_is (&std::cin), m_os (&std::cout)
{
}
Compiler::Compiler (std::istream *new_is, std::ostream *new_os)
: m_is (new_is), m_os (new_os)
{
}
void Compiler::compile_intermediate () const {
try {
expression();
} catch (std::exception &ex) {
std::cerr << ex.what() << '\n';
}
}
void Compiler::compile_full () const {
compile_start();
compile_intermediate();
compile_end();
}
void Compiler::compile_start () const {
//emit lines for necessary includes
emit_line("#include <stack>");
emit_line("#include <vector>");
emit_line("#include <iostream>");
emit_line("#include <string>");
//create a stack and vector for registers
std::string stack_init = "static std::stack<int> cpu_stack;";
std::string registers_init = "static std::vector<int> cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0);";
emit_line(stack_init);
emit_line(registers_init);
//emit definition of a function for easier stack handling
emit_line("int cpu_pop() {");
emit_line("int val = cpu_stack.top();");
emit_line("cpu_stack.pop();");
emit_line("return val; }");
//emit lines for int main() {
emit_line("int main () {");
}
void Compiler::compile_end () const {
//dump register contents
emit_line("std::cout << \"Register contents\\n\";");
emit_line(
std::string("for (int i = 0; i < ") + std::to_string(NUM_REGISTERS) + "; ++i)"
);
emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';");
//emit lines for closing main
emit_line("return 0;");
emit_line("}");
}
//cradle methods
void Compiler::report_error(const std::string err) const {
os() << '\n';
os() << "Error: " << err << '\n';
}
void Compiler::abort(const std::string err) const {
report_error(err);
throw std::runtime_error("Compilation failed.\n");
}
void Compiler::expected(const std::string expect) const {
abort(expect + " expected.\n");
}
//overload to handle single characters;
//prevents having to construct a string whenever calling expected()
void Compiler::expected(const char c) const {
expected(std::string(1, c));
}
//checks if next character matches; if so, consume that character
void Compiler::match(const char c) const {
if (is().peek() == c) {
is().get();
} else {
expected(c);
}
}
void Compiler::expression () const {
term();
while (is_in(ADD_OPS, is().peek())) {
emit_line("cpu_stack.at(1) = cpu_stack.at(0);");
switch (is().peek()) {
case '+':
add();
break;
case '-':
subtract();
break;
default:
expected("Addop");
}
}
}
void Compiler::term () const {
char expr = get_num();
if (expr != ERR_CHAR) {
emit_line(
std::string("cpu_registers.at(0) = ") + expr + ";"
);
}
}
// gets a valid identifier from input stream
char Compiler::get_name () const {
if (!std::isalpha(is().peek())) {
expected("Name");
return ERR_CHAR;
} else {
return std::toupper(is().get());
}
}
//gets a number
char Compiler::get_num () const {
if (!std::isdigit(is().peek())) {
expected("Integer");
return ERR_CHAR;
} else {
return is().get();
}
}
//output a string
void Compiler::emit (std::string s) const {
os() << s;
}
//output a string with newline
void Compiler::emit_line (std::string s) const {
emit(s);
emit("\n");
}
//helper members to allow using stream syntax with *is, *os
void Compiler::add () const {
match('+');
term();
emit_line(
std::string("cpu_registers.at(0) = cpu_registers.at(1) + cpu_registers.at(0);")
);
}
void Compiler::subtract () const {
match('-');
term();
emit_line(
std::string("cpu_registers.at(0) = cpu_registers.at(1) - cpu_registers.at(0);")
);
}
bool Compiler::is_in(const std::unordered_set<char> us, const char elem) {
return us.find(elem) != us.end();
}
void Compiler::set_is (std::istream *new_is) {
m_is = new_is;
}
void Compiler::set_os (std::ostream *new_os) {
m_os = new_os;
}
std::istream& Compiler::is() const {
return *m_is;
}
std::ostream& Compiler::os() const {
return *m_os;
}
} //end namespace<|endoftext|> |
<commit_before>/*!
\file stack_trace.cpp
\brief Stack trace snapshot provider implementation
\author Ivan Shynkarenka
\date 09.02.2016
\copyright MIT License
*/
#include "system/stack_trace.h"
#include "threads/critical_section.h"
#include "utility/countof.h"
#include <cstring>
#include <iomanip>
#include <sstream>
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
#include <execinfo.h>
#if defined(LIBBFD_SUPPORT)
#include <bfd.h>
#endif
#if defined(LIBDL_SUPPORT)
#include <cxxabi.h>
#include <dlfcn.h>
#endif
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include <windows.h>
#if defined(DBGHELP_SUPPORT)
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4091) // C4091: 'keyword' : ignored on left of 'type' when no variable is declared
#endif
#include <dbghelp.h>
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#endif
#endif
namespace CppCommon {
std::ostream& operator<<(std::ostream& os, const StackTrace::Frame& frame)
{
// Format stack trace frame address
std::ios_base::fmtflags flags = os.flags();
os << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2 * sizeof(uintptr_t)) << (uintptr_t)frame.address << ": ";
os.flags(flags);
// Format stack trace frame other fields
os << (frame.module.empty() ? "<unknown>" : frame.module) << '!';
os << (frame.function.empty() ? "??" : frame.function) << ' ';
os << frame.filename;
if (frame.line > 0)
os << '(' << frame.line << ')';
return os;
}
StackTrace::StackTrace(int skip)
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
const int capacity = 1024;
void* frames[capacity];
// Capture the current stack trace
int captured = backtrace(frames, capacity);
int index = skip + 1;
int size = captured - index;
// Check the current stack trace size
if (size <= 0)
return;
// Resize stack trace frames vector
_frames.resize(size);
// Capture stack trace snapshot under the critical section
static CriticalSection cs;
Locker<CriticalSection> locker(cs);
// Fill all captured frames with symbol information
for (int i = 0; i < size; ++i)
{
auto& frame = _frames[i];
// Get the frame address
frame.address = frames[index + i];
#if defined(LIBDL_SUPPORT)
// Get the frame information
Dl_info info;
if (dladdr(frames[index + i], &info) == 0)
continue;
// Get the frame module
if (info.dli_fname != nullptr)
{
const char* module = std::strrchr(info.dli_fname, '/');
if (module != nullptr)
frame.module = module + 1;
}
// Get the frame function
if (info.dli_sname != nullptr)
{
// Demangle symbol name if need
int status;
char* demangled = abi::__cxa_demangle(info.dli_sname, nullptr, 0, &status);
if ((status == 0) && (demangled != nullptr))
{
frame.function = demangled;
free(demangled);
}
else
frame.function = info.dli_sname;
}
#endif
#if defined(LIBBFD_SUPPORT)
bfd* abfd = nullptr;
char** matching = nullptr;
void* symsptr = nullptr;
asymbol** syms = nullptr;
unsigned int symsize;
long symcount;
const char* filename = nullptr;
const char* functionname = nullptr;
unsigned int line;
bfd_boolean found = false;
bfd_vma pc;
if ((frame.address == nullptr) || (info.dli_fname == nullptr))
continue;
abfd = bfd_openr(info.dli_fname, nullptr);
if (abfd == nullptr)
continue;
if (bfd_check_format(abfd, bfd_archive))
goto cleanup;
if (!bfd_check_format_matches(abfd, bfd_object, &matching))
goto cleanup;
if ((bfd_get_file_flags(abfd) & HAS_SYMS) == 0)
goto cleanup;
symcount = bfd_read_minisymbols(abfd, FALSE, &symsptr, &symsize);
if (symcount == 0)
symcount = bfd_read_minisymbols(abfd, TRUE, &symsptr, &symsize);
if (symcount < 0)
goto cleanup;
syms = (asymbol**)symsptr;
pc = (bfd_vma)frame.address;
for (asection* section = abfd->sections; section != nullptr; section = section->next)
{
if (found)
break;
if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
continue;
bfd_vma vma = bfd_section_vma(section);
if (pc < vma)
continue;
bfd_size_type secsize = bfd_section_size(section);
if (pc >= vma + secsize)
continue;
found = bfd_find_nearest_line(abfd, section, syms, pc - vma, &filename, &functionname, &line);
}
if (!found)
goto cleanup;
if (filename != nullptr)
frame.filename = filename;
frame.line = line;
cleanup:
if (symsptr != nullptr)
free(symsptr);
if (abfd != nullptr)
bfd_close(abfd);
#endif
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
const int capacity = 1024;
void* frames[capacity];
// Capture the current stack trace
USHORT captured = CaptureStackBackTrace(skip + 1, capacity, frames, nullptr);
// Resize stack trace frames vector
_frames.resize(captured);
// Capture stack trace snapshot under the critical section
static CriticalSection cs;
Locker<CriticalSection> locker(cs);
// Fill all captured frames with symbol information
for (int i = 0; i < captured; ++i)
{
auto& frame = _frames[i];
// Get the frame address
frame.address = frames[i];
#if defined(DBGHELP_SUPPORT)
// Get the current process handle
HANDLE hProcess = GetCurrentProcess();
// Get the frame module
IMAGEHLP_MODULE64 module;
ZeroMemory(&module, sizeof(module));
module.SizeOfStruct = sizeof(module);
if (SymGetModuleInfo64(hProcess, (DWORD64)frame.address, &module))
{
const char* image = std::strrchr(module.ImageName, '\\');
if (image != nullptr)
frame.module = image + 1;
}
// Get the frame function
char symbol[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
ZeroMemory(&symbol, countof(symbol));
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbol;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
if (SymFromAddr(hProcess, (DWORD64)frame.address, nullptr, pSymbol))
{
char buffer[4096];
if (UnDecorateSymbolName(pSymbol->Name, buffer, (DWORD)countof(buffer), UNDNAME_NAME_ONLY) > 0)
frame.function = buffer;
}
// Get the frame file name and line number
DWORD offset = 0;
IMAGEHLP_LINE64 line;
ZeroMemory(&line, sizeof(line));
line.SizeOfStruct = sizeof(line);
if (SymGetLineFromAddr64(hProcess, (DWORD64)frame.address, &offset, &line))
{
if (line.FileName != nullptr)
frame.filename = line.FileName;
frame.line = line.LineNumber;
}
#endif
}
#endif
}
std::ostream& operator<<(std::ostream& os, const StackTrace& stack_trace)
{
for (const auto& frame : stack_trace.frames())
os << frame << std::endl;
return os;
}
} // namespace CppCommon
<commit_msg>Build fail on Linux #19<commit_after>/*!
\file stack_trace.cpp
\brief Stack trace snapshot provider implementation
\author Ivan Shynkarenka
\date 09.02.2016
\copyright MIT License
*/
// Workaround for the "binutils/bfd.h wants config.h now?" issue
// https://stackoverflow.com/questions/11748035/binutils-bfd-h-wants-config-h-now
#define PACKAGE "CppCommon"
#define PACKAGE_VERSION "1.0.0.0"
#include "system/stack_trace.h"
#include "threads/critical_section.h"
#include "utility/countof.h"
#include <cstring>
#include <iomanip>
#include <sstream>
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
#include <execinfo.h>
#if defined(LIBBFD_SUPPORT)
#include <bfd.h>
#endif
#if defined(LIBDL_SUPPORT)
#include <cxxabi.h>
#include <dlfcn.h>
#endif
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include <windows.h>
#if defined(DBGHELP_SUPPORT)
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4091) // C4091: 'keyword' : ignored on left of 'type' when no variable is declared
#endif
#include <dbghelp.h>
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#endif
#endif
namespace CppCommon {
std::ostream& operator<<(std::ostream& os, const StackTrace::Frame& frame)
{
// Format stack trace frame address
std::ios_base::fmtflags flags = os.flags();
os << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2 * sizeof(uintptr_t)) << (uintptr_t)frame.address << ": ";
os.flags(flags);
// Format stack trace frame other fields
os << (frame.module.empty() ? "<unknown>" : frame.module) << '!';
os << (frame.function.empty() ? "??" : frame.function) << ' ';
os << frame.filename;
if (frame.line > 0)
os << '(' << frame.line << ')';
return os;
}
StackTrace::StackTrace(int skip)
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
const int capacity = 1024;
void* frames[capacity];
// Capture the current stack trace
int captured = backtrace(frames, capacity);
int index = skip + 1;
int size = captured - index;
// Check the current stack trace size
if (size <= 0)
return;
// Resize stack trace frames vector
_frames.resize(size);
// Capture stack trace snapshot under the critical section
static CriticalSection cs;
Locker<CriticalSection> locker(cs);
// Fill all captured frames with symbol information
for (int i = 0; i < size; ++i)
{
auto& frame = _frames[i];
// Get the frame address
frame.address = frames[index + i];
#if defined(LIBDL_SUPPORT)
// Get the frame information
Dl_info info;
if (dladdr(frames[index + i], &info) == 0)
continue;
// Get the frame module
if (info.dli_fname != nullptr)
{
const char* module = std::strrchr(info.dli_fname, '/');
if (module != nullptr)
frame.module = module + 1;
}
// Get the frame function
if (info.dli_sname != nullptr)
{
// Demangle symbol name if need
int status;
char* demangled = abi::__cxa_demangle(info.dli_sname, nullptr, 0, &status);
if ((status == 0) && (demangled != nullptr))
{
frame.function = demangled;
free(demangled);
}
else
frame.function = info.dli_sname;
}
#endif
#if defined(LIBBFD_SUPPORT)
bfd* abfd = nullptr;
char** matching = nullptr;
void* symsptr = nullptr;
asymbol** syms = nullptr;
unsigned int symsize;
long symcount;
const char* filename = nullptr;
const char* functionname = nullptr;
unsigned int line;
bfd_boolean found = false;
bfd_vma pc;
if ((frame.address == nullptr) || (info.dli_fname == nullptr))
continue;
abfd = bfd_openr(info.dli_fname, nullptr);
if (abfd == nullptr)
continue;
if (bfd_check_format(abfd, bfd_archive))
goto cleanup;
if (!bfd_check_format_matches(abfd, bfd_object, &matching))
goto cleanup;
if ((bfd_get_file_flags(abfd) & HAS_SYMS) == 0)
goto cleanup;
symcount = bfd_read_minisymbols(abfd, FALSE, &symsptr, &symsize);
if (symcount == 0)
symcount = bfd_read_minisymbols(abfd, TRUE, &symsptr, &symsize);
if (symcount < 0)
goto cleanup;
syms = (asymbol**)symsptr;
pc = (bfd_vma)frame.address;
for (asection* section = abfd->sections; section != nullptr; section = section->next)
{
if (found)
break;
if ((bfd_section_flags(section) & SEC_ALLOC) == 0)
continue;
bfd_vma vma = bfd_section_vma(section);
if (pc < vma)
continue;
bfd_size_type secsize = bfd_section_size(section);
if (pc >= vma + secsize)
continue;
found = bfd_find_nearest_line(abfd, section, syms, pc - vma, &filename, &functionname, &line);
}
if (!found)
goto cleanup;
if (filename != nullptr)
frame.filename = filename;
frame.line = line;
cleanup:
if (symsptr != nullptr)
free(symsptr);
if (abfd != nullptr)
bfd_close(abfd);
#endif
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
const int capacity = 1024;
void* frames[capacity];
// Capture the current stack trace
USHORT captured = CaptureStackBackTrace(skip + 1, capacity, frames, nullptr);
// Resize stack trace frames vector
_frames.resize(captured);
// Capture stack trace snapshot under the critical section
static CriticalSection cs;
Locker<CriticalSection> locker(cs);
// Fill all captured frames with symbol information
for (int i = 0; i < captured; ++i)
{
auto& frame = _frames[i];
// Get the frame address
frame.address = frames[i];
#if defined(DBGHELP_SUPPORT)
// Get the current process handle
HANDLE hProcess = GetCurrentProcess();
// Get the frame module
IMAGEHLP_MODULE64 module;
ZeroMemory(&module, sizeof(module));
module.SizeOfStruct = sizeof(module);
if (SymGetModuleInfo64(hProcess, (DWORD64)frame.address, &module))
{
const char* image = std::strrchr(module.ImageName, '\\');
if (image != nullptr)
frame.module = image + 1;
}
// Get the frame function
char symbol[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
ZeroMemory(&symbol, countof(symbol));
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbol;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
if (SymFromAddr(hProcess, (DWORD64)frame.address, nullptr, pSymbol))
{
char buffer[4096];
if (UnDecorateSymbolName(pSymbol->Name, buffer, (DWORD)countof(buffer), UNDNAME_NAME_ONLY) > 0)
frame.function = buffer;
}
// Get the frame file name and line number
DWORD offset = 0;
IMAGEHLP_LINE64 line;
ZeroMemory(&line, sizeof(line));
line.SizeOfStruct = sizeof(line);
if (SymGetLineFromAddr64(hProcess, (DWORD64)frame.address, &offset, &line))
{
if (line.FileName != nullptr)
frame.filename = line.FileName;
frame.line = line.LineNumber;
}
#endif
}
#endif
}
std::ostream& operator<<(std::ostream& os, const StackTrace& stack_trace)
{
for (const auto& frame : stack_trace.frames())
os << frame << std::endl;
return os;
}
} // namespace CppCommon
<|endoftext|> |
<commit_before>///
/// @file cmdoptions.hpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMECOUNT_CMDOPTIONS_HPP
#define PRIMECOUNT_CMDOPTIONS_HPP
#include <primecount.hpp>
#include <int128.hpp>
#include <stdint.h>
namespace primecount {
enum OptionValues
{
OPTION_ALPHA,
OPTION_DELEGLISE_RIVAT,
OPTION_DELEGLISE_RIVAT1,
OPTION_DELEGLISE_RIVAT2,
OPTION_DELEGLISE_RIVAT_PARALLEL1,
OPTION_DELEGLISE_RIVAT_PARALLEL2,
OPTION_DELEGLISE_RIVAT_PARALLEL3,
OPTION_HELP,
OPTION_LEGENDRE,
OPTION_LEHMER,
OPTION_LEHMER2,
OPTION_LMO,
OPTION_LMO1,
OPTION_LMO2,
OPTION_LMO3,
OPTION_LMO4,
OPTION_LMO5,
OPTION_LMO_PARALLEL1,
OPTION_LMO_PARALLEL2,
OPTION_LMO_PARALLEL3,
OPTION_LI,
OPTION_LIINV,
OPTION_MEISSEL,
OPTION_NTHPRIME,
OPTION_NUMBER,
OPTION_PI,
OPTION_PRIMESIEVE,
OPTION_STATUS,
OPTION_TEST,
OPTION_TIME,
OPTION_THREADS,
OPTION_VERSION
};
struct PrimeCountOptions
{
maxint_t x;
int64_t option;
bool time;
int threads;
PrimeCountOptions() :
x(-1),
option(OPTION_PI),
time(false),
threads(get_num_threads())
{ }
};
PrimeCountOptions parseOptions(int, char**);
} // namespace primecount
#endif
<commit_msg>Update cmdoptions.hpp<commit_after>///
/// @file cmdoptions.hpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMECOUNT_CMDOPTIONS_HPP
#define PRIMECOUNT_CMDOPTIONS_HPP
#include <primecount.hpp>
#include <int128.hpp>
#include <stdint.h>
namespace primecount {
enum OptionValues
{
OPTION_ALPHA,
OPTION_DELEGLISE_RIVAT,
OPTION_DELEGLISE_RIVAT1,
OPTION_DELEGLISE_RIVAT2,
OPTION_DELEGLISE_RIVAT_PARALLEL1,
OPTION_DELEGLISE_RIVAT_PARALLEL2,
OPTION_DELEGLISE_RIVAT_PARALLEL3,
OPTION_HELP,
OPTION_LEGENDRE,
OPTION_LEHMER,
OPTION_LEHMER2,
OPTION_LMO,
OPTION_LMO1,
OPTION_LMO2,
OPTION_LMO3,
OPTION_LMO4,
OPTION_LMO5,
OPTION_LMO_PARALLEL1,
OPTION_LMO_PARALLEL2,
OPTION_LMO_PARALLEL3,
OPTION_LI,
OPTION_LIINV,
OPTION_MEISSEL,
OPTION_NTHPRIME,
OPTION_NUMBER,
OPTION_P2,
OPTION_PI,
OPTION_PRIMESIEVE,
OPTION_S1,
OPTION_S2_EASY,
OPTION_S2_HARD,
OPTION_S2_TRIVIAL,
OPTION_STATUS,
OPTION_TEST,
OPTION_TIME,
OPTION_THREADS,
OPTION_VERSION
};
struct PrimeCountOptions
{
maxint_t x;
int64_t option;
bool time;
int threads;
PrimeCountOptions() :
x(-1),
option(OPTION_PI),
time(false),
threads(get_num_threads())
{ }
};
PrimeCountOptions parseOptions(int, char**);
} // namespace primecount
#endif
<|endoftext|> |
<commit_before>#include <vector>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <string>
#include <regex>
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include "img_hash/AverageHash.h"
#include "img_hash/BlockMeanHash.h"
#include "img_hash/PerceptualHash.h"
#include "img_hash/PerceptualHash_Fast.h"
//#include "img_hash/FragmentHash.h"
//#include "ShapeAndPositionInvariantImage.h"
#include "Triangle.h"
#include "mainImageProcessingFunctions.hpp"
#include <boost/program_options.hpp>
#include <iostream>
#include "utils/utils.hpp"
#include "hiredis/hiredis.h"
#include <map>
using namespace std;
template<typename T> void dumpHashes(string imageName, string imagePoints, string imageFullPath)
{
auto triangles = getTheTris_random(imagePoints);
auto loadedImage = getLoadedImage(imageFullPath);
auto hashes = cv::getAllTheHashesForImage<T>(loadedImage, triangles, "inputImages/"+imageName+"/outputFragments");
writeHashObjectsToFile<T>("inputImages/"+ imageName + "/hashes.txt", hashes);
}
template <typename T> void testNonMatchingFragmentsForFalsePositive(string imageName, string imagePoints, string imageFullPath, int threshold = 3)
{
const string hashesFileFullPath = "inputImages/"+ imageName + "/hashes.txt";
const string excludeListFullPath = "inputImages/"+ imageName + "/excludeList.txt";
auto triangles = getTheTris(imagePoints);
auto loadedImage = getLoadedImage(imageFullPath);
auto hashes = loadHashesFromFile<T>(hashesFileFullPath);
cout << hashes.size() << " hashes found." << endl;
auto imageNames = loadImageNames("inputImages/imageNames.txt");
auto excludeList = loadExcludeList(excludeListFullPath);
cout << imageNames.size() << " image names found." << endl;
int finOutputArr[65] = {0};
for (auto name: imageNames)
{
int outputArr[65] = {0};
if ( !isInImageNameExcludeList(name, excludeList, imageName) ){
cout << "Output for image: " << name << endl;
auto toCompareHashes = loadHashesFromFile<T>("inputImages/"+ name + "/hashes.txt");
for (auto hash : hashes){
for (auto comp: toCompareHashes){
int dist = hash.getHammingDistance(comp);
if (dist < threshold){
cout << "ERROR: dist below threshold" << endl;
}
if (dist <= 64){
outputArr[dist] += 1;
}else{
cout << "ERROR: bad hamming distance: " << dist << endl;
exit(1);
}
}
}
for (unsigned int i = 0; i<64;i++)
{
cout << i << ": " << outputArr[i] << endl;
finOutputArr[i] += outputArr[i];
}
}
}
cout << "finoutput: " << endl;
for (unsigned int i = 0; i<64;i++)
{
cout << i << ": " << finOutputArr[i] << endl;
}
}
template<typename T> vector<int> testMatchingFragments(string imageName) {
int finOutputArr[65] = {0};
vector<Triangle> imageTris1;
vector<Triangle> imageTris2;
tie(imageTris2, imageTris1) = readMatchingTrianglesFromJsonFile("imageMatchingPairs/"+imageName+"/matchingTriangles.json");
auto loadedImage1 = getLoadedImage("imageMatchingPairs/"+imageName+"/img1.jpg");
auto loadedImage2 = getLoadedImage("imageMatchingPairs/"+imageName+"/img2.jpg");
auto hashes1 = cv::getAllTheHashesForImage<T>(loadedImage1, imageTris1, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
auto hashes2 = cv::getAllTheHashesForImage<T>(loadedImage2, imageTris2, "imageMatchingPairs/"+imageName+"/outputFragments", "2");
for (unsigned int i = 0; i < hashes1.size(); i++)
{
int dist = hashes1[i].getHammingDistance(hashes2[i]);
finOutputArr[dist] += 1;
//cout << "Distance of: " << hashes1[i].toString() << " and: " << hashes2[i].toString() << " is: " << dist << endl;
}
vector<int> ret;
for (int i = 0; i < 65; i++) {
ret.push_back(finOutputArr[i]);
}
return ret;
}
template<typename T> void testMatchingFragmentsForAllInputImages() {
//TODO:
auto imageNames = loadImageNames("inputImages/imageNames.txt");
int finOutputArr[65] = {0};
for(auto name: imageNames)
{
auto tempRes = testMatchingFragments<T>(name);
for (int i = 0; i < 65; i++){
finOutputArr[i] += tempRes[i];
}
}
for (int i = 0; i < 65; i++) {
cout << i << ": " << finOutputArr[i] << endl;
}
}
template<typename T> int hasingSpeedTestInner(string imageName, vector<Triangle> tris, ShapeAndPositionInvariantImage loadedImage)
{
auto hashes1 = cv::getAllTheHashesForImage<T>(loadedImage, tris, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
return 0;
}
template<typename T> vector<T> hasingSpeedTestInner_full(string imageName, vector<Triangle> tris, ShapeAndPositionInvariantImage loadedImage)
{
return cv::getAllTheHashesForImage<T>(loadedImage, tris, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
}
template<typename T> void hasingSpeedTestFull(string imageName) {
auto triangles = getTriangles("inputImages/"+imageName+"/keypoints2.json");
cv::Mat img = cv::imread("imageMatchingPairs/"+imageName+"/img1.jpg");
auto loadedImage1 = ShapeAndPositionInvariantImage("", img, std::vector<Keypoint>(), "");
cout << "About to processs " << triangles.size() << " triangles" << endl;
auto def = hasingSpeedTestInner_full<T>(imageName, triangles, loadedImage1);
cout << def.size() << endl;
}
template<typename T> void hasingSpeedTest(string imageName) {
vector<Triangle> imageTris1;
vector<Triangle> imageTris2;
tie(imageTris2, imageTris1) = readMatchingTrianglesFromJsonFile("imageMatchingPairs/"+imageName+"/matchingTriangles.json");
cv::Mat gray_image;
cv::Mat img = cv::imread("imageMatchingPairs/"+imageName+"/img1.jpg");
cv::cvtColor( img, gray_image, CV_BGR2GRAY );
auto loadedImage1 = ShapeAndPositionInvariantImage("", gray_image, std::vector<Keypoint>(), "");
// auto loadedImage1 = ShapeAndPositionInvariantImage("", img, std::vector<Keypoint>(), "");
for (int i = 0; i < 7; i++) {
imageTris2.insert(std::end(imageTris2), std::begin(imageTris2), std::end(imageTris2));
}
cout << "About to processs " << imageTris2.size() << " triangles" << endl;
auto def = hasingSpeedTestInner<T>(imageName, imageTris2, loadedImage1);
cout << def << endl;
}
void dumpThem(string imageName)
{
vector<Triangle> imageTris1;
vector<Triangle> imageTris2;
tie(imageTris2, imageTris1) = readMatchingTrianglesFromJsonFile("imageMatchingPairs/"+imageName+"/matchingTriangles.json");
auto loadedImage1 = getLoadedImage("imageMatchingPairs/"+imageName+"/img1.jpg");
auto loadedImage2 = getLoadedImage("imageMatchingPairs/"+imageName+"/img2.jpg");
auto hashes1 = cv::getAllTheHashesForImage<hashes::PerceptualHash>(loadedImage1, imageTris1, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
dumpHashesToJsonFile<hashes::PerceptualHash>("c_src/test/resources/savedHashes.json", hashes1);
}
void addAllHashesToRedis(string imageName){
vector<Triangle> tris = getTriangles("../inputImages/"+imageName+"/keypoints2.json");
auto loadedImage = getLoadedImage("../inputImages/"+imageName+"/"+imageName+".jpg");
auto hashes = cv::getAllTheHashesForImage<hashes::PerceptualHash>(loadedImage, tris, "../inputImages/"+imageName+"/outputFragments", "1");
redisContext *c;
// redisReply *reply;
const char *hostname = "127.0.0.1";
int port = 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
for (auto hash : hashes)
{
redisCommand(c,"SET %s %s", hash.toString().c_str(), imageName.c_str());
}
}
void findMatchingHashInRedis(string imageName){
vector<Triangle> tris = getTriangles("../inputImages/"+imageName+"/keypoints2.json");
auto loadedImage = getLoadedImage("../inputImages/"+imageName+"/"+imageName+".jpg");
auto hashes = cv::getAllTheHashesForImage<hashes::PerceptualHash>(loadedImage, tris, "../inputImages/"+imageName+"/outputFragments", "1");
redisContext *c;
redisReply *reply;
const char *hostname = "127.0.0.1";
int port = 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
cout << "finished hashing" << endl;
// vector<hashes::PerceptualHash_Fast> result;
vector<string> result;
// for (auto hash : hashes)
// {
unsigned int batchSize = 1000;
for (unsigned int i = 0; i < hashes.size(); i++)
{
unsigned int j = 0;
for(;i < hashes.size() && j < batchSize; j++, i++){
auto hash = hashes[i];
redisAppendCommand(c,"GET %s", hash.toString().c_str());
}
for(; j > 0; j--){
redisGetReply(c, (void **) &reply );
//unsigned int r = redisGetReply(c, (void **) &reply );
if(reply->str != nullptr){
string str(reply->str);
result.push_back(str);
}
}
}
std::map<string,int> mymap;
for (auto t_str : result)
{
mymap[t_str] = mymap[t_str] + 1;
}
cout << "Matches:" << endl;
for(auto const& ent1 : mymap)
{
cout << ent1.first << ": " << ent1.second << endl;
}
cout << "Number of matches: " << result.size() << endl;
}
int main(int argc, char* argv[])
{
if (argc < 3){
printf("error: no args!!!\n");
return -1;
}
string imageName = (argc > 2)? argv[2]: "img1";
string imageFullPath = "inputImages/"+ imageName + "/" + imageName + ".jpg";
string imagePoints = "inputImages/"+ imageName + "/keypoints.txt";
if (argc > 2 && !strcmp(argv[1], "dumpRandom")){
cout << "Dumping image hashes for: " << imageName << endl;
dumpHashes<hashes::PerceptualHash>(imageName, imagePoints, imageFullPath);
}else if (argc > 2 && !strcmp(argv[1], "printConflicts")){
cout << "Printing conflicts: " << imageName << endl;
testNonMatchingFragmentsForFalsePositive<hashes::PerceptualHash>(imageName, imagePoints, imageFullPath);
}else if (argc > 2 && !strcmp(argv[1], "testMatching")){
testMatchingFragments<hashes::PerceptualHash>(imageName);
}else if (argc > 2 && !strcmp(argv[1], "testAllMatching")){
testMatchingFragmentsForAllInputImages<hashes::PerceptualHash_Fast>();
}else if (argc > 2 && !strcmp(argv[1], "speedTest")){
hasingSpeedTestFull<hashes::PerceptualHash_Fast>(imageName);
}else if (argc > 2 && !strcmp(argv[1], "dumpThem")){
dumpThem(imageName);
}else if (argc > 2 && !strcmp(argv[1], "addRedisImage")){
addAllHashesToRedis(imageName);
}else if (argc > 2 && !strcmp(argv[1], "checkRedisImage")){
findMatchingHashInRedis(imageName);
}else{
cout << "Bad argument: " << argv[1] << endl;
}
}
<commit_msg>it now uses set commands<commit_after>#include <vector>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <string>
#include <regex>
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include "img_hash/AverageHash.h"
#include "img_hash/BlockMeanHash.h"
#include "img_hash/PerceptualHash.h"
#include "img_hash/PerceptualHash_Fast.h"
//#include "img_hash/FragmentHash.h"
//#include "ShapeAndPositionInvariantImage.h"
#include "Triangle.h"
#include "mainImageProcessingFunctions.hpp"
#include <boost/program_options.hpp>
#include <iostream>
#include "utils/utils.hpp"
#include "hiredis/hiredis.h"
#include <map>
using namespace std;
template<typename T> void dumpHashes(string imageName, string imagePoints, string imageFullPath)
{
auto triangles = getTheTris_random(imagePoints);
auto loadedImage = getLoadedImage(imageFullPath);
auto hashes = cv::getAllTheHashesForImage<T>(loadedImage, triangles, "inputImages/"+imageName+"/outputFragments");
writeHashObjectsToFile<T>("inputImages/"+ imageName + "/hashes.txt", hashes);
}
template <typename T> void testNonMatchingFragmentsForFalsePositive(string imageName, string imagePoints, string imageFullPath, int threshold = 3)
{
const string hashesFileFullPath = "inputImages/"+ imageName + "/hashes.txt";
const string excludeListFullPath = "inputImages/"+ imageName + "/excludeList.txt";
auto triangles = getTheTris(imagePoints);
auto loadedImage = getLoadedImage(imageFullPath);
auto hashes = loadHashesFromFile<T>(hashesFileFullPath);
cout << hashes.size() << " hashes found." << endl;
auto imageNames = loadImageNames("inputImages/imageNames.txt");
auto excludeList = loadExcludeList(excludeListFullPath);
cout << imageNames.size() << " image names found." << endl;
int finOutputArr[65] = {0};
for (auto name: imageNames)
{
int outputArr[65] = {0};
if ( !isInImageNameExcludeList(name, excludeList, imageName) ){
cout << "Output for image: " << name << endl;
auto toCompareHashes = loadHashesFromFile<T>("inputImages/"+ name + "/hashes.txt");
for (auto hash : hashes){
for (auto comp: toCompareHashes){
int dist = hash.getHammingDistance(comp);
if (dist < threshold){
cout << "ERROR: dist below threshold" << endl;
}
if (dist <= 64){
outputArr[dist] += 1;
}else{
cout << "ERROR: bad hamming distance: " << dist << endl;
exit(1);
}
}
}
for (unsigned int i = 0; i<64;i++)
{
cout << i << ": " << outputArr[i] << endl;
finOutputArr[i] += outputArr[i];
}
}
}
cout << "finoutput: " << endl;
for (unsigned int i = 0; i<64;i++)
{
cout << i << ": " << finOutputArr[i] << endl;
}
}
template<typename T> vector<int> testMatchingFragments(string imageName) {
int finOutputArr[65] = {0};
vector<Triangle> imageTris1;
vector<Triangle> imageTris2;
tie(imageTris2, imageTris1) = readMatchingTrianglesFromJsonFile("imageMatchingPairs/"+imageName+"/matchingTriangles.json");
auto loadedImage1 = getLoadedImage("imageMatchingPairs/"+imageName+"/img1.jpg");
auto loadedImage2 = getLoadedImage("imageMatchingPairs/"+imageName+"/img2.jpg");
auto hashes1 = cv::getAllTheHashesForImage<T>(loadedImage1, imageTris1, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
auto hashes2 = cv::getAllTheHashesForImage<T>(loadedImage2, imageTris2, "imageMatchingPairs/"+imageName+"/outputFragments", "2");
for (unsigned int i = 0; i < hashes1.size(); i++)
{
int dist = hashes1[i].getHammingDistance(hashes2[i]);
finOutputArr[dist] += 1;
//cout << "Distance of: " << hashes1[i].toString() << " and: " << hashes2[i].toString() << " is: " << dist << endl;
}
vector<int> ret;
for (int i = 0; i < 65; i++) {
ret.push_back(finOutputArr[i]);
}
return ret;
}
template<typename T> void testMatchingFragmentsForAllInputImages() {
//TODO:
auto imageNames = loadImageNames("inputImages/imageNames.txt");
int finOutputArr[65] = {0};
for(auto name: imageNames)
{
auto tempRes = testMatchingFragments<T>(name);
for (int i = 0; i < 65; i++){
finOutputArr[i] += tempRes[i];
}
}
for (int i = 0; i < 65; i++) {
cout << i << ": " << finOutputArr[i] << endl;
}
}
template<typename T> int hasingSpeedTestInner(string imageName, vector<Triangle> tris, ShapeAndPositionInvariantImage loadedImage)
{
auto hashes1 = cv::getAllTheHashesForImage<T>(loadedImage, tris, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
return 0;
}
template<typename T> vector<T> hasingSpeedTestInner_full(string imageName, vector<Triangle> tris, ShapeAndPositionInvariantImage loadedImage)
{
return cv::getAllTheHashesForImage<T>(loadedImage, tris, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
}
template<typename T> void hasingSpeedTestFull(string imageName) {
auto triangles = getTriangles("inputImages/"+imageName+"/keypoints2.json");
cv::Mat img = cv::imread("imageMatchingPairs/"+imageName+"/img1.jpg");
auto loadedImage1 = ShapeAndPositionInvariantImage("", img, std::vector<Keypoint>(), "");
cout << "About to processs " << triangles.size() << " triangles" << endl;
auto def = hasingSpeedTestInner_full<T>(imageName, triangles, loadedImage1);
cout << def.size() << endl;
}
template<typename T> void hasingSpeedTest(string imageName) {
vector<Triangle> imageTris1;
vector<Triangle> imageTris2;
tie(imageTris2, imageTris1) = readMatchingTrianglesFromJsonFile("imageMatchingPairs/"+imageName+"/matchingTriangles.json");
cv::Mat gray_image;
cv::Mat img = cv::imread("imageMatchingPairs/"+imageName+"/img1.jpg");
cv::cvtColor( img, gray_image, CV_BGR2GRAY );
auto loadedImage1 = ShapeAndPositionInvariantImage("", gray_image, std::vector<Keypoint>(), "");
// auto loadedImage1 = ShapeAndPositionInvariantImage("", img, std::vector<Keypoint>(), "");
for (int i = 0; i < 7; i++) {
imageTris2.insert(std::end(imageTris2), std::begin(imageTris2), std::end(imageTris2));
}
cout << "About to processs " << imageTris2.size() << " triangles" << endl;
auto def = hasingSpeedTestInner<T>(imageName, imageTris2, loadedImage1);
cout << def << endl;
}
void dumpThem(string imageName)
{
vector<Triangle> imageTris1;
vector<Triangle> imageTris2;
tie(imageTris2, imageTris1) = readMatchingTrianglesFromJsonFile("imageMatchingPairs/"+imageName+"/matchingTriangles.json");
auto loadedImage1 = getLoadedImage("imageMatchingPairs/"+imageName+"/img1.jpg");
auto loadedImage2 = getLoadedImage("imageMatchingPairs/"+imageName+"/img2.jpg");
auto hashes1 = cv::getAllTheHashesForImage<hashes::PerceptualHash>(loadedImage1, imageTris1, "imageMatchingPairs/"+imageName+"/outputFragments", "1");
dumpHashesToJsonFile<hashes::PerceptualHash>("c_src/test/resources/savedHashes.json", hashes1);
}
void addAllHashesToRedis(string imageName){
vector<Triangle> tris = getTriangles("../inputImages/"+imageName+"/keypoints2.json");
auto loadedImage = getLoadedImage("../inputImages/"+imageName+"/"+imageName+".jpg");
auto hashes = cv::getAllTheHashesForImage<hashes::PerceptualHash>(loadedImage, tris, "../inputImages/"+imageName+"/outputFragments", "1");
redisContext *c;
// redisReply *reply;
const char *hostname = "127.0.0.1";
int port = 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
for (auto hash : hashes)
{
redisCommand(c,"SADD %s %s", hash.toString().c_str(), imageName.c_str());
}
}
void findMatchingHashInRedis(string imageName){
vector<Triangle> tris = getTriangles("../inputImages/"+imageName+"/keypoints2.json");
auto loadedImage = getLoadedImage("../inputImages/"+imageName+"/"+imageName+".jpg");
auto hashes = cv::getAllTheHashesForImage<hashes::PerceptualHash>(loadedImage, tris, "../inputImages/"+imageName+"/outputFragments", "1");
redisContext *c;
redisReply *reply;
const char *hostname = "127.0.0.1";
int port = 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
cout << "finished hashing" << endl;
// vector<hashes::PerceptualHash_Fast> result;
vector<string> result;
// for (auto hash : hashes)
// {
unsigned int batchSize = 1000;
for (unsigned int i = 0; i < hashes.size(); i++)
{
unsigned int j = 0;
for(;i < hashes.size() && j < batchSize; j++, i++){
auto hash = hashes[i];
redisAppendCommand(c,"SMEMBERS %s", hash.toString().c_str());
}
for(; j > 0; j--){
redisGetReply(c, (void **) &reply );
//unsigned int r = redisGetReply(c, (void **) &reply );
if (reply->type == REDIS_REPLY_ARRAY) {
for (j = 0; j < reply->elements; j++) {
string str(reply->str);
result.push_back(str);
}
}
}
}
std::map<string,int> mymap;
for (auto t_str : result)
{
mymap[t_str] = mymap[t_str] + 1;
}
cout << "Matches:" << endl;
for(auto const& ent1 : mymap)
{
cout << ent1.first << ": " << ent1.second << endl;
}
cout << "Number of matches: " << result.size() << endl;
}
int main(int argc, char* argv[])
{
if (argc < 3){
printf("error: no args!!!\n");
return -1;
}
string imageName = (argc > 2)? argv[2]: "img1";
string imageFullPath = "inputImages/"+ imageName + "/" + imageName + ".jpg";
string imagePoints = "inputImages/"+ imageName + "/keypoints.txt";
if (argc > 2 && !strcmp(argv[1], "dumpRandom")){
cout << "Dumping image hashes for: " << imageName << endl;
dumpHashes<hashes::PerceptualHash>(imageName, imagePoints, imageFullPath);
}else if (argc > 2 && !strcmp(argv[1], "printConflicts")){
cout << "Printing conflicts: " << imageName << endl;
testNonMatchingFragmentsForFalsePositive<hashes::PerceptualHash>(imageName, imagePoints, imageFullPath);
}else if (argc > 2 && !strcmp(argv[1], "testMatching")){
testMatchingFragments<hashes::PerceptualHash>(imageName);
}else if (argc > 2 && !strcmp(argv[1], "testAllMatching")){
testMatchingFragmentsForAllInputImages<hashes::PerceptualHash_Fast>();
}else if (argc > 2 && !strcmp(argv[1], "speedTest")){
hasingSpeedTestFull<hashes::PerceptualHash_Fast>(imageName);
}else if (argc > 2 && !strcmp(argv[1], "dumpThem")){
dumpThem(imageName);
}else if (argc > 2 && !strcmp(argv[1], "addRedisImage")){
addAllHashesToRedis(imageName);
}else if (argc > 2 && !strcmp(argv[1], "checkRedisImage")){
findMatchingHashInRedis(imageName);
}else{
cout << "Bad argument: " << argv[1] << endl;
}
}
<|endoftext|> |
<commit_before>#include "gum/Statistics.h"
#include "gum/StatFPS.h"
#include "gum/StatTag.h"
#include "gum/GUM_GTxt.h"
#include <logger.h>
#include <glp_loop.h>
#include <ps_3d.h>
#include <sprite2/pre_defined.h>
#include S2_MAT_HEADER
#include <sprite2/StatDrawCall.h>
#include <sprite2/StatPingPong.h>
#include <sprite2/StatTopNodes.h>
#include <sprite2/StatSymbol.h>
#include <shaderlab/ShaderMgr.h>
#include <shaderlab/Statistics.h>
#include <shaderlab/StatDrawCall.h>
#include <string>
#include <time.h>
namespace gum
{
SINGLETON_DEFINITION(Statistics);
static const float FPS_SMOOTHING = 0.99f;
Statistics::Statistics()
: m_flags(0)
, m_tpf(0)
, m_tpf_smooth(0)
, m_no_stat_begin(0)
, m_no_stat_tot(0)
, m_opt_enable(false)
{
memset(&m_mem, 0, sizeof(m_mem));
}
void Statistics::EnableGraph(bool enable)
{
if (enable) {
m_flags |= FLAG_PRINT_GRAPH;
} else {
m_flags &= ~FLAG_PRINT_GRAPH;
}
}
void Statistics::EnableConsole(bool enable)
{
if (enable) {
m_flags |= FLAG_PRINT_CONSOLE;
} else {
m_flags &= ~FLAG_PRINT_CONSOLE;
}
}
void Statistics::EnableFile(bool enable)
{
if (enable == IsFileEnable()) {
return;
}
if (enable)
{
m_flags |= FLAG_PRINT_FILE;
#ifdef __ANDROID__
m_fout.open("/sdcard/lr_stat.bin", std::ofstream::out | std::ofstream::binary);
#else
m_fout.open("lr_stat.bin", std::ofstream::out | std::ofstream::binary);
#endif // __ANDROID__
}
else
{
m_flags &= ~FLAG_PRINT_FILE;
m_fout.close();
}
}
bool Statistics::IsGraphEnable() const
{
return (m_flags & FLAG_PRINT_GRAPH) != 0;
}
bool Statistics::IsConsoleEnable() const
{
return (m_flags & FLAG_PRINT_CONSOLE) != 0;
}
bool Statistics::IsFileEnable() const
{
return (m_flags & FLAG_PRINT_FILE) != 0;
}
void Statistics::Update()
{
if (m_flags == 0) {
return;
}
m_tpf = glp_get_dt();
m_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING);
StatFPS::Instance()->Update();
}
void Statistics::Print()
{
StatTag::Instance()->PrintScreen();
if (m_flags == 0) {
return;
}
if (m_flags & FLAG_PRINT_GRAPH) {
PrintScreen();
}
if (m_flags & FLAG_PRINT_CONSOLE) {
PrintConsole();
}
if (m_flags & FLAG_PRINT_FILE) {
PrintFile();
}
}
void Statistics::Reset()
{
if (m_flags == 0) {
return;
}
m_tpf = 0;
sl::Statistics::Instance()->Reset();
sl::StatDrawCall::Instance()->Reset();
s2::StatDrawCall::Instance()->Reset();
s2::StatPingPong::Instance()->Reset();
s2::StatTopNodes::Instance()->Reset();
s2::StatSymbol::Instance()->Reset();
}
void Statistics::Flush()
{
StatTag::Instance()->Flush();
}
void Statistics::NoStatBegin()
{
m_no_stat_begin = glp_get_time();
}
void Statistics::NoStatEnd()
{
m_no_stat_tot = (glp_get_time() - m_no_stat_begin);
}
void Statistics::OptEnable(bool enable)
{
m_opt_enable = enable;
}
void Statistics::SetMem(float tot, float lua)
{
m_mem.tot = tot;
m_mem.lua = lua;
}
void Statistics::PrintScreen() const
{
sl::ShaderMgr* mgr = sl::ShaderMgr::Instance();
mgr->SetShader(sl::SPRITE2);
static char buf[512];
const int w = 960;
const int top = 280;
S2_MAT mt;
mt.Translate(0, top);
sprintf(buf, "OPT: %s, emitter: %d", m_opt_enable ? "open" : "closed", p3d_emitter_count());
GTxt::Instance()->Draw(mt, buf, w);
mt.Translate(0, -30);
sprintf(buf, "FPS: %.1f, ms: %.1f, ex:%.1f", 1000.0f / m_tpf, m_tpf_smooth, m_no_stat_tot / 1000.0f);
GTxt::Instance()->Draw(mt, buf, w);
mt.Translate(0, -30);
sprintf(buf, "MEM: tot %.1f, tex %.1f, lua %.1f", m_mem.tot, m_mem.tex, m_mem.lua);
GTxt::Instance()->Draw(mt, buf, w);
static std::string buf_str;
buf_str.reserve(512);
mt.Translate(0, -30);
sl::Statistics::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(0, -30);
s2::StatDrawCall::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(0, -40);
s2::StatPingPong::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(0, -200);
s2::StatTopNodes::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(450, 180);
s2::StatSymbol::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(0, -230);
sl::StatDrawCall::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mgr->FlushShader();
}
void Statistics::PrintConsole() const
{
static const int PRINT_COUNT = 30;
static int count = 0;
++count;
if (count == PRINT_COUNT) {
count = 0;
LOGI("fps %.1f, cost %.1f\n", 1000.0f / m_tpf_smooth, m_tpf_smooth);
}
}
void Statistics::PrintFile() const
{
sl::Statistics* sl_stat = sl::Statistics::Instance();
static char buf[512];
sprintf(buf, "timestamp %lu, cost %.1f, vertices %d, dc %d\n",
time(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall());
m_fout << buf;
static const int FLUSH_COUNT = 100;
static int count = 0;
++count;
if (count == FLUSH_COUNT) {
count = 0;
m_fout.flush();
}
}
}<commit_msg>[CHANGED] stat view<commit_after>#include "gum/Statistics.h"
#include "gum/StatFPS.h"
#include "gum/StatTag.h"
#include "gum/GUM_GTxt.h"
#include <logger.h>
#include <glp_loop.h>
#include <ps_3d.h>
#include <sprite2/pre_defined.h>
#include S2_MAT_HEADER
#include <sprite2/StatDrawCall.h>
#include <sprite2/StatPingPong.h>
#include <sprite2/StatTopNodes.h>
#include <sprite2/StatSymbol.h>
#include <shaderlab/ShaderMgr.h>
#include <shaderlab/Statistics.h>
#include <shaderlab/StatDrawCall.h>
#include <string>
#include <time.h>
namespace gum
{
SINGLETON_DEFINITION(Statistics);
static const float FPS_SMOOTHING = 0.99f;
Statistics::Statistics()
: m_flags(0)
, m_tpf(0)
, m_tpf_smooth(0)
, m_no_stat_begin(0)
, m_no_stat_tot(0)
, m_opt_enable(false)
{
memset(&m_mem, 0, sizeof(m_mem));
}
void Statistics::EnableGraph(bool enable)
{
if (enable) {
m_flags |= FLAG_PRINT_GRAPH;
} else {
m_flags &= ~FLAG_PRINT_GRAPH;
}
}
void Statistics::EnableConsole(bool enable)
{
if (enable) {
m_flags |= FLAG_PRINT_CONSOLE;
} else {
m_flags &= ~FLAG_PRINT_CONSOLE;
}
}
void Statistics::EnableFile(bool enable)
{
if (enable == IsFileEnable()) {
return;
}
if (enable)
{
m_flags |= FLAG_PRINT_FILE;
#ifdef __ANDROID__
m_fout.open("/sdcard/lr_stat.bin", std::ofstream::out | std::ofstream::binary);
#else
m_fout.open("lr_stat.bin", std::ofstream::out | std::ofstream::binary);
#endif // __ANDROID__
}
else
{
m_flags &= ~FLAG_PRINT_FILE;
m_fout.close();
}
}
bool Statistics::IsGraphEnable() const
{
return (m_flags & FLAG_PRINT_GRAPH) != 0;
}
bool Statistics::IsConsoleEnable() const
{
return (m_flags & FLAG_PRINT_CONSOLE) != 0;
}
bool Statistics::IsFileEnable() const
{
return (m_flags & FLAG_PRINT_FILE) != 0;
}
void Statistics::Update()
{
if (m_flags == 0) {
return;
}
m_tpf = glp_get_dt();
m_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING);
StatFPS::Instance()->Update();
}
void Statistics::Print()
{
StatTag::Instance()->PrintScreen();
if (m_flags == 0) {
return;
}
if (m_flags & FLAG_PRINT_GRAPH) {
PrintScreen();
}
if (m_flags & FLAG_PRINT_CONSOLE) {
PrintConsole();
}
if (m_flags & FLAG_PRINT_FILE) {
PrintFile();
}
}
void Statistics::Reset()
{
if (m_flags == 0) {
return;
}
m_tpf = 0;
sl::Statistics::Instance()->Reset();
sl::StatDrawCall::Instance()->Reset();
s2::StatDrawCall::Instance()->Reset();
s2::StatPingPong::Instance()->Reset();
s2::StatTopNodes::Instance()->Reset();
s2::StatSymbol::Instance()->Reset();
}
void Statistics::Flush()
{
StatTag::Instance()->Flush();
}
void Statistics::NoStatBegin()
{
m_no_stat_begin = glp_get_time();
}
void Statistics::NoStatEnd()
{
m_no_stat_tot = (glp_get_time() - m_no_stat_begin);
}
void Statistics::OptEnable(bool enable)
{
m_opt_enable = enable;
}
void Statistics::SetMem(float tot, float lua)
{
m_mem.tot = tot;
m_mem.lua = lua;
}
void Statistics::PrintScreen() const
{
sl::ShaderMgr* mgr = sl::ShaderMgr::Instance();
mgr->SetShader(sl::SPRITE2);
static char buf[512];
const int w = 960;
const int top = 280;
S2_MAT mt;
mt.Translate(0, top);
sprintf(buf, "OPT: %s, emitter: %d", m_opt_enable ? "open" : "closed", p3d_emitter_count());
GTxt::Instance()->Draw(mt, buf, w);
mt.Translate(0, -30);
sprintf(buf, "FPS: %.1f, ms: %.1f, ex:%.1f", 1000.0f / m_tpf, m_tpf_smooth, m_no_stat_tot / 1000.0f);
GTxt::Instance()->Draw(mt, buf, w);
mt.Translate(0, -30);
sprintf(buf, "MEM: tot %.1f, tex %.1f, lua %.1f", m_mem.tot, m_mem.tex, m_mem.lua);
GTxt::Instance()->Draw(mt, buf, w);
static std::string buf_str;
buf_str.reserve(512);
mt.Translate(0, -30);
sl::Statistics::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(0, -30);
s2::StatDrawCall::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(0, -40);
s2::StatPingPong::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
mt.Translate(450, -100);
s2::StatTopNodes::Instance()->Print(buf_str);
GTxt::Instance()->Draw(mt, buf_str, w);
buf_str.clear();
// mt.Translate(450, 180);
// s2::StatSymbol::Instance()->Print(buf_str);
// GTxt::Instance()->Draw(mt, buf_str, w);
// buf_str.clear();
// mt.Translate(0, -230);
// sl::StatDrawCall::Instance()->Print(buf_str);
// GTxt::Instance()->Draw(mt, buf_str, w);
// buf_str.clear();
mgr->FlushShader();
}
void Statistics::PrintConsole() const
{
static const int PRINT_COUNT = 30;
static int count = 0;
++count;
if (count == PRINT_COUNT) {
count = 0;
LOGI("fps %.1f, cost %.1f\n", 1000.0f / m_tpf_smooth, m_tpf_smooth);
}
}
void Statistics::PrintFile() const
{
sl::Statistics* sl_stat = sl::Statistics::Instance();
static char buf[512];
sprintf(buf, "timestamp %lu, cost %.1f, vertices %d, dc %d\n",
time(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall());
m_fout << buf;
static const int FLUSH_COUNT = 100;
static int count = 0;
++count;
if (count == FLUSH_COUNT) {
count = 0;
m_fout.flush();
}
}
}<|endoftext|> |
<commit_before>#include <ros/console.h>
#include <string>
#include <teraranger_array/RangeArray.h>
#include <teraranger_array/teraranger_evo.h>
#include <teraranger_array/helper_lib.h>
namespace teraranger_array
{
TerarangerHubEvo::TerarangerHubEvo()
{
// Get parameters and namespace
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_,
std::string("/dev/ttyACM0"));
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
if (ns_ != "" && ns_[0] == '/')
{ // Remove first backslash if needed
ns_.erase(0,1);
}
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Publishers
range_publisher_ = nh_.advertise<teraranger_array::RangeArray>("teraranger_evo/ranges", 10);
imu_publisher_ = nh_.advertise<sensor_msgs::Imu>("teraranger_evo/imu", 10);
// Serial Port init
serial_port_.setPort(portname_);
serial_port_.setBaudrate(115200);
serial_port_.setParity(serial::parity_none);
serial_port_.setStopbits(serial::stopbits_one);
serial_port_.setBytesize(serial::eightbits);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
serial_port_.setTimeout(to);
serial_port_.open();
if(!serial_port_.isOpen())
{
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:",
ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(),
portname_.c_str());
//Initialize local parameters and measurement array
field_of_view = 0.03491;
max_range = 14.0;
min_range = 0.2;
number_of_sensor = 8;
frame_id = "base_range_";
// Initialize rangeArray
for (size_t i=0; i < number_of_sensor; i++)
{
sensor_msgs::Range range;
range.field_of_view = field_of_view;
range.max_range = max_range;
range.min_range = min_range;
range.radiation_type = sensor_msgs::Range::INFRARED;
range.range = 0.0;
// set the right range frame depending of the namespace
if (ns_ == "")
{
range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i);
}
else
{
range.header.frame_id = ns_ + '_'+ frame_id + boost::lexical_cast<std::string>(i);
}
range_array_msg.ranges.push_back(range);
}
// Initialize IMU message
sensor_msgs::Imu imu_msg;
// set the right RangeArray and IMU frame depending of the namespace
if (ns_ == "")
{
range_array_msg.header.frame_id = "base_hub";
imu_msg.header.frame_id = "base_hub";
}
else
{
range_array_msg.header.frame_id = "base_" + ns_;
imu_msg.header.frame_id = "base_" + ns_;
}
// This line is needed to start measurements on the hub
setMode(BINARY_MODE, 4);
setMode(TOWER_MODE, 4);
setMode(RATE_ASAP, 5);
setMode(ENABLE_CMD, 5);
setMode(IMU_EULER,4);
imu_status = euler;
// Dynamic reconfigure
dyn_param_server_callback_function_ =
boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubEvo::~TerarangerHubEvo() {}
void TerarangerHubEvo::setMode(const char *c, int length)
{
serial_port_.write((uint8_t*)c, length);
serial_port_.flushOutput();
}
void TerarangerHubEvo::dynParamCallback(
const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level)
{
ROS_INFO("Dynamic reconfigure call");
// Set the mode dynamically
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary)
{
setMode(BINARY_MODE, 4);
}
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text)
{
setMode(TEXT_MODE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Long_range)
{
setMode(LONG_RANGE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Short_range)
{
setMode(SHORT_RANGE, 4);
}
// Set the rate dynamically
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP)
{
setMode(RATE_ASAP, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700)
{
setMode(RATE_700, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600)
{
setMode(RATE_600, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500)
{
setMode(RATE_500, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250)
{
setMode(RATE_250, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100)
{
setMode(RATE_100, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50)
{
setMode(RATE_50, 5);
}
// Set the IMU mode dynamically
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_OFF)
{
setMode(IMU_OFF,4);
imu_status = off;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUAT)
{
setMode(IMU_QUAT,4);
imu_status = quat;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_EULER)
{
setMode(IMU_EULER,4);
imu_status = euler;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUATLIN)
{
setMode(IMU_QUATLIN,4);
imu_status = quatlin;
}
//Set the sequence mode dynamically
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Crosstalk)
{
setMode(CROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Non_crosstalk)
{
setMode(NONCROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Tower_mode)
{
setMode(TOWER_MODE,4);
}
//Set VCP state dynamically
if(config.Enable_VCP)
{
setMode(ENABLE_CMD, 5);
}
else
{
setMode(DISABLE_CMD, 5);
}
}
void TerarangerHubEvo::processRangeFrame(uint8_t* input_buffer, int seq_ctr)
{
//Processing full range frame
uint8_t crc = HelperLib::crc8(input_buffer, 19);
if (crc == input_buffer[RANGE_CRC_POS])
{
for (size_t i=0; i < range_array_msg.ranges.size(); i++)
{
range_array_msg.ranges.at(i).header.stamp = ros::Time::now();
range_array_msg.ranges.at(i).header.seq = seq_ctr++;
// Convert bytes to range
// Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8
char c1 = input_buffer[2 * (i + 1)];
char c2 = input_buffer[2 * (i + 1) + 1];
ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF));
int16_t current_range = (c1 & 0x0FF) << 8;
current_range |= (c2 & 0x0FF);
float float_range = (float)current_range;
ROS_DEBUG("Value int : %d | float : %f", current_range, float_range);
if (current_range <= 1 || current_range == 255)
{
float_range = -1.0;
}
else
{
float_range = float_range * 0.001;
}
range_array_msg.ranges.at(i).range = float_range;
}
range_array_msg.header.seq = (int) seq_ctr / 8;
range_array_msg.header.stamp = ros::Time::now();
range_publisher_.publish(range_array_msg);
}
else
{
ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str());
}
}
void TerarangerHubEvo::processImuFrame(uint8_t* input_buffer, int seq_ctr)
{
if (imu_status == imu_mode::off)
{
return;
}
else if (imu_status == imu_mode::quat)
{
}
else if (imu_status == imu_mode::euler)
{
}
else if (imu_status == imu_mode::quatlin)
{
}
imu_msg.header.seq = seq_ctr;
imu_msg.header.stamp = ros::Time::now();
imu_publisher_.publish(imu_msg);
}
void TerarangerHubEvo::serialDataCallback(uint8_t single_character)
{
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int seq_ctr = 0;
ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character);
if (buffer_ctr == 0)
{
if (single_character == 'T' || single_character == 'I')
{
// Waiting for T or an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
else if (buffer_ctr == 1)
{
if (single_character == 'H' || single_character == 'M')
{
// Waiting for H after a T or an M after an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
if (buffer_ctr > 1)
{
if (input_buffer[0] == 'T')// Parsing ranges
{
// Gathering after-header range data
if (buffer_ctr < RANGES_FRAME_LENGTH)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == RANGES_FRAME_LENGTH)
{
processRangeFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > RANGES_FRAME_LENGTH)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
else if (input_buffer[0] == 'I')// Parsing Imu
{
// ROS_INFO("%d", imu_status);
// Gathering after-header imu data
if (buffer_ctr < IMU_EULER_FRAME_LENGHT)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == IMU_EULER_FRAME_LENGHT)
{
processImuFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > IMU_EULER_FRAME_LENGHT)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
// resetting buffer and ctr
buffer_ctr = 0;
bzero(&input_buffer, BUFFER_SIZE);
// Appending current char to hook next frame
input_buffer[buffer_ctr++] = single_character;
}
}
void TerarangerHubEvo::spin()
{
static uint8_t buffer[1];
while(ros::ok())
{
serial_port_.read(buffer, 1);
serialDataCallback(buffer[0]);
ros::spinOnce();
}
setMode(DISABLE_CMD, 5);
}
}// end of namespace
int main(int argc, char **argv) {
ros::init(argc, argv, "teraranger_hub_evo");
teraranger_array::TerarangerHubEvo node;
node.spin();
return 0;
}
<commit_msg>Change default imu mode to quat<commit_after>#include <ros/console.h>
#include <string>
#include <teraranger_array/RangeArray.h>
#include <teraranger_array/teraranger_evo.h>
#include <teraranger_array/helper_lib.h>
namespace teraranger_array
{
TerarangerHubEvo::TerarangerHubEvo()
{
// Get parameters and namespace
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_,
std::string("/dev/ttyACM0"));
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
if (ns_ != "" && ns_[0] == '/')
{ // Remove first backslash if needed
ns_.erase(0,1);
}
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Publishers
range_publisher_ = nh_.advertise<teraranger_array::RangeArray>("teraranger_evo/ranges", 10);
imu_publisher_ = nh_.advertise<sensor_msgs::Imu>("teraranger_evo/imu", 10);
// Serial Port init
serial_port_.setPort(portname_);
serial_port_.setBaudrate(115200);
serial_port_.setParity(serial::parity_none);
serial_port_.setStopbits(serial::stopbits_one);
serial_port_.setBytesize(serial::eightbits);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
serial_port_.setTimeout(to);
serial_port_.open();
if(!serial_port_.isOpen())
{
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:",
ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(),
portname_.c_str());
//Initialize local parameters and measurement array
field_of_view = 0.03491;
max_range = 14.0;
min_range = 0.2;
number_of_sensor = 8;
frame_id = "base_range_";
// Initialize rangeArray
for (size_t i=0; i < number_of_sensor; i++)
{
sensor_msgs::Range range;
range.field_of_view = field_of_view;
range.max_range = max_range;
range.min_range = min_range;
range.radiation_type = sensor_msgs::Range::INFRARED;
range.range = 0.0;
// set the right range frame depending of the namespace
if (ns_ == "")
{
range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i);
}
else
{
range.header.frame_id = ns_ + '_'+ frame_id + boost::lexical_cast<std::string>(i);
}
range_array_msg.ranges.push_back(range);
}
// Initialize IMU message
sensor_msgs::Imu imu_msg;
// set the right RangeArray and IMU frame depending of the namespace
if (ns_ == "")
{
range_array_msg.header.frame_id = "base_hub";
imu_msg.header.frame_id = "base_hub";
}
else
{
range_array_msg.header.frame_id = "base_" + ns_;
imu_msg.header.frame_id = "base_" + ns_;
}
// This line is needed to start measurements on the hub
setMode(BINARY_MODE, 4);
setMode(TOWER_MODE, 4);
setMode(RATE_ASAP, 5);
setMode(ENABLE_CMD, 5);
setMode(IMU_QUAT,4);
imu_status = quat;
// Dynamic reconfigure
dyn_param_server_callback_function_ =
boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubEvo::~TerarangerHubEvo() {}
void TerarangerHubEvo::setMode(const char *c, int length)
{
serial_port_.write((uint8_t*)c, length);
serial_port_.flushOutput();
}
void TerarangerHubEvo::dynParamCallback(
const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level)
{
ROS_INFO("Dynamic reconfigure call");
// Set the mode dynamically
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary)
{
setMode(BINARY_MODE, 4);
}
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text)
{
setMode(TEXT_MODE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Long_range)
{
setMode(LONG_RANGE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Short_range)
{
setMode(SHORT_RANGE, 4);
}
// Set the rate dynamically
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP)
{
setMode(RATE_ASAP, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700)
{
setMode(RATE_700, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600)
{
setMode(RATE_600, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500)
{
setMode(RATE_500, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250)
{
setMode(RATE_250, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100)
{
setMode(RATE_100, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50)
{
setMode(RATE_50, 5);
}
// Set the IMU mode dynamically
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_OFF)
{
setMode(IMU_OFF,4);
imu_status = off;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUAT)
{
setMode(IMU_QUAT,4);
imu_status = quat;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_EULER)
{
setMode(IMU_EULER,4);
imu_status = euler;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUATLIN)
{
setMode(IMU_QUATLIN,4);
imu_status = quatlin;
}
//Set the sequence mode dynamically
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Crosstalk)
{
setMode(CROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Non_crosstalk)
{
setMode(NONCROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Tower_mode)
{
setMode(TOWER_MODE,4);
}
//Set VCP state dynamically
if(config.Enable_VCP)
{
setMode(ENABLE_CMD, 5);
}
else
{
setMode(DISABLE_CMD, 5);
}
}
void TerarangerHubEvo::processRangeFrame(uint8_t* input_buffer, int seq_ctr)
{
//Processing full range frame
uint8_t crc = HelperLib::crc8(input_buffer, 19);
if (crc == input_buffer[RANGE_CRC_POS])
{
for (size_t i=0; i < range_array_msg.ranges.size(); i++)
{
range_array_msg.ranges.at(i).header.stamp = ros::Time::now();
range_array_msg.ranges.at(i).header.seq = seq_ctr++;
// Convert bytes to range
// Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8
char c1 = input_buffer[2 * (i + 1)];
char c2 = input_buffer[2 * (i + 1) + 1];
ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF));
int16_t current_range = (c1 & 0x0FF) << 8;
current_range |= (c2 & 0x0FF);
float float_range = (float)current_range;
ROS_DEBUG("Value int : %d | float : %f", current_range, float_range);
if (current_range <= 1 || current_range == 255)
{
float_range = -1.0;
}
else
{
float_range = float_range * 0.001;
}
range_array_msg.ranges.at(i).range = float_range;
}
range_array_msg.header.seq = (int) seq_ctr / 8;
range_array_msg.header.stamp = ros::Time::now();
range_publisher_.publish(range_array_msg);
}
else
{
ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str());
}
}
void TerarangerHubEvo::processImuFrame(uint8_t* input_buffer, int seq_ctr)
{
if (imu_status == imu_mode::off)
{
return;
}
else if (imu_status == imu_mode::quat)
{
}
else if (imu_status == imu_mode::euler)
{
}
else if (imu_status == imu_mode::quatlin)
{
}
imu_msg.header.seq = seq_ctr;
imu_msg.header.stamp = ros::Time::now();
imu_publisher_.publish(imu_msg);
}
void TerarangerHubEvo::serialDataCallback(uint8_t single_character)
{
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int seq_ctr = 0;
ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character);
if (buffer_ctr == 0)
{
if (single_character == 'T' || single_character == 'I')
{
// Waiting for T or an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
else if (buffer_ctr == 1)
{
if (single_character == 'H' || single_character == 'M')
{
// Waiting for H after a T or an M after an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
if (buffer_ctr > 1)
{
if (input_buffer[0] == 'T')// Parsing ranges
{
// Gathering after-header range data
if (buffer_ctr < RANGES_FRAME_LENGTH)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == RANGES_FRAME_LENGTH)
{
processRangeFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > RANGES_FRAME_LENGTH)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
else if (input_buffer[0] == 'I')// Parsing Imu
{
// ROS_INFO("%d", imu_status);
// Gathering after-header imu data
if (buffer_ctr < IMU_EULER_FRAME_LENGHT)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == IMU_EULER_FRAME_LENGHT)
{
processImuFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > IMU_EULER_FRAME_LENGHT)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
// resetting buffer and ctr
buffer_ctr = 0;
bzero(&input_buffer, BUFFER_SIZE);
// Appending current char to hook next frame
input_buffer[buffer_ctr++] = single_character;
}
}
void TerarangerHubEvo::spin()
{
static uint8_t buffer[1];
while(ros::ok())
{
serial_port_.read(buffer, 1);
serialDataCallback(buffer[0]);
ros::spinOnce();
}
setMode(DISABLE_CMD, 5);
}
}// end of namespace
int main(int argc, char **argv) {
ros::init(argc, argv, "teraranger_hub_evo");
teraranger_array::TerarangerHubEvo node;
node.spin();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <validation.h>
#include <services/asset.h>
#include <services/assetconsensus.h>
#include <consensus/validation.h>
std::string stringFromSyscoinTx(const int &nVersion) {
switch (nVersion) {
case SYSCOIN_TX_VERSION_ASSET_ACTIVATE:
return "assetactivate";
case SYSCOIN_TX_VERSION_ASSET_UPDATE:
return "assetupdate";
case SYSCOIN_TX_VERSION_ASSET_SEND:
return "assetsend";
case SYSCOIN_TX_VERSION_ALLOCATION_SEND:
return "assetallocationsend";
case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM:
return "assetallocationburntoethereum";
case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN:
return "assetallocationburntosyscoin";
case SYSCOIN_TX_VERSION_SYSCOIN_BURN_TO_ALLOCATION:
return "syscoinburntoassetallocation";
case SYSCOIN_TX_VERSION_ALLOCATION_MINT:
return "assetallocationmint";
default:
return "<unknown assetallocation op>";
}
}
std::vector<unsigned char> vchFromString(const std::string &str) {
unsigned char *strbeg = (unsigned char*)str.c_str();
return std::vector<unsigned char>(strbeg, strbeg + str.size());
}
std::string stringFromVch(const std::vector<unsigned char> &vch) {
std::string res;
std::vector<unsigned char>::const_iterator vi = vch.begin();
while (vi != vch.end()) {
res += (char)(*vi);
vi++;
}
return res;
}
bool CAsset::UnserializeFromData(const std::vector<unsigned char> &vchData) {
try {
CDataStream dsAsset(vchData, SER_NETWORK, PROTOCOL_VERSION);
Unserialize(dsAsset);
} catch (std::exception &e) {
SetNull();
return false;
}
return true;
}
bool CAsset::UnserializeFromTx(const CTransaction &tx) {
std::vector<unsigned char> vchData;
int nOut;
if (!GetSyscoinData(tx, vchData, nOut))
{
SetNull();
return false;
}
if(!UnserializeFromData(vchData))
{
SetNull();
return false;
}
return true;
}
int32_t GenerateSyscoinGuid(const COutPoint& outPoint) {
const arith_uint256 &txidArith = UintToArith256(outPoint.hash);
int32_t low32 = (int32_t)txidArith.GetLow64();
low32 += outPoint.n;
if(low32 < 0){
low32 *= -1;
}
if(low32 <= SYSCOIN_TX_VERSION_ALLOCATION_SEND*10){
low32 = SYSCOIN_TX_VERSION_ALLOCATION_SEND*10;
}
return low32;
}
void CAsset::SerializeData( std::vector<unsigned char> &vchData) {
CDataStream dsAsset(SER_NETWORK, PROTOCOL_VERSION);
Serialize(dsAsset);
vchData = std::vector<unsigned char>(dsAsset.begin(), dsAsset.end());
}
bool GetAsset(const int32_t &nAsset,
CAsset& txPos) {
if (passetdb == nullptr || !passetdb->ReadAsset(nAsset, txPos))
return false;
return true;
}
bool ReserializeAssetCommitment(CMutableTransaction& mtx) {
// load tx.voutAssets from tx.vout.assetInfo info
// when change is added this function should be called and preceding this the vout.assetInfo
// should all be in sync with the asset commitment in OP_RETURN. This will resync that commitment
// because when change is added the vout.assetInfo is filled and we should capture that in LoadAssetsFromVout as it
// re-orders tx->voutAssets if change address was somewhere before the last asset output
mtx.LoadAssetsFromVout();
// store tx.voutAssets into OP_RETURN data overwriting previous commitment
const CTransactionRef& tx = MakeTransactionRef(mtx);
std::vector<unsigned char> data;
if(IsSyscoinMintTx(tx->nVersion)) {
CMintSyscoin mintSyscoin(*tx);
mintSyscoin.assetAllocation.voutAssets = tx->voutAssets;
mintSyscoin.SerializeData(data);
} else if(tx->nVersion == SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN) {
CBurnSyscoin burnSyscoin(*tx);
burnSyscoin.assetAllocation.voutAssets = tx->voutAssets;
burnSyscoin.SerializeData(data);
} else if(IsAssetTx(tx->nVersion)) {
CAsset asset(*tx);
asset.assetAllocation.voutAssets = tx->voutAssets;
asset.SerializeData(data);
} else if(IsAssetAllocationTx(tx->nVersion)) {
CAssetAllocation allocation(*tx);
allocation.voutAssets = tx->voutAssets;
allocation.SerializeData(data);
}
// find previous commitment (OP_RETURN) and replace script
CScript scriptData;
scriptData << OP_RETURN << data;
bool bFoundData = false;
for(auto& vout: mtx.vout) {
if(vout.scriptPubKey.IsUnspendable()) {
vout.scriptPubKey = scriptData;
bFoundData = true;
break;
}
}
if(!bFoundData) {
return false;
}
return true;
}
<commit_msg>inc dbwrapper<commit_after>// Copyright (c) 2013-2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <validation.h>
#include <services/asset.h>
#include <services/assetconsensus.h>
#include <consensus/validation.h>
#include <consensus/dbwrapper.h>
std::string stringFromSyscoinTx(const int &nVersion) {
switch (nVersion) {
case SYSCOIN_TX_VERSION_ASSET_ACTIVATE:
return "assetactivate";
case SYSCOIN_TX_VERSION_ASSET_UPDATE:
return "assetupdate";
case SYSCOIN_TX_VERSION_ASSET_SEND:
return "assetsend";
case SYSCOIN_TX_VERSION_ALLOCATION_SEND:
return "assetallocationsend";
case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM:
return "assetallocationburntoethereum";
case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN:
return "assetallocationburntosyscoin";
case SYSCOIN_TX_VERSION_SYSCOIN_BURN_TO_ALLOCATION:
return "syscoinburntoassetallocation";
case SYSCOIN_TX_VERSION_ALLOCATION_MINT:
return "assetallocationmint";
default:
return "<unknown assetallocation op>";
}
}
std::vector<unsigned char> vchFromString(const std::string &str) {
unsigned char *strbeg = (unsigned char*)str.c_str();
return std::vector<unsigned char>(strbeg, strbeg + str.size());
}
std::string stringFromVch(const std::vector<unsigned char> &vch) {
std::string res;
std::vector<unsigned char>::const_iterator vi = vch.begin();
while (vi != vch.end()) {
res += (char)(*vi);
vi++;
}
return res;
}
bool CAsset::UnserializeFromData(const std::vector<unsigned char> &vchData) {
try {
CDataStream dsAsset(vchData, SER_NETWORK, PROTOCOL_VERSION);
Unserialize(dsAsset);
} catch (std::exception &e) {
SetNull();
return false;
}
return true;
}
bool CAsset::UnserializeFromTx(const CTransaction &tx) {
std::vector<unsigned char> vchData;
int nOut;
if (!GetSyscoinData(tx, vchData, nOut))
{
SetNull();
return false;
}
if(!UnserializeFromData(vchData))
{
SetNull();
return false;
}
return true;
}
int32_t GenerateSyscoinGuid(const COutPoint& outPoint) {
const arith_uint256 &txidArith = UintToArith256(outPoint.hash);
int32_t low32 = (int32_t)txidArith.GetLow64();
low32 += outPoint.n;
if(low32 < 0){
low32 *= -1;
}
if(low32 <= SYSCOIN_TX_VERSION_ALLOCATION_SEND*10){
low32 = SYSCOIN_TX_VERSION_ALLOCATION_SEND*10;
}
return low32;
}
void CAsset::SerializeData( std::vector<unsigned char> &vchData) {
CDataStream dsAsset(SER_NETWORK, PROTOCOL_VERSION);
Serialize(dsAsset);
vchData = std::vector<unsigned char>(dsAsset.begin(), dsAsset.end());
}
bool GetAsset(const int32_t &nAsset,
CAsset& txPos) {
if (passetdb == nullptr || !passetdb->ReadAsset(nAsset, txPos))
return false;
return true;
}
bool ReserializeAssetCommitment(CMutableTransaction& mtx) {
// load tx.voutAssets from tx.vout.assetInfo info
// when change is added this function should be called and preceding this the vout.assetInfo
// should all be in sync with the asset commitment in OP_RETURN. This will resync that commitment
// because when change is added the vout.assetInfo is filled and we should capture that in LoadAssetsFromVout as it
// re-orders tx->voutAssets if change address was somewhere before the last asset output
mtx.LoadAssetsFromVout();
// store tx.voutAssets into OP_RETURN data overwriting previous commitment
const CTransactionRef& tx = MakeTransactionRef(mtx);
std::vector<unsigned char> data;
if(IsSyscoinMintTx(tx->nVersion)) {
CMintSyscoin mintSyscoin(*tx);
mintSyscoin.assetAllocation.voutAssets = tx->voutAssets;
mintSyscoin.SerializeData(data);
} else if(tx->nVersion == SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN) {
CBurnSyscoin burnSyscoin(*tx);
burnSyscoin.assetAllocation.voutAssets = tx->voutAssets;
burnSyscoin.SerializeData(data);
} else if(IsAssetTx(tx->nVersion)) {
CAsset asset(*tx);
asset.assetAllocation.voutAssets = tx->voutAssets;
asset.SerializeData(data);
} else if(IsAssetAllocationTx(tx->nVersion)) {
CAssetAllocation allocation(*tx);
allocation.voutAssets = tx->voutAssets;
allocation.SerializeData(data);
}
// find previous commitment (OP_RETURN) and replace script
CScript scriptData;
scriptData << OP_RETURN << data;
bool bFoundData = false;
for(auto& vout: mtx.vout) {
if(vout.scriptPubKey.IsUnspendable()) {
vout.scriptPubKey = scriptData;
bFoundData = true;
break;
}
}
if(!bFoundData) {
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include <ros/console.h>
#include <string>
#include <teraranger_hub/RangeArray.h>
#include <teraranger_hub/teraranger_evo.h>
#include <teraranger_hub/helper_lib.h>
namespace teraranger_hub
{
TerarangerHubEvo::TerarangerHubEvo()
{
// Get parameters and namespace
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_,
std::string("/dev/ttyACM0"));
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Publishers
range_publisher_ = nh_.advertise<teraranger_hub::RangeArray>("teraranger_evo", 8);
// Serial Port init
serial_port_ = new SerialPort();
if (!serial_port_->connect(portname_)) {
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
else {
serial_data_callback_function_ =
boost::bind(&TerarangerHubEvo::serialDataCallback, this, _1);
serial_port_->setSerialCallbackFunction(&serial_data_callback_function_);
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:",
ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(),
portname_.c_str());
//Initialize local parameters and measurement array
field_of_view = 0.0593;
max_range = 14.0;
min_range = 0.2;
number_of_sensor = 8;
frame_id = "base_range_";
// Initialize rangeArray
for (size_t i=0; i < number_of_sensor; i++)
{
sensor_msgs::Range range;
range.field_of_view = field_of_view;
range.max_range = max_range;
range.min_range = min_range;
range.radiation_type = sensor_msgs::Range::INFRARED;
range.range = 0.0;
// set the right range frame depending of the namespace
if (ns_ == ""){
range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i);
}
else{
range.header.frame_id = ns_.erase(0,1) + '_'+ frame_id + boost::lexical_cast<std::string>(i);
}
measure.ranges.push_back(range);
}
// set the right RangeArray frame depending of the namespace
if (ns_ == ""){
measure.header.frame_id = "base_hub";
}
else{
measure.header.frame_id = "base_" + ns_.erase(0,1);// Remove first slash
}
// This line is needed to start measurements on the hub
setMode(ENABLE_CMD, 5);
setMode(BINARY_MODE, 4);
setMode(TOWER_MODE, 4);
setMode(RATE_ASAP, 5);
// Dynamic reconfigure
dyn_param_server_callback_function_ =
boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubEvo::~TerarangerHubEvo() {}
void TerarangerHubEvo::setMode(const char *c, int length) {
serial_port_->sendChar(c, length);
}
void TerarangerHubEvo::dynParamCallback(
const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level) {
// Set the mode dynamically
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary) {
setMode(BINARY_MODE, 4);
}
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text) {
setMode(TEXT_MODE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Long_range) {
setMode(LONG_RANGE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Short_range) {
setMode(SHORT_RANGE, 4);
}
// Set the rate dynamically
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP){
setMode(RATE_ASAP, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700){
setMode(RATE_700, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600){
setMode(RATE_600, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500){
setMode(RATE_500, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250){
setMode(RATE_250, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100){
setMode(RATE_100, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50){
setMode(RATE_50, 5);
}
}
void TerarangerHubEvo::serialDataCallback(uint8_t single_character) {
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int seq_ctr = 0;
ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character);
if (single_character == 'T' && buffer_ctr == 0) {
// Waiting for T
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (single_character == 'H' && buffer_ctr == 1) {
// Waiting for H after a T
input_buffer[buffer_ctr++] = single_character;
return;
}
// Gathering after-header range data
if (buffer_ctr > 1 && buffer_ctr < RANGES_FRAME_LENGTH) {
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == RANGES_FRAME_LENGTH) {
//Processing full range frame
uint8_t crc = HelperLib::crc8(input_buffer, 19);
if (crc == input_buffer[RANGE_CRC_POS]) {
//ROS_DEBUG("Frame of size %d : %s ", buffer_ctr, input_buffer);
for (size_t i=0; i < measure.ranges.size(); i++) {
measure.ranges.at(i).header.stamp = ros::Time::now();
measure.ranges.at(i).header.seq = seq_ctr++;
// Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8
char c1 = input_buffer[2 * (i + 1)];
char c2 = input_buffer[2 * (i + 1) + 1];
ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF));
int16_t current_range = (c1 & 0x0FF) << 8;
current_range |= (c2 & 0x0FF);
float float_range = (float)current_range;
ROS_DEBUG("Value int : %d | float : %f", current_range, float_range);
if (current_range <= 1 || current_range == 255) {
float_range = -1.0;
} else {
float_range = float_range * 0.001;
}
measure.ranges.at(i).range = float_range;
}
measure.header.seq = (int) seq_ctr / 8;
measure.header.stamp = ros::Time::now();
range_publisher_.publish(measure);
} else {
ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str());
}
} else if (buffer_ctr > RANGES_FRAME_LENGTH){
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
// resetting buffer and ctr
buffer_ctr = 0;
bzero(&input_buffer, BUFFER_SIZE);
// Appending current char to hook next frame
input_buffer[buffer_ctr++] = single_character;
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "teraranger_hub_evo");
teraranger_hub::TerarangerHubEvo node;
ros::spin();
return 0;
}
<commit_msg>Correct field of view constant<commit_after>#include <ros/console.h>
#include <string>
#include <teraranger_hub/RangeArray.h>
#include <teraranger_hub/teraranger_evo.h>
#include <teraranger_hub/helper_lib.h>
namespace teraranger_hub
{
TerarangerHubEvo::TerarangerHubEvo()
{
// Get parameters and namespace
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_,
std::string("/dev/ttyACM0"));
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Publishers
range_publisher_ = nh_.advertise<teraranger_hub::RangeArray>("teraranger_evo", 8);
// Serial Port init
serial_port_ = new SerialPort();
if (!serial_port_->connect(portname_)) {
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
else {
serial_data_callback_function_ =
boost::bind(&TerarangerHubEvo::serialDataCallback, this, _1);
serial_port_->setSerialCallbackFunction(&serial_data_callback_function_);
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:",
ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(),
portname_.c_str());
//Initialize local parameters and measurement array
field_of_view = 0.03491;
max_range = 14.0;
min_range = 0.2;
number_of_sensor = 8;
frame_id = "base_range_";
// Initialize rangeArray
for (size_t i=0; i < number_of_sensor; i++)
{
sensor_msgs::Range range;
range.field_of_view = field_of_view;
range.max_range = max_range;
range.min_range = min_range;
range.radiation_type = sensor_msgs::Range::INFRARED;
range.range = 0.0;
// set the right range frame depending of the namespace
if (ns_ == ""){
range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i);
}
else{
range.header.frame_id = ns_.erase(0,1) + '_'+ frame_id + boost::lexical_cast<std::string>(i);
}
measure.ranges.push_back(range);
}
// set the right RangeArray frame depending of the namespace
if (ns_ == ""){
measure.header.frame_id = "base_hub";
}
else{
measure.header.frame_id = "base_" + ns_.erase(0,1);// Remove first slash
}
// This line is needed to start measurements on the hub
setMode(ENABLE_CMD, 5);
setMode(BINARY_MODE, 4);
setMode(TOWER_MODE, 4);
setMode(RATE_ASAP, 5);
// Dynamic reconfigure
dyn_param_server_callback_function_ =
boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubEvo::~TerarangerHubEvo() {}
void TerarangerHubEvo::setMode(const char *c, int length) {
serial_port_->sendChar(c, length);
}
void TerarangerHubEvo::dynParamCallback(
const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level) {
// Set the mode dynamically
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary) {
setMode(BINARY_MODE, 4);
}
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text) {
setMode(TEXT_MODE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Long_range) {
setMode(LONG_RANGE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Short_range) {
setMode(SHORT_RANGE, 4);
}
// Set the rate dynamically
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP){
setMode(RATE_ASAP, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700){
setMode(RATE_700, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600){
setMode(RATE_600, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500){
setMode(RATE_500, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250){
setMode(RATE_250, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100){
setMode(RATE_100, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50){
setMode(RATE_50, 5);
}
}
void TerarangerHubEvo::serialDataCallback(uint8_t single_character) {
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int seq_ctr = 0;
ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character);
if (single_character == 'T' && buffer_ctr == 0) {
// Waiting for T
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (single_character == 'H' && buffer_ctr == 1) {
// Waiting for H after a T
input_buffer[buffer_ctr++] = single_character;
return;
}
// Gathering after-header range data
if (buffer_ctr > 1 && buffer_ctr < RANGES_FRAME_LENGTH) {
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == RANGES_FRAME_LENGTH) {
//Processing full range frame
uint8_t crc = HelperLib::crc8(input_buffer, 19);
if (crc == input_buffer[RANGE_CRC_POS]) {
//ROS_DEBUG("Frame of size %d : %s ", buffer_ctr, input_buffer);
for (size_t i=0; i < measure.ranges.size(); i++) {
measure.ranges.at(i).header.stamp = ros::Time::now();
measure.ranges.at(i).header.seq = seq_ctr++;
// Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8
char c1 = input_buffer[2 * (i + 1)];
char c2 = input_buffer[2 * (i + 1) + 1];
ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF));
int16_t current_range = (c1 & 0x0FF) << 8;
current_range |= (c2 & 0x0FF);
float float_range = (float)current_range;
ROS_DEBUG("Value int : %d | float : %f", current_range, float_range);
if (current_range <= 1 || current_range == 255) {
float_range = -1.0;
} else {
float_range = float_range * 0.001;
}
measure.ranges.at(i).range = float_range;
}
measure.header.seq = (int) seq_ctr / 8;
measure.header.stamp = ros::Time::now();
range_publisher_.publish(measure);
} else {
ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str());
}
} else if (buffer_ctr > RANGES_FRAME_LENGTH){
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
// resetting buffer and ctr
buffer_ctr = 0;
bzero(&input_buffer, BUFFER_SIZE);
// Appending current char to hook next frame
input_buffer[buffer_ctr++] = single_character;
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "teraranger_hub_evo");
teraranger_hub::TerarangerHubEvo node;
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef THIS_HASH_MAP
#define THIS_HASH_MAP parallel_flat_hash_map
#define THIS_TEST_NAME ParallelFlatHashMap
#endif
#include "flat_hash_map_test.cc"
namespace phmap {
namespace priv {
namespace {
TEST(THIS_TEST_NAME, ThreadSafeContains) {
// We can't test mutable keys, or non-copyable keys with ThisMap.
// Test that the nodes have the proper API.
using Map = ThisMap<int, int>;
Map m = { {1, 7}, {2, 9} };
const Map& const_m(m);
auto val = 0;
auto get_value = [&val](const int& v) { val = v; };
EXPECT_TRUE(const_m.if_contains(2, get_value));
EXPECT_EQ(val, 9);
EXPECT_FALSE(m.if_contains(3, get_value));
auto set_value = [](int& v) { v = 11; };
EXPECT_TRUE(m.modify_if(2, set_value));
EXPECT_EQ(m[2], 11);
EXPECT_FALSE(m.modify_if(3, set_value)); // because m[3] does not exist
// overwrite an existing value
m.try_emplace_l(2, [](int& v) { v = 5; });
EXPECT_EQ(m[2], 5);
// insert a value that is not already present. Will be default initialised to 0 and lambda not called
m.try_emplace_l(3,
[](int& v) { v = 6; }, // called only when key was already present
1); // argument to construct new value is key not present
EXPECT_EQ(m[3], 1);
// insert a value that is not already present, provide argument to value-construct it
m.try_emplace_l(4,
[](int& ) {}, // called only when key was already present
999); // argument to construct new value is key not present
EXPECT_EQ(m[4], 999);
// insert a value that is not already present.
// right now m[5] does not exist
m.lazy_emplace_l(5,
[](int& v) { v = 6; }, // called only when key was already present
[](const Map::constructor& ctor) { ctor(5, 13); }); // construct value_type in place when key not present
EXPECT_EQ(m[5], 13);
// change a value that is present. Currently m[5] == 13
m.lazy_emplace_l(5,
[](int& v) { v = 6; }, // called only when key was already present
[](const Map::constructor& ctor) { ctor(5, 13); }); // construct value_type in place when key not present
EXPECT_EQ(m[5], 6);
// test erase_if
// -------------
EXPECT_EQ(m.erase_if(9, [](int& v) { assert(0); return v==12; }), false); // m[9] not present - lambda not called
EXPECT_EQ(m.erase_if(5, [](int& v) { return v==12; }), false); // m[5] == 6, so erase not performed
EXPECT_EQ(m[5], 6);
EXPECT_EQ(m.erase_if(5, [](int& v) { return v==6; }), true); // lambda returns true, so m[5] erased
EXPECT_EQ(m[5], 0);
}
} // namespace
} // namespace priv
} // namespace phmap
<commit_msg>cleanup tests for extension APIs<commit_after>#ifndef THIS_HASH_MAP
#define THIS_HASH_MAP parallel_flat_hash_map
#define THIS_TEST_NAME ParallelFlatHashMap
#endif
#include "flat_hash_map_test.cc"
namespace phmap {
namespace priv {
namespace {
TEST(THIS_TEST_NAME, ThreadSafeContains) {
// We can't test mutable keys, or non-copyable keys with ThisMap.
// Test that the nodes have the proper API.
using Map = ThisMap<int, int>;
{
// ----------------
// test if_contains
// ----------------
Map m = { {1, 7}, {2, 9} };
const Map& const_m(m);
auto val = 0;
auto get_value = [&val](const int& v) { val = v; };
EXPECT_TRUE(const_m.if_contains(2, get_value));
EXPECT_EQ(val, 9);
EXPECT_FALSE(m.if_contains(3, get_value));
}
{
// --------------
// test modify_if
// --------------
Map m = { {1, 7}, {2, 9} };
auto set_value = [](int& v) { v = 11; };
EXPECT_TRUE(m.modify_if(2, set_value));
EXPECT_EQ(m[2], 11);
EXPECT_FALSE(m.modify_if(3, set_value)); // because m[3] does not exist
}
{
// ------------------
// test try_emplace_l
// ------------------
Map m = { {1, 7}, {2, 9} };
// overwrite an existing value
m.try_emplace_l(2, [](int& v) { v = 5; });
EXPECT_EQ(m[2], 5);
// insert a value that is not already present. Will be default initialised to 0 and lambda not called
m.try_emplace_l(3,
[](int& v) { v = 6; }, // called only when key was already present
1); // argument to construct new value is key not present
EXPECT_EQ(m[3], 1);
// insert a value that is not already present, provide argument to value-construct it
m.try_emplace_l(4,
[](int& ) {}, // called only when key was already present
999); // argument to construct new value is key not present
EXPECT_EQ(m[4], 999);
}
{
// --------------------
// test lazy__emplace_l
// --------------------
Map m = { {1, 7}, {2, 9} };
// insert a value that is not already present.
// right now m[5] does not exist
m.lazy_emplace_l(5,
[](int& v) { v = 6; }, // called only when key was already present
[](const Map::constructor& ctor) { ctor(5, 13); }); // construct value_type in place when key not present
EXPECT_EQ(m[5], 13);
// change a value that is present. Currently m[5] == 13
m.lazy_emplace_l(5,
[](int& v) { v = 6; }, // called only when key was already present
[](const Map::constructor& ctor) { ctor(5, 13); }); // construct value_type in place when key not present
EXPECT_EQ(m[5], 6);
}
{
// -------------
// test erase_if
// -------------
Map m = { {1, 7}, {2, 9}, {5, 6} };
EXPECT_EQ(m.erase_if(9, [](int& v) { assert(0); return v==12; }), false); // m[9] not present - lambda not called
EXPECT_EQ(m.erase_if(5, [](int& v) { return v==12; }), false); // m[5] == 6, so erase not performed
EXPECT_EQ(m[5], 6);
EXPECT_EQ(m.erase_if(5, [](int& v) { return v==6; }), true); // lambda returns true, so m[5] erased
EXPECT_EQ(m[5], 0);
}
}
} // namespace
} // namespace priv
} // namespace phmap
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Miguel Freitas
// TODO: write description for the soft checkpoint
// More info:
// https://groups.google.com/forum/#!topic/twister-dev/tH3HlVQ_wmo
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/assign.hpp>
#include <boost/foreach.hpp>
#include "softcheckpoint.h"
#include "main.h"
#include "checkpoints.h"
#include "uint256.h"
#include "script.h"
#include "init.h"
#include "twister.h"
//#define dbgprintf OutputDebugStringF
#define dbgprintf(...) // no debug printf
namespace SoftCheckpoints
{
bool fEnabled = true;
CCriticalSection cs_softCP;
typedef std::pair<int, uint256> Checkpoint; // height, hash
typedef std::map<std::string, std::string> CPSigMap; // user, sign
typedef std::pair<std::string, std::string> CPSigPair; // user, sign
static Checkpoint lastSoftCP;
static CPSigMap lastSoftCPSigs;
static std::map<Checkpoint, CPSigMap> nextCandidates;
static std::map<Checkpoint, CPSigMap> uncheckedCandidates;
static std::set<std::string> uniqueUsersList =
boost::assign::list_of
("mf1")("mf1a")("mf2")("mf2a")("mf3")
("wn41");
static std::set<std::string> upcomingUsersList =
boost::assign::list_of
("omgasm");
void SetSoftCPBestChain() {
// requires cs_main and cs_softCP locked (in this order)
if( !fEnabled )
return;
if( lastSoftCP.first && mapBlockIndex.count(lastSoftCP.second) &&
!mapBlockIndex[lastSoftCP.second]->IsInMainChain() ) {
dbgprintf("SoftCheckpoints::SetSoftCPBestChain: lastSoftCP %d not in main chain\n", lastSoftCP.first);
// ? use !mapOrphanBlocks.count() ?
CBlockIndex *pindex = mapBlockIndex[lastSoftCP.second];
while( pindex && !pindex->IsInMainChain() ) {
pindex = pindex->pprev;
}
if( !pindex ) {
dbgprintf("SoftCheckpoints::SetSoftCPBestChain: lastSoftCP %d currently orphaned? strange.\n", lastSoftCP.first);
return;
}
dbgprintf("SoftCheckpoints::SetSoftCPBestChain: trying SetBestChain with lastSoftCP %d\n", lastSoftCP.first);
CValidationState state;
if (!SetBestChain(state, mapBlockIndex[lastSoftCP.second])) {
dbgprintf("SoftCheckpoints::lastSoftCPUpdated: SetBestChain failed\n");
}
}
}
void LastSoftCPUpdated() {
//LOCK(cs_main); // FIXME: not needed if called from ProcessMessage. check. wrong mutex order is bad.
SetSoftCPBestChain();
}
std::string CPtoString(Checkpoint &cp) {
CScript cs = CScript() << cp.first << cp.second;
return std::string((const char *)cs.data(), cs.size());
}
void NewBlockAccepted() {
LOCK(cs_softCP);
SetSoftCPBestChain();
if( (nBestHeight % SOFT_CHECKPOINT_PERIOD) == 0 &&
nBestHeight > Checkpoints::GetHighestCheckpoint() &&
nBestHeight >= lastSoftCP.first + SOFT_CHECKPOINT_PERIOD &&
!fImporting && !fReindex) {
LOCK(pwalletMain->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(CKeyID, CKeyMetadata)& item, pwalletMain->mapKeyMetadata)
{
const std::string &username = item.second.username;
if(uniqueUsersList.count(username) || upcomingUsersList.count(username)) {
int height = nBestHeight - SOFT_CHECKPOINT_PERIOD;
dbgprintf("SoftCheckpoints::NewBlockAccepted: user '%s' will vote for %d\n",
username.c_str(), height);
CBlockIndex* pblockindex = FindBlockByHeight(height);
assert( pblockindex );
Checkpoint cpPair = std::make_pair(height, *pblockindex->phashBlock);
std::string dataToSign = CPtoString(cpPair);
std::string sign = createSignature(dataToSign, username);
if( sign.size() ) {
if( CastVoteSoftCheckpoint(height, *pblockindex->phashBlock, username, sign) ) {
dbgprintf("SoftCheckpoints::NewBlockAccepted: relaying our own vote\n");
CSoftCheckpoint cp;
cp.nHeight = height;
cp.blockHash = *pblockindex->phashBlock;
cp.vchUsername = std::vector<char>(username.begin(), username.end());
cp.vchSign = std::vector<char>(sign.begin(), sign.end());
SoftCheckpoints::RelayCP(cp, NULL);
} else {
dbgprintf("SoftCheckpoints::NewBlockAccepted: CastVoteSoftCheckpoint failed for our own vote!\n");
}
} else {
dbgprintf("SoftCheckpoints::NewBlockAccepted: createSignature failed for user '%s'\n",
username.c_str());
}
break;
}
}
}
if( uncheckedCandidates.size() && nBestHeight > Checkpoints::GetHighestCheckpoint() ) {
// pending unchecked
dbgprintf("SoftCheckpoints::NewBlockAccepted process %zd pending unchecked (not implemented)\n",
uncheckedCandidates.size());
uncheckedCandidates.clear();
}
}
bool CastVerifiedVote(Checkpoint &cp, const std::string &username, const std::string &sign) {
if( cp.first == lastSoftCP.first ) {
if( lastSoftCPSigs.count(username) ) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: '%s' already voted for lastSoftCP %d\n", username.c_str(), cp.first);
return false;
}
if( cp != lastSoftCP ) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: '%s' voted for a different hash than lastSoftCP %d\n", username.c_str(), cp.first);
return false;
}
dbgprintf("SoftCheckpoints::CastVerifiedVote: new vote for lastSoftCP %d by '%s'\n", cp.first, username.c_str());
lastSoftCPSigs[username] = sign;
return true;
}
if( nextCandidates.count(cp) && nextCandidates[cp].count(username) ) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: '%s' already voted for candidate %d\n", username.c_str(), cp.first);
return false;
}
nextCandidates[cp][username] = sign;
if( nextCandidates[cp].size() > uniqueUsersList.size() / 2) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: new soft checkpoint %d wins!\n", cp.first);
lastSoftCP = cp;
lastSoftCPSigs = nextCandidates[cp];
nextCandidates.clear();
LastSoftCPUpdated();
}
return true;
}
// returns true if vote is to be restransmitted
bool CastVoteSoftCheckpoint(int height, const uint256 &hash, const std::string &username, const std::string &sign) {
LOCK(cs_softCP);
if( (height % SOFT_CHECKPOINT_PERIOD) != 0 ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: height %d not multiple of SOFT_CHECKPOINT_PERIOD\n", height);
return false;
}
int hardCheckPointHeight = Checkpoints::GetHighestCheckpoint();
if( height < hardCheckPointHeight ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: height %d < hard checkpoint %d\n", height, hardCheckPointHeight);
return false;
}
if( height < lastSoftCP.first ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: height %d < soft checkpoint %d\n", height, lastSoftCP.first);
return false;
}
if( !uniqueUsersList.count(username) && !upcomingUsersList.count(username) ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: username '%s' not accepted\n", username.c_str());
return false;
}
Checkpoint cp = std::make_pair(height, hash);
if( nBestHeight < hardCheckPointHeight ) {
// still downloading blocks, we can't check signatures yet
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: vote for %d by '%s' added to unchecked\n", height, username.c_str());
uncheckedCandidates[cp][username] = sign;
return false;
}
if( !verifySignature( CPtoString(cp), username, sign) ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: invalid signature by '%s'\n", username.c_str());
return false;
}
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: signature by '%s' verified for %d, casting vote\n",
username.c_str(), height);
return CastVerifiedVote( cp, username, sign );
}
bool CheckBlock(int nHeight, const uint256& hash) {
LOCK(cs_softCP);
if (!fEnabled)
return true;
if (!lastSoftCP.first || nHeight != lastSoftCP.first)
return true;
dbgprintf("SoftCheckpoints::CheckBlock: height %d isOk=%d\n", nHeight, hash == lastSoftCP.second);
return hash == lastSoftCP.second;
}
void RelayCP(const CSoftCheckpoint& cp, CNode* pfrom) {
LOCK(cs_vNodes);
dbgprintf("SoftCheckpoints::RelayCP: relaying softCP height %d from %s\n",
cp.nHeight, !pfrom ? "localhost" : pfrom->addr.ToString().c_str());
BOOST_FOREACH(CNode* pnode, vNodes) {
if(pnode == pfrom)
continue;
if (pnode->nVersion >= SOFT_CHECKPOINT_VERSION) {
dbgprintf("SoftCheckpoints::RelayCP: pushMessage to %s\n", pnode->addr.ToString().c_str());
pnode->PushMessage("cp", cp);
}
}
if( pfrom && lastSoftCP.first == cp.nHeight ) {
if( !mapBlockIndex.count(lastSoftCP.second) ) {
dbgprintf("SoftCheckpoints::RelayCP: requesting block height %d from node\n", cp.nHeight);
PushGetBlocks(pfrom, pindexBest, cp.blockHash);
}
}
}
void RelayLastCPToNode(CNode* pnode) {
LOCK(cs_softCP);
if (!lastSoftCP.first)
return;
if (pnode->nVersion >= SOFT_CHECKPOINT_VERSION) {
dbgprintf("SoftCheckpoints::RelayToLastCP: relaying lastSoftCP height %d (size %zd) to %s\n",
lastSoftCP.first, lastSoftCPSigs.size(), pnode->addr.ToString().c_str());
BOOST_FOREACH(const CPSigMap::value_type& i, lastSoftCPSigs) {
CSoftCheckpoint cp;
cp.nHeight = lastSoftCP.first;
cp.blockHash = lastSoftCP.second;
cp.vchUsername = std::vector<char>(i.first.begin(), i.first.end());
cp.vchSign = std::vector<char>(i.second.begin(), i.second.end());
pnode->PushMessage("cp", cp);
}
}
}
bool GetLastCPVotes(int &height, uint256 &hash, std::set<std::string> &usernames) {
LOCK(cs_softCP);
if (!lastSoftCP.first)
return false;
height = lastSoftCP.first;
hash = lastSoftCP.second;
usernames.clear();
BOOST_FOREACH(const CPSigMap::value_type& i, lastSoftCPSigs) {
usernames.insert(i.first);
}
return true;
}
}
<commit_msg>more voters<commit_after>// Copyright (c) 2014 Miguel Freitas
// TODO: write description for the soft checkpoint
// More info:
// https://groups.google.com/forum/#!topic/twister-dev/tH3HlVQ_wmo
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/assign.hpp>
#include <boost/foreach.hpp>
#include "softcheckpoint.h"
#include "main.h"
#include "checkpoints.h"
#include "uint256.h"
#include "script.h"
#include "init.h"
#include "twister.h"
//#define dbgprintf OutputDebugStringF
#define dbgprintf(...) // no debug printf
namespace SoftCheckpoints
{
bool fEnabled = true;
CCriticalSection cs_softCP;
typedef std::pair<int, uint256> Checkpoint; // height, hash
typedef std::map<std::string, std::string> CPSigMap; // user, sign
typedef std::pair<std::string, std::string> CPSigPair; // user, sign
static Checkpoint lastSoftCP;
static CPSigMap lastSoftCPSigs;
static std::map<Checkpoint, CPSigMap> nextCandidates;
static std::map<Checkpoint, CPSigMap> uncheckedCandidates;
static std::set<std::string> uniqueUsersList =
boost::assign::list_of
("mf1")("mf1a")("mf2")("mf2a")("mf3")
("wn41");
static std::set<std::string> upcomingUsersList =
boost::assign::list_of
("omgasm")("rantizdani")("rantisluni");
void SetSoftCPBestChain() {
// requires cs_main and cs_softCP locked (in this order)
if( !fEnabled )
return;
if( lastSoftCP.first && mapBlockIndex.count(lastSoftCP.second) &&
!mapBlockIndex[lastSoftCP.second]->IsInMainChain() ) {
dbgprintf("SoftCheckpoints::SetSoftCPBestChain: lastSoftCP %d not in main chain\n", lastSoftCP.first);
// ? use !mapOrphanBlocks.count() ?
CBlockIndex *pindex = mapBlockIndex[lastSoftCP.second];
while( pindex && !pindex->IsInMainChain() ) {
pindex = pindex->pprev;
}
if( !pindex ) {
dbgprintf("SoftCheckpoints::SetSoftCPBestChain: lastSoftCP %d currently orphaned? strange.\n", lastSoftCP.first);
return;
}
dbgprintf("SoftCheckpoints::SetSoftCPBestChain: trying SetBestChain with lastSoftCP %d\n", lastSoftCP.first);
CValidationState state;
if (!SetBestChain(state, mapBlockIndex[lastSoftCP.second])) {
dbgprintf("SoftCheckpoints::lastSoftCPUpdated: SetBestChain failed\n");
}
}
}
void LastSoftCPUpdated() {
//LOCK(cs_main); // FIXME: not needed if called from ProcessMessage. check. wrong mutex order is bad.
SetSoftCPBestChain();
}
std::string CPtoString(Checkpoint &cp) {
CScript cs = CScript() << cp.first << cp.second;
return std::string((const char *)cs.data(), cs.size());
}
void NewBlockAccepted() {
LOCK(cs_softCP);
SetSoftCPBestChain();
if( (nBestHeight % SOFT_CHECKPOINT_PERIOD) == 0 &&
nBestHeight > Checkpoints::GetHighestCheckpoint() &&
nBestHeight >= lastSoftCP.first + SOFT_CHECKPOINT_PERIOD &&
!fImporting && !fReindex) {
LOCK(pwalletMain->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(CKeyID, CKeyMetadata)& item, pwalletMain->mapKeyMetadata)
{
const std::string &username = item.second.username;
if(uniqueUsersList.count(username) || upcomingUsersList.count(username)) {
int height = nBestHeight - SOFT_CHECKPOINT_PERIOD;
dbgprintf("SoftCheckpoints::NewBlockAccepted: user '%s' will vote for %d\n",
username.c_str(), height);
CBlockIndex* pblockindex = FindBlockByHeight(height);
assert( pblockindex );
Checkpoint cpPair = std::make_pair(height, *pblockindex->phashBlock);
std::string dataToSign = CPtoString(cpPair);
std::string sign = createSignature(dataToSign, username);
if( sign.size() ) {
if( CastVoteSoftCheckpoint(height, *pblockindex->phashBlock, username, sign) ) {
dbgprintf("SoftCheckpoints::NewBlockAccepted: relaying our own vote\n");
CSoftCheckpoint cp;
cp.nHeight = height;
cp.blockHash = *pblockindex->phashBlock;
cp.vchUsername = std::vector<char>(username.begin(), username.end());
cp.vchSign = std::vector<char>(sign.begin(), sign.end());
SoftCheckpoints::RelayCP(cp, NULL);
} else {
dbgprintf("SoftCheckpoints::NewBlockAccepted: CastVoteSoftCheckpoint failed for our own vote!\n");
}
} else {
dbgprintf("SoftCheckpoints::NewBlockAccepted: createSignature failed for user '%s'\n",
username.c_str());
}
break;
}
}
}
if( uncheckedCandidates.size() && nBestHeight > Checkpoints::GetHighestCheckpoint() ) {
// pending unchecked
dbgprintf("SoftCheckpoints::NewBlockAccepted process %zd pending unchecked (not implemented)\n",
uncheckedCandidates.size());
uncheckedCandidates.clear();
}
}
bool CastVerifiedVote(Checkpoint &cp, const std::string &username, const std::string &sign) {
if( cp.first == lastSoftCP.first ) {
if( lastSoftCPSigs.count(username) ) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: '%s' already voted for lastSoftCP %d\n", username.c_str(), cp.first);
return false;
}
if( cp != lastSoftCP ) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: '%s' voted for a different hash than lastSoftCP %d\n", username.c_str(), cp.first);
return false;
}
dbgprintf("SoftCheckpoints::CastVerifiedVote: new vote for lastSoftCP %d by '%s'\n", cp.first, username.c_str());
lastSoftCPSigs[username] = sign;
return true;
}
if( nextCandidates.count(cp) && nextCandidates[cp].count(username) ) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: '%s' already voted for candidate %d\n", username.c_str(), cp.first);
return false;
}
nextCandidates[cp][username] = sign;
if( nextCandidates[cp].size() > uniqueUsersList.size() / 2) {
dbgprintf("SoftCheckpoints::CastVerifiedVote: new soft checkpoint %d wins!\n", cp.first);
lastSoftCP = cp;
lastSoftCPSigs = nextCandidates[cp];
nextCandidates.clear();
LastSoftCPUpdated();
}
return true;
}
// returns true if vote is to be restransmitted
bool CastVoteSoftCheckpoint(int height, const uint256 &hash, const std::string &username, const std::string &sign) {
LOCK(cs_softCP);
if( (height % SOFT_CHECKPOINT_PERIOD) != 0 ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: height %d not multiple of SOFT_CHECKPOINT_PERIOD\n", height);
return false;
}
int hardCheckPointHeight = Checkpoints::GetHighestCheckpoint();
if( height < hardCheckPointHeight ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: height %d < hard checkpoint %d\n", height, hardCheckPointHeight);
return false;
}
if( height < lastSoftCP.first ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: height %d < soft checkpoint %d\n", height, lastSoftCP.first);
return false;
}
if( !uniqueUsersList.count(username) && !upcomingUsersList.count(username) ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: username '%s' not accepted\n", username.c_str());
return false;
}
Checkpoint cp = std::make_pair(height, hash);
if( nBestHeight < hardCheckPointHeight ) {
// still downloading blocks, we can't check signatures yet
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: vote for %d by '%s' added to unchecked\n", height, username.c_str());
uncheckedCandidates[cp][username] = sign;
return false;
}
if( !verifySignature( CPtoString(cp), username, sign) ) {
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: invalid signature by '%s'\n", username.c_str());
return false;
}
dbgprintf("SoftCheckpoints::CastVoteSoftCheckpoint: signature by '%s' verified for %d, casting vote\n",
username.c_str(), height);
return CastVerifiedVote( cp, username, sign );
}
bool CheckBlock(int nHeight, const uint256& hash) {
LOCK(cs_softCP);
if (!fEnabled)
return true;
if (!lastSoftCP.first || nHeight != lastSoftCP.first)
return true;
dbgprintf("SoftCheckpoints::CheckBlock: height %d isOk=%d\n", nHeight, hash == lastSoftCP.second);
return hash == lastSoftCP.second;
}
void RelayCP(const CSoftCheckpoint& cp, CNode* pfrom) {
LOCK(cs_vNodes);
dbgprintf("SoftCheckpoints::RelayCP: relaying softCP height %d from %s\n",
cp.nHeight, !pfrom ? "localhost" : pfrom->addr.ToString().c_str());
BOOST_FOREACH(CNode* pnode, vNodes) {
if(pnode == pfrom)
continue;
if (pnode->nVersion >= SOFT_CHECKPOINT_VERSION) {
dbgprintf("SoftCheckpoints::RelayCP: pushMessage to %s\n", pnode->addr.ToString().c_str());
pnode->PushMessage("cp", cp);
}
}
if( pfrom && lastSoftCP.first == cp.nHeight ) {
if( !mapBlockIndex.count(lastSoftCP.second) ) {
dbgprintf("SoftCheckpoints::RelayCP: requesting block height %d from node\n", cp.nHeight);
PushGetBlocks(pfrom, pindexBest, cp.blockHash);
}
}
}
void RelayLastCPToNode(CNode* pnode) {
LOCK(cs_softCP);
if (!lastSoftCP.first)
return;
if (pnode->nVersion >= SOFT_CHECKPOINT_VERSION) {
dbgprintf("SoftCheckpoints::RelayToLastCP: relaying lastSoftCP height %d (size %zd) to %s\n",
lastSoftCP.first, lastSoftCPSigs.size(), pnode->addr.ToString().c_str());
BOOST_FOREACH(const CPSigMap::value_type& i, lastSoftCPSigs) {
CSoftCheckpoint cp;
cp.nHeight = lastSoftCP.first;
cp.blockHash = lastSoftCP.second;
cp.vchUsername = std::vector<char>(i.first.begin(), i.first.end());
cp.vchSign = std::vector<char>(i.second.begin(), i.second.end());
pnode->PushMessage("cp", cp);
}
}
}
bool GetLastCPVotes(int &height, uint256 &hash, std::set<std::string> &usernames) {
LOCK(cs_softCP);
if (!lastSoftCP.first)
return false;
height = lastSoftCP.first;
hash = lastSoftCP.second;
usernames.clear();
BOOST_FOREACH(const CPSigMap::value_type& i, lastSoftCPSigs) {
usernames.insert(i.first);
}
return true;
}
}
<|endoftext|> |
<commit_before>#include <QDir>
#include <QImage>
#include <QQueue>
#include <QHash>
#include <QTimer>
#include "seafile-applet.h"
#include "configurator.h"
#include "account-mgr.h"
#include "api/requests.h"
#include "utils/paint-utils.h"
#include "utils/utils.h"
#include "avatar-service.h"
namespace {
const int kCheckPendingInterval = 1000; // 1s
const char *kAvatarsDirName = "avatars";
} // namespace
const int AvatarService::kAvatarSize = 48;
struct PendingRequestInfo {
int last_wait;
int time_to_wait;
void backoff() {
last_wait = qMax(last_wait, 1) * 2;
printf ("backoff: last_wait = %d\n", last_wait);
time_to_wait = last_wait;
}
bool isReady() {
return time_to_wait == 0;
}
void tick() {
time_to_wait = qMax(0, time_to_wait - 1);
}
};
class PendingAvatarRequestQueue
{
public:
PendingAvatarRequestQueue() {};
void enqueue(const QString& email) {
if (q_.contains(email)) {
return;
}
q_.enqueue(email);
}
void enqueueAndBackoff(const QString& email) {
PendingRequestInfo& info = wait_[email];
info.backoff();
enqueue(email);
}
void clearWait(const QString& email) {
wait_.remove(email);
}
void tick() {
QListIterator<QString> iter(q_);
while (iter.hasNext()) {
QString email = iter.next();
if (wait_.contains(email)) {
PendingRequestInfo& info = wait_[email];
info.tick();
}
}
}
QString dequeue() {
int i = 0, n = q_.size();
while (i++ < n) {
if (q_.isEmpty()) {
return QString();
}
QString email = q_.dequeue();
PendingRequestInfo info = wait_.value(email);
if (info.isReady()) {
return email;
} else {
q_.enqueue(email);
}
}
return QString();
}
void reset() {
q_.clear();
wait_.clear();
}
private:
QQueue<QString> q_;
QHash<QString, PendingRequestInfo> wait_;
};
AvatarService* AvatarService::singleton_;
AvatarService* AvatarService::instance()
{
if (singleton_ == NULL) {
static AvatarService instance;
singleton_ = &instance;
}
return singleton_;
}
AvatarService::AvatarService(QObject *parent)
: QObject(parent)
{
get_avatar_req_ = 0;
queue_ = new PendingAvatarRequestQueue;
timer_ = new QTimer(this);
connect(timer_, SIGNAL(timeout()), this, SLOT(checkPendingRequests()));
connect(seafApplet->accountManager(), SIGNAL(accountsChanged()),
this, SLOT(onAccountChanged()));
}
void AvatarService::start()
{
QDir seafile_dir(seafApplet->configurator()->seafileDir());
if (!seafile_dir.mkpath(kAvatarsDirName)) {
qWarning("Failed to create avatars folder");
QString err_msg = tr("Failed to create avatars folder");
seafApplet->errorAndExit(err_msg);
}
avatars_dir_ = seafile_dir.filePath(kAvatarsDirName);
timer_->start(kCheckPendingInterval);
}
// fist check in-memory-cache, then check saved image on disk
QImage AvatarService::loadAvatarFromLocal(const QString& email)
{
if (cache_.contains(email)) {
return cache_.value(email);
}
QImage ret;
if (avatarFileExists(email)) {
ret = QImage(getAvatarFilePath(email));
cache_[email] = ret;
}
return ret;
}
QString AvatarService::avatarPathForEmail(const Account& account, const QString& email)
{
return QDir(avatars_dir_).filePath(::md5(account.serverUrl.host() + email));
}
void AvatarService::fetchImageFromServer(const QString& email)
{
if (get_avatar_req_) {
if (email == get_avatar_req_->email()) {
return;
}
queue_->enqueue(email);
return;
}
const Account& account = seafApplet->accountManager()->currentAccount();
if (!account.isValid()) {
return;
}
get_avatar_req_ = new GetAvatarRequest(account, email, devicePixelRatio() * kAvatarSize);
connect(get_avatar_req_, SIGNAL(success(const QImage&)),
this, SLOT(onGetAvatarSuccess(const QImage&)));
connect(get_avatar_req_, SIGNAL(failed(const ApiError&)),
this, SLOT(onGetAvatarFailed(const ApiError&)));
get_avatar_req_->send();
}
void AvatarService::onGetAvatarSuccess(const QImage& img)
{
image_ = img;
QString email = get_avatar_req_->email();
cache_[email] = img;
// save image to avatars/ folder
QString path = avatarPathForEmail(get_avatar_req_->account(), email);
img.save(path, "PNG");
emit avatarUpdated(email, img);
get_avatar_req_->deleteLater();
get_avatar_req_ = 0;
queue_->clearWait(email);
}
void AvatarService::onGetAvatarFailed(const ApiError& error)
{
const QString email = get_avatar_req_->email();
printf ("get avatar failed for %s\n", email.toUtf8().data());
get_avatar_req_->deleteLater();
get_avatar_req_ = 0;
queue_->enqueueAndBackoff(email);
}
QImage AvatarService::getAvatar(const QString& email)
{
QImage img = loadAvatarFromLocal(email);
if (img.isNull()) {
if (!get_avatar_req_ || get_avatar_req_->email() != email) {
queue_->enqueue(email);
}
return devicePixelRatio() > 1 ?
QImage(":/images/account@2x.png") : QImage(":/images/account.png");
} else {
return img;
}
}
QString AvatarService::getAvatarFilePath(const QString& email)
{
const Account& account = seafApplet->accountManager()->currentAccount();
return avatarPathForEmail(account, email);
}
bool AvatarService::avatarFileExists(const QString& email)
{
QString path = getAvatarFilePath(email);
bool ret = QFileInfo(path).exists();
if (ret) {
QImage target(path);
// remove old avatar which is too small
if (target.size().width() < kAvatarSize ||
target.size().height() < kAvatarSize ) {
if (!QFile::remove(path))
qWarning("Unable to remove old avatar file %s", path.toUtf8().data());
ret = false;
}
}
return ret;
}
void AvatarService::checkPendingRequests()
{
queue_->tick();
if (get_avatar_req_ != 0) {
return;
}
QString email = queue_->dequeue();
if (!email.isEmpty()) {
fetchImageFromServer(email);
}
}
void AvatarService::onAccountChanged()
{
queue_->reset();
if (get_avatar_req_) {
delete get_avatar_req_;
get_avatar_req_ = 0;
}
cache_.clear();
}
<commit_msg>remove debug prints<commit_after>#include <QDir>
#include <QImage>
#include <QQueue>
#include <QHash>
#include <QTimer>
#include "seafile-applet.h"
#include "configurator.h"
#include "account-mgr.h"
#include "api/requests.h"
#include "utils/paint-utils.h"
#include "utils/utils.h"
#include "avatar-service.h"
namespace {
const int kCheckPendingInterval = 1000; // 1s
const char *kAvatarsDirName = "avatars";
} // namespace
const int AvatarService::kAvatarSize = 48;
struct PendingRequestInfo {
int last_wait;
int time_to_wait;
void backoff() {
last_wait = qMax(last_wait, 1) * 2;
time_to_wait = last_wait;
}
bool isReady() {
return time_to_wait == 0;
}
void tick() {
time_to_wait = qMax(0, time_to_wait - 1);
}
};
class PendingAvatarRequestQueue
{
public:
PendingAvatarRequestQueue() {};
void enqueue(const QString& email) {
if (q_.contains(email)) {
return;
}
q_.enqueue(email);
}
void enqueueAndBackoff(const QString& email) {
PendingRequestInfo& info = wait_[email];
info.backoff();
enqueue(email);
}
void clearWait(const QString& email) {
wait_.remove(email);
}
void tick() {
QListIterator<QString> iter(q_);
while (iter.hasNext()) {
QString email = iter.next();
if (wait_.contains(email)) {
PendingRequestInfo& info = wait_[email];
info.tick();
}
}
}
QString dequeue() {
int i = 0, n = q_.size();
while (i++ < n) {
if (q_.isEmpty()) {
return QString();
}
QString email = q_.dequeue();
PendingRequestInfo info = wait_.value(email);
if (info.isReady()) {
return email;
} else {
q_.enqueue(email);
}
}
return QString();
}
void reset() {
q_.clear();
wait_.clear();
}
private:
QQueue<QString> q_;
QHash<QString, PendingRequestInfo> wait_;
};
AvatarService* AvatarService::singleton_;
AvatarService* AvatarService::instance()
{
if (singleton_ == NULL) {
static AvatarService instance;
singleton_ = &instance;
}
return singleton_;
}
AvatarService::AvatarService(QObject *parent)
: QObject(parent)
{
get_avatar_req_ = 0;
queue_ = new PendingAvatarRequestQueue;
timer_ = new QTimer(this);
connect(timer_, SIGNAL(timeout()), this, SLOT(checkPendingRequests()));
connect(seafApplet->accountManager(), SIGNAL(accountsChanged()),
this, SLOT(onAccountChanged()));
}
void AvatarService::start()
{
QDir seafile_dir(seafApplet->configurator()->seafileDir());
if (!seafile_dir.mkpath(kAvatarsDirName)) {
qWarning("Failed to create avatars folder");
QString err_msg = tr("Failed to create avatars folder");
seafApplet->errorAndExit(err_msg);
}
avatars_dir_ = seafile_dir.filePath(kAvatarsDirName);
timer_->start(kCheckPendingInterval);
}
// fist check in-memory-cache, then check saved image on disk
QImage AvatarService::loadAvatarFromLocal(const QString& email)
{
if (cache_.contains(email)) {
return cache_.value(email);
}
QImage ret;
if (avatarFileExists(email)) {
ret = QImage(getAvatarFilePath(email));
cache_[email] = ret;
}
return ret;
}
QString AvatarService::avatarPathForEmail(const Account& account, const QString& email)
{
return QDir(avatars_dir_).filePath(::md5(account.serverUrl.host() + email));
}
void AvatarService::fetchImageFromServer(const QString& email)
{
if (get_avatar_req_) {
if (email == get_avatar_req_->email()) {
return;
}
queue_->enqueue(email);
return;
}
const Account& account = seafApplet->accountManager()->currentAccount();
if (!account.isValid()) {
return;
}
get_avatar_req_ = new GetAvatarRequest(account, email, devicePixelRatio() * kAvatarSize);
connect(get_avatar_req_, SIGNAL(success(const QImage&)),
this, SLOT(onGetAvatarSuccess(const QImage&)));
connect(get_avatar_req_, SIGNAL(failed(const ApiError&)),
this, SLOT(onGetAvatarFailed(const ApiError&)));
get_avatar_req_->send();
}
void AvatarService::onGetAvatarSuccess(const QImage& img)
{
image_ = img;
QString email = get_avatar_req_->email();
cache_[email] = img;
// save image to avatars/ folder
QString path = avatarPathForEmail(get_avatar_req_->account(), email);
img.save(path, "PNG");
emit avatarUpdated(email, img);
get_avatar_req_->deleteLater();
get_avatar_req_ = 0;
queue_->clearWait(email);
}
void AvatarService::onGetAvatarFailed(const ApiError& error)
{
const QString email = get_avatar_req_->email();
get_avatar_req_->deleteLater();
get_avatar_req_ = 0;
queue_->enqueueAndBackoff(email);
}
QImage AvatarService::getAvatar(const QString& email)
{
QImage img = loadAvatarFromLocal(email);
if (img.isNull()) {
if (!get_avatar_req_ || get_avatar_req_->email() != email) {
queue_->enqueue(email);
}
return devicePixelRatio() > 1 ?
QImage(":/images/account@2x.png") : QImage(":/images/account.png");
} else {
return img;
}
}
QString AvatarService::getAvatarFilePath(const QString& email)
{
const Account& account = seafApplet->accountManager()->currentAccount();
return avatarPathForEmail(account, email);
}
bool AvatarService::avatarFileExists(const QString& email)
{
QString path = getAvatarFilePath(email);
bool ret = QFileInfo(path).exists();
if (ret) {
QImage target(path);
// remove old avatar which is too small
if (target.size().width() < kAvatarSize ||
target.size().height() < kAvatarSize ) {
if (!QFile::remove(path))
qWarning("Unable to remove old avatar file %s", path.toUtf8().data());
ret = false;
}
}
return ret;
}
void AvatarService::checkPendingRequests()
{
queue_->tick();
if (get_avatar_req_ != 0) {
return;
}
QString email = queue_->dequeue();
if (!email.isEmpty()) {
fetchImageFromServer(email);
}
}
void AvatarService::onAccountChanged()
{
queue_->reset();
if (get_avatar_req_) {
delete get_avatar_req_;
get_avatar_req_ = 0;
}
cache_.clear();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: http://github.com/azerothcore/azerothcore-wotlk/LICENSE-GPL2
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*/
/*
* Ordered alphabetically using scriptname.
* Scriptnames of files in this file should be prefixed with "npc_pet_mag_".
*/
#include "ScriptMgr.h"
#include "ScriptPCH.h"
#include "ScriptedCreature.h"
#include "CombatAI.h"
#include "Pet.h"
enum MageSpells
{
SPELL_MAGE_CLONE_ME = 45204,
SPELL_MAGE_MASTERS_THREAT_LIST = 58838,
SPELL_PET_HIT_SCALING = 61013,
SPELL_SUMMON_MIRROR_IMAGE1 = 58831,
SPELL_SUMMON_MIRROR_IMAGE2 = 58833,
SPELL_SUMMON_MIRROR_IMAGE3 = 58834,
SPELL_SUMMON_MIRROR_IMAGE_GLYPH = 65047
};
class DeathEvent : public BasicEvent
{
public:
DeathEvent(Creature& owner) : BasicEvent(), _owner(owner) { }
bool Execute(uint64 /*eventTime*/, uint32 /*diff*/)
{
Unit::Kill(&_owner, &_owner);
return true;
}
private:
Creature& _owner;
};
class npc_pet_mage_mirror_image : public CreatureScript
{
public:
npc_pet_mage_mirror_image() : CreatureScript("npc_pet_mage_mirror_image") { }
struct npc_pet_mage_mirror_imageAI : CasterAI
{
npc_pet_mage_mirror_imageAI(Creature* creature) : CasterAI(creature) { }
uint32 selectionTimer;
uint64 _ebonGarogyleGUID;
void InitializeAI()
{
CasterAI::InitializeAI();
Unit* owner = me->GetOwner();
if (!owner)
return;
// Clone Me!
owner->CastSpell(me, SPELL_MAGE_CLONE_ME, true);
// xinef: Glyph of Mirror Image (4th copy)
float angle = 0.0f;
switch (me->GetUInt32Value(UNIT_CREATED_BY_SPELL))
{
case SPELL_SUMMON_MIRROR_IMAGE1:
angle = 0.5f * M_PI;
break;
case SPELL_SUMMON_MIRROR_IMAGE2:
angle = M_PI;
break;
case SPELL_SUMMON_MIRROR_IMAGE3:
angle = 1.5f * M_PI;
break;
}
((Minion*)me)->SetFollowAngle(angle);
me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle(), MOTION_SLOT_ACTIVE);
me->SetReactState(REACT_PASSIVE);
// Xinef: Inherit Master's Threat List (not yet implemented)
//owner->CastSpell((Unit*)NULL, SPELL_MAGE_MASTERS_THREAT_LIST, true);
HostileReference* ref = owner->getHostileRefManager().getFirst();
while (ref)
{
if (Unit* unit = ref->GetSource()->GetOwner())
unit->AddThreat(me, ref->getThreat() - ref->getTempThreatModifier());
ref = ref->next();
}
_ebonGarogyleGUID = 0;
// Xinef: copy caster auras
Unit::VisibleAuraMap const* visibleAuraMap = owner->GetVisibleAuras();
for (Unit::VisibleAuraMap::const_iterator itr = visibleAuraMap->begin(); itr != visibleAuraMap->end(); ++itr)
if (Aura* visAura = itr->second->GetBase())
{
// Ebon Gargoyle
if (visAura->GetId() == 49206 && me->GetUInt32Value(UNIT_CREATED_BY_SPELL) == SPELL_SUMMON_MIRROR_IMAGE1)
{
if (Unit* garogyle = visAura->GetCaster())
_ebonGarogyleGUID = garogyle->GetGUID();
continue;
}
SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(visAura->GetId());
if (bounds.first != bounds.second)
continue;
std::vector<int32> const* spellTriggered = sSpellMgr->GetSpellLinked(visAura->GetId() + SPELL_LINK_AURA);
if (!spellTriggered || !spellTriggered->empty())
continue;
if (Aura* newAura = me->AddAura(visAura->GetId(), me))
newAura->SetDuration(visAura->GetDuration());
}
me->m_Events.AddEvent(new DeathEvent(*me), me->m_Events.CalculateTime(29500));
}
// Do not reload Creature templates on evade mode enter - prevent visual lost
void EnterEvadeMode()
{
if (me->IsInEvadeMode() || !me->IsAlive())
return;
Unit* owner = me->GetCharmerOrOwner();
me->CombatStop(true);
if (owner && !me->HasUnitState(UNIT_STATE_FOLLOW))
{
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle(), MOTION_SLOT_ACTIVE);
}
}
bool MySelectNextTarget()
{
if (_ebonGarogyleGUID)
{
if (Unit* garogyle = ObjectAccessor::GetUnit(*me, _ebonGarogyleGUID))
garogyle->GetAI()->AttackStart(me);
_ebonGarogyleGUID = 0;
}
Unit* owner = me->GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
{
Unit* selection = owner->ToPlayer()->GetSelectedUnit();
if (selection && selection != me->GetVictim())
{
// target has cc, search target without cc!
if (selection->HasBreakableByDamageCrowdControlAura() || !me->IsValidAttackTarget(selection))
{
return false;
}
me->getThreatManager().resetAllAggro();
me->AddThreat(selection, 1000000.0f);
AttackStart(selection);
return true;
}
}
return false;
}
void Reset()
{
selectionTimer = 0;
}
void UpdateAI(uint32 diff)
{
events.Update(diff);
if (events.GetTimer() < 1200)
return;
if (!me->IsInCombat() || !me->GetVictim())
{
MySelectNextTarget();
return;
}
if (me->GetVictim()->HasBreakableByDamageCrowdControlAura() || !me->GetVictim()->IsAlive())
{
me->InterruptNonMeleeSpells(false);
if (!MySelectNextTarget())
EnterEvadeMode();
return;
}
selectionTimer += diff;
if (selectionTimer >= 1000)
{
MySelectNextTarget();
selectionTimer = 0;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 spellId = events.GetEvent())
{
events.RescheduleEvent(spellId, spellId == 59637 ? 6500 : 2500);
me->CastSpell(me->GetVictim(), spellId, false);
}
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_pet_mage_mirror_imageAI(creature);
}
};
void AddSC_mage_pet_scripts()
{
new npc_pet_mage_mirror_image();
}
<commit_msg>Scripts/PetMage: fixed a crash with DK's Gargoyle and Mirror Image<commit_after>/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: http://github.com/azerothcore/azerothcore-wotlk/LICENSE-GPL2
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*/
/*
* Ordered alphabetically using scriptname.
* Scriptnames of files in this file should be prefixed with "npc_pet_mag_".
*/
#include "ScriptMgr.h"
#include "ScriptPCH.h"
#include "ScriptedCreature.h"
#include "CombatAI.h"
#include "Pet.h"
enum MageSpells
{
SPELL_MAGE_CLONE_ME = 45204,
SPELL_MAGE_MASTERS_THREAT_LIST = 58838,
SPELL_PET_HIT_SCALING = 61013,
SPELL_SUMMON_MIRROR_IMAGE1 = 58831,
SPELL_SUMMON_MIRROR_IMAGE2 = 58833,
SPELL_SUMMON_MIRROR_IMAGE3 = 58834,
SPELL_SUMMON_MIRROR_IMAGE_GLYPH = 65047
};
class DeathEvent : public BasicEvent
{
public:
DeathEvent(Creature& owner) : BasicEvent(), _owner(owner) { }
bool Execute(uint64 /*eventTime*/, uint32 /*diff*/)
{
Unit::Kill(&_owner, &_owner);
return true;
}
private:
Creature& _owner;
};
class npc_pet_mage_mirror_image : public CreatureScript
{
public:
npc_pet_mage_mirror_image() : CreatureScript("npc_pet_mage_mirror_image") { }
struct npc_pet_mage_mirror_imageAI : CasterAI
{
npc_pet_mage_mirror_imageAI(Creature* creature) : CasterAI(creature) { }
uint32 selectionTimer;
uint64 _ebonGargoyleGUID;
void InitializeAI()
{
CasterAI::InitializeAI();
Unit* owner = me->GetOwner();
if (!owner)
return;
// Clone Me!
owner->CastSpell(me, SPELL_MAGE_CLONE_ME, true);
// xinef: Glyph of Mirror Image (4th copy)
float angle = 0.0f;
switch (me->GetUInt32Value(UNIT_CREATED_BY_SPELL))
{
case SPELL_SUMMON_MIRROR_IMAGE1:
angle = 0.5f * M_PI;
break;
case SPELL_SUMMON_MIRROR_IMAGE2:
angle = M_PI;
break;
case SPELL_SUMMON_MIRROR_IMAGE3:
angle = 1.5f * M_PI;
break;
}
((Minion*)me)->SetFollowAngle(angle);
me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle(), MOTION_SLOT_ACTIVE);
me->SetReactState(REACT_PASSIVE);
// Xinef: Inherit Master's Threat List (not yet implemented)
//owner->CastSpell((Unit*)NULL, SPELL_MAGE_MASTERS_THREAT_LIST, true);
HostileReference* ref = owner->getHostileRefManager().getFirst();
while (ref)
{
if (Unit* unit = ref->GetSource()->GetOwner())
unit->AddThreat(me, ref->getThreat() - ref->getTempThreatModifier());
ref = ref->next();
}
_ebonGargoyleGUID = 0;
// Xinef: copy caster auras
Unit::VisibleAuraMap const* visibleAuraMap = owner->GetVisibleAuras();
for (Unit::VisibleAuraMap::const_iterator itr = visibleAuraMap->begin(); itr != visibleAuraMap->end(); ++itr)
if (Aura* visAura = itr->second->GetBase())
{
// Ebon Gargoyle
if (visAura->GetId() == 49206 && me->GetUInt32Value(UNIT_CREATED_BY_SPELL) == SPELL_SUMMON_MIRROR_IMAGE1)
{
if (Unit* gargoyle = visAura->GetCaster())
_ebonGargoyleGUID = gargoyle->GetGUID();
continue;
}
SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(visAura->GetId());
if (bounds.first != bounds.second)
continue;
std::vector<int32> const* spellTriggered = sSpellMgr->GetSpellLinked(visAura->GetId() + SPELL_LINK_AURA);
if (!spellTriggered || !spellTriggered->empty())
continue;
if (Aura* newAura = me->AddAura(visAura->GetId(), me))
newAura->SetDuration(visAura->GetDuration());
}
me->m_Events.AddEvent(new DeathEvent(*me), me->m_Events.CalculateTime(29500));
}
// Do not reload Creature templates on evade mode enter - prevent visual lost
void EnterEvadeMode()
{
if (me->IsInEvadeMode() || !me->IsAlive())
return;
Unit* owner = me->GetCharmerOrOwner();
me->CombatStop(true);
if (owner && !me->HasUnitState(UNIT_STATE_FOLLOW))
{
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle(), MOTION_SLOT_ACTIVE);
}
}
bool MySelectNextTarget()
{
if (_ebonGargoyleGUID)
{
Unit* gargoyle = ObjectAccessor::GetUnit(*me, _ebonGargoyleGUID);
if (gargoyle && gargoyle->GetAI())
gargoyle->GetAI()->AttackStart(me);
_ebonGargoyleGUID = 0;
}
Unit* owner = me->GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
{
Unit* selection = owner->ToPlayer()->GetSelectedUnit();
if (selection && selection != me->GetVictim())
{
// target has cc, search target without cc!
if (selection->HasBreakableByDamageCrowdControlAura() || !me->IsValidAttackTarget(selection))
{
return false;
}
me->getThreatManager().resetAllAggro();
me->AddThreat(selection, 1000000.0f);
AttackStart(selection);
return true;
}
}
return false;
}
void Reset()
{
selectionTimer = 0;
}
void UpdateAI(uint32 diff)
{
events.Update(diff);
if (events.GetTimer() < 1200)
return;
if (!me->IsInCombat() || !me->GetVictim())
{
MySelectNextTarget();
return;
}
if (me->GetVictim()->HasBreakableByDamageCrowdControlAura() || !me->GetVictim()->IsAlive())
{
me->InterruptNonMeleeSpells(false);
if (!MySelectNextTarget())
EnterEvadeMode();
return;
}
selectionTimer += diff;
if (selectionTimer >= 1000)
{
MySelectNextTarget();
selectionTimer = 0;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 spellId = events.GetEvent())
{
events.RescheduleEvent(spellId, spellId == 59637 ? 6500 : 2500);
me->CastSpell(me->GetVictim(), spellId, false);
}
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_pet_mage_mirror_imageAI(creature);
}
};
void AddSC_mage_pet_scripts()
{
new npc_pet_mage_mirror_image();
}
<|endoftext|> |
<commit_before>#include "kernel.h"
#include "raster.h"
#include "linerasterizer.h"
#include "pixeliterator.h"
using namespace Ilwis;
bool PixelIterator::isValid() const {
return _isValid;
}
PixelIterator::PixelIterator() : _localOffset(0), _currentBlock(0), _step(0), _flow(fXYZ),_isValid(false),_positionid(0) {
}
PixelIterator::PixelIterator(IGridCoverage raster, const Box3D<>& box, double step) :
_raster(raster),
_box(box),
_localOffset(0),
_currentBlock(0),
_step(step),
_flow(fXYZ),
_isValid(false)
{
init();
}
PixelIterator::PixelIterator(const PixelIterator& iter) {
copy(iter);
}
void PixelIterator::copy(const PixelIterator &iter) {
_raster = iter._raster;
if ( _raster.isValid()) // TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future
_grid = _raster->_grid.data();
_box = iter._box;
_step = iter._step;
_isValid = iter._isValid;
_flow = iter._flow;
_positionid = iter._positionid;
_x = iter._x;
_y = iter._y;
_z = iter._z;
_endx = iter._endx;
_endy = iter._endy;
_endz = iter._endz;
_positionid = iter._positionid;
_endpositionid = iter._endpositionid;
_localOffset = iter._localOffset;
_currentBlock = iter._currentBlock;
}
void PixelIterator::init() {
const Size& sz = _raster->size();
if ( _box.isNull()) {
_box = Box3D<>(sz);
}
_box.ensure(sz);
_x = _box.min_corner().x();
_y = _box.min_corner().y();
_z = _box.min_corner().z();
_endx = _box.max_corner().x();
_endy = _box.max_corner().y();
_endz = _box.max_corner().z();
bool inside = contains(Pixel(_x,_y));
if ( inside) {
_grid = _raster->grid();
}
if ( _grid == 0) {
_isValid = false;
ERROR1(ERR_NO_INITIALIZED_1,_raster->name());
return;
}
initPosition();
quint64 shift = _x + _y * 1e5 + (_z + 1) *1e10;
_endpositionid = _positionid + shift;
//_endpositionid = _endx + _endy * 1e5 + _endz*1e10 + _raster->id() * 1e13;
_isValid = inside;
_xChanged = _yChanged = _zChanged = false;
}
inline bool PixelIterator::moveXYZ(int n) {
quint32 delta = n * _step;
_x += delta;
_localOffset += n;
_xChanged = true;
_yChanged = _zChanged = false;
if ( _x > _endx) {
quint32 xsize = _grid->size().xsize();
_y += (delta / xsize) + 1;
_x = _box.min_corner().x();
_yChanged = true;
qint32 ylocal = _y % _grid->maxLines();
_localOffset = _x + ylocal * xsize;
if ( ylocal == 0) {
++_currentBlock;
_localOffset = _x;
}
if ( _y > _endy) {
++_z;
++_currentBlock;
_zChanged = true;
_y = _box.min_corner().y();
_localOffset = _box.min_corner().x();
if ( _z >= _endz) { // done with this iteration block
_positionid = _endpositionid;
return false;
}
}
}
return true;
}
inline bool PixelIterator::isAtEnd() const {
return _x == _box.max_corner().x() &&
_y == _box.max_corner().y() &&
_z == _box.max_corner().z();
}
Voxel PixelIterator::position() const
{
return Voxel(_x, _y, _z);
}
bool PixelIterator::move(int n) {
bool ok;
if (isAtEnd()) {
_positionid = _endpositionid;
return false;
}
if ( _flow == fXYZ) {
ok = moveXYZ(n);
}
else if ( _flow == fYXZ){
}
if (ok)
_positionid = calcPosId();
return ok;
}
PixelIterator& PixelIterator::operator=(const PixelIterator& iter) {
copy(iter);
return *this;
}
inline PixelIterator PixelIterator::operator++(int) {
PixelIterator temp(*this);
if(!move(1))
return end();
return temp;
}
inline PixelIterator PixelIterator::operator--(int) {
PixelIterator temp(*this);
move(-1);
return temp;
}
bool PixelIterator::operator==(const PixelIterator& iter) const{
return _positionid == iter._positionid;
}
bool PixelIterator::operator!=(const PixelIterator& iter) const{
return ! operator ==(iter);
}
PixelIterator PixelIterator::end() const {
return PixelIterator(_endpositionid);
}
void PixelIterator::setFlow(Flow flw) {
_flow = flw;
}
bool PixelIterator::contains(const Pixel& pix) {
return pix.x() >= _box.min_corner().x() &&
pix.x() < _box.max_corner().x() &&
pix.y() >= _box.min_corner().y() &&
pix.y() < _box.max_corner().y();
}
bool PixelIterator::xchanged() const {
return _xChanged;
}
bool PixelIterator::ychanged() const {
return _yChanged;
}
bool PixelIterator::zchanged() const {
return _zChanged;
}
void PixelIterator::initPosition() {
const Size& sz = _raster->size();
quint64 linearPos = _y * sz.xsize() + _x;
_currentBlock = _y / _grid->maxLines();
_localOffset = linearPos - _currentBlock * _grid->maxLines() * sz.xsize();
_currentBlock += _z * _grid->blocksPerBand();
_positionid = calcPosId();
}
<commit_msg>solved some errors with stepsizes that are bigger than 1<commit_after>#include "kernel.h"
#include "raster.h"
#include "linerasterizer.h"
#include "pixeliterator.h"
using namespace Ilwis;
bool PixelIterator::isValid() const {
return _isValid;
}
PixelIterator::PixelIterator() : _localOffset(0), _currentBlock(0), _step(0), _flow(fXYZ),_isValid(false),_positionid(0) {
}
PixelIterator::PixelIterator(IGridCoverage raster, const Box3D<>& box, double step) :
_raster(raster),
_box(box),
_localOffset(0),
_currentBlock(0),
_step(step),
_flow(fXYZ),
_isValid(false)
{
init();
}
PixelIterator::PixelIterator(const PixelIterator& iter) {
copy(iter);
}
void PixelIterator::copy(const PixelIterator &iter) {
_raster = iter._raster;
if ( _raster.isValid()) // TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future
_grid = _raster->_grid.data();
_box = iter._box;
_step = iter._step;
_isValid = iter._isValid;
_flow = iter._flow;
_positionid = iter._positionid;
_x = iter._x;
_y = iter._y;
_z = iter._z;
_endx = iter._endx;
_endy = iter._endy;
_endz = iter._endz;
_positionid = iter._positionid;
_endpositionid = iter._endpositionid;
_localOffset = iter._localOffset;
_currentBlock = iter._currentBlock;
}
void PixelIterator::init() {
const Size& sz = _raster->size();
if ( _box.isNull()) {
_box = Box3D<>(sz);
}
_box.ensure(sz);
_x = _box.min_corner().x();
_y = _box.min_corner().y();
_z = _box.min_corner().z();
_endx = _box.max_corner().x();
_endy = _box.max_corner().y();
_endz = _box.max_corner().z();
bool inside = contains(Pixel(_x,_y));
if ( inside) {
_grid = _raster->grid();
}
if ( _grid == 0) {
_isValid = false;
ERROR1(ERR_NO_INITIALIZED_1,_raster->name());
return;
}
initPosition();
quint64 shift = _x + _y * 1e5 + (_z + 1) *1e10;
_endpositionid = _positionid + shift;
//_endpositionid = _endx + _endy * 1e5 + _endz*1e10 + _raster->id() * 1e13;
_isValid = inside;
_xChanged = _yChanged = _zChanged = false;
}
inline bool PixelIterator::moveXYZ(int n) {
quint32 delta = n * _step;
_x += delta;
_localOffset += n;
_xChanged = true;
_yChanged = _zChanged = false;
if ( _x > _endx) {
quint32 xsize = _grid->size().xsize();
_y += (delta / xsize) + 1;
_x = _box.min_corner().x();
_yChanged = true;
qint32 ylocal = _y % _grid->maxLines();
quint32 block = _y / _grid->maxLines();
_localOffset = _x + ylocal * xsize;
if ( block != _currentBlock) {
_currentBlock = block;
_localOffset = _x;
}
if ( _y > _endy) {
++_z;
++_currentBlock;
_zChanged = true;
_y = _box.min_corner().y();
_localOffset = _box.min_corner().x();
if ( _z >= _endz) { // done with this iteration block
_positionid = _endpositionid;
return false;
}
}
}
return true;
}
inline bool PixelIterator::isAtEnd() const {
return _x == _box.max_corner().x() &&
_y == _box.max_corner().y() &&
_z == _box.max_corner().z();
}
Voxel PixelIterator::position() const
{
return Voxel(_x, _y, _z);
}
bool PixelIterator::move(int n) {
bool ok;
if (isAtEnd()) {
_positionid = _endpositionid;
return false;
}
if ( _flow == fXYZ) {
ok = moveXYZ(n);
}
else if ( _flow == fYXZ){
}
if (ok)
_positionid = calcPosId();
return ok;
}
PixelIterator& PixelIterator::operator=(const PixelIterator& iter) {
copy(iter);
return *this;
}
inline PixelIterator PixelIterator::operator++(int) {
PixelIterator temp(*this);
if(!move(1))
return end();
return temp;
}
inline PixelIterator PixelIterator::operator--(int) {
PixelIterator temp(*this);
move(-1);
return temp;
}
bool PixelIterator::operator==(const PixelIterator& iter) const{
return _positionid == iter._positionid;
}
bool PixelIterator::operator!=(const PixelIterator& iter) const{
return ! operator ==(iter);
}
PixelIterator PixelIterator::end() const {
return PixelIterator(_endpositionid);
}
void PixelIterator::setFlow(Flow flw) {
_flow = flw;
}
bool PixelIterator::contains(const Pixel& pix) {
return pix.x() >= _box.min_corner().x() &&
pix.x() < _box.max_corner().x() &&
pix.y() >= _box.min_corner().y() &&
pix.y() < _box.max_corner().y();
}
bool PixelIterator::xchanged() const {
return _xChanged;
}
bool PixelIterator::ychanged() const {
return _yChanged;
}
bool PixelIterator::zchanged() const {
return _zChanged;
}
void PixelIterator::initPosition() {
const Size& sz = _raster->size();
quint64 linearPos = _y * sz.xsize() + _x;
_currentBlock = _y / _grid->maxLines();
_localOffset = linearPos - _currentBlock * _grid->maxLines() * sz.xsize();
_currentBlock += _z * _grid->blocksPerBand();
_positionid = calcPosId();
}
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "el/elemental_forms.h"
#include "xenia/base/logging.h"
#include "xenia/emulator.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xam_private.h"
#include "xenia/ui/window.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
SHIM_CALL XamIsUIActive_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
XELOGD("XamIsUIActive()");
SHIM_SET_RETURN_32(el::ModalWindow::is_any_visible());
}
class MessageBoxWindow : public el::ModalWindow {
public:
MessageBoxWindow(xe::threading::Fence* fence)
: ModalWindow([fence]() { fence->Signal(); }) {}
~MessageBoxWindow() override = default;
// TODO(benvanik): icon.
void Show(el::Element* root_element, std::wstring title, std::wstring message,
std::vector<std::wstring> buttons, uint32_t default_button,
uint32_t* out_chosen_button) {
title_ = std::move(title);
message_ = std::move(message);
buttons_ = std::move(buttons);
default_button_ = default_button;
out_chosen_button_ = out_chosen_button;
// In case we are cancelled, always set default button.
*out_chosen_button_ = default_button;
ModalWindow::Show(root_element);
EnsureFocus();
}
protected:
void BuildUI() override {
using namespace el::dsl;
set_text(xe::to_string(title_));
auto button_bar = LayoutBoxNode().distribution_position(
LayoutDistributionPosition::kRightBottom);
for (int32_t i = 0; i < buttons_.size(); ++i) {
button_bar.child(ButtonNode(xe::to_string(buttons_[i]).c_str())
.id(100 + i)
.data(100 + i));
}
LoadNodeTree(
LayoutBoxNode()
.axis(Axis::kY)
.gravity(Gravity::kAll)
.position(LayoutPosition::kLeftTop)
.distribution(LayoutDistribution::kAvailable)
.distribution_position(LayoutDistributionPosition::kLeftTop)
.child(LabelNode(xe::to_string(message_).c_str()))
.child(button_bar));
auto default_button = GetElementById<el::Button>(100 + default_button_);
el::Button::set_auto_focus_state(true);
default_button->set_focus(el::FocusReason::kNavigation);
}
bool OnEvent(const el::Event& ev) override {
if (ev.target->IsOfType<el::Button>() && ev.type == el::EventType::kClick) {
int data_value = ev.target->data.as_integer();
if (data_value) {
*out_chosen_button_ = data_value - 100;
}
Die();
return true;
}
return ModalWindow::OnEvent(ev);
}
std::wstring title_;
std::wstring message_;
std::vector<std::wstring> buttons_;
uint32_t default_button_ = 0;
uint32_t* out_chosen_button_ = nullptr;
};
// http://www.se7ensins.com/forums/threads/working-xshowmessageboxui.844116/?jdfwkey=sb0vm
SHIM_CALL XamShowMessageBoxUI_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t user_index = SHIM_GET_ARG_32(0);
uint32_t title_ptr = SHIM_GET_ARG_32(1);
uint32_t text_ptr = SHIM_GET_ARG_32(2);
uint32_t button_count = SHIM_GET_ARG_32(3);
uint32_t button_ptrs = SHIM_GET_ARG_32(4);
uint32_t active_button = SHIM_GET_ARG_32(5);
uint32_t flags = SHIM_GET_ARG_32(6);
uint32_t result_ptr = SHIM_GET_ARG_32(7);
uint32_t overlapped_ptr = SHIM_GET_ARG_32(8);
auto title = xe::load_and_swap<std::wstring>(SHIM_MEM_ADDR(title_ptr));
auto text = xe::load_and_swap<std::wstring>(SHIM_MEM_ADDR(text_ptr));
std::vector<std::wstring> buttons;
std::wstring all_buttons;
for (uint32_t j = 0; j < button_count; ++j) {
uint32_t button_ptr = SHIM_MEM_32(button_ptrs + j * 4);
auto button = xe::load_and_swap<std::wstring>(SHIM_MEM_ADDR(button_ptr));
all_buttons.append(button);
if (j + 1 < button_count) {
all_buttons.append(L" | ");
}
buttons.push_back(button);
}
XELOGD(
"XamShowMessageBoxUI(%d, %.8X(%S), %.8X(%S), %d, %.8X(%S), %d, %X, %.8X, "
"%.8X)",
user_index, title_ptr, title.c_str(), text_ptr, text.c_str(),
button_count, button_ptrs, all_buttons.c_str(), active_button, flags,
result_ptr, overlapped_ptr);
uint32_t chosen_button;
if (FLAGS_headless) {
// Auto-pick the focused button.
chosen_button = active_button;
} else {
auto display_window = kernel_state->emulator()->display_window();
xe::threading::Fence fence;
display_window->loop()->PostSynchronous([&]() {
auto root_element = display_window->root_element();
auto window = new MessageBoxWindow(&fence);
switch (flags & 0xF) {
case 0:
// config.pszMainIcon = nullptr;
break;
case 1:
// config.pszMainIcon = TD_ERROR_ICON;
break;
case 2:
// config.pszMainIcon = TD_WARNING_ICON;
break;
case 3:
// config.pszMainIcon = TD_INFORMATION_ICON;
break;
}
window->Show(root_element, title, text, buttons, active_button,
&chosen_button);
});
fence.Wait();
}
SHIM_SET_MEM_32(result_ptr, chosen_button);
kernel_state->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_SUCCESS);
SHIM_SET_RETURN_32(X_ERROR_IO_PENDING);
}
class DirtyDiscWindow : public el::ModalWindow {
public:
DirtyDiscWindow(xe::threading::Fence* fence)
: ModalWindow([fence]() { fence->Signal(); }) {}
~DirtyDiscWindow() override = default;
protected:
void BuildUI() override {
using namespace el::dsl;
set_text("Disc Read Error");
LoadNodeTree(
LayoutBoxNode()
.axis(Axis::kY)
.gravity(Gravity::kAll)
.position(LayoutPosition::kLeftTop)
.distribution(LayoutDistribution::kAvailable)
.distribution_position(LayoutDistributionPosition::kLeftTop)
.child(LabelNode(
"There's been an issue reading content from the game disc."))
.child(LabelNode(
"This is likely caused by bad or unimplemented file IO "
"calls."))
.child(LayoutBoxNode()
.distribution_position(
LayoutDistributionPosition::kRightBottom)
.child(ButtonNode("Exit").id("exit_button"))));
}
bool OnEvent(const el::Event& ev) override {
if (ev.target->id() == TBIDC("exit_button") &&
ev.type == el::EventType::kClick) {
Die();
return true;
}
return ModalWindow::OnEvent(ev);
}
};
SHIM_CALL XamShowDirtyDiscErrorUI_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t user_index = SHIM_GET_ARG_32(0);
XELOGD("XamShowDirtyDiscErrorUI(%d)", user_index);
if (FLAGS_headless) {
assert_always();
exit(1);
return;
}
auto display_window = kernel_state->emulator()->display_window();
xe::threading::Fence fence;
display_window->loop()->PostSynchronous([&]() {
auto root_element = display_window->root_element();
auto window = new DirtyDiscWindow(&fence);
window->Show(root_element);
});
fence.Wait();
// This is death, and should never return.
// TODO(benvanik): cleaner exit.
assert_always();
exit(1);
}
} // namespace kernel
} // namespace xe
void xe::kernel::xam::RegisterUIExports(
xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {
SHIM_SET_MAPPING("xam.xex", XamIsUIActive, state);
SHIM_SET_MAPPING("xam.xex", XamShowMessageBoxUI, state);
SHIM_SET_MAPPING("xam.xex", XamShowDirtyDiscErrorUI, state);
}
<commit_msg>Xam keyboard input UI Moved XamShowDeviceSelectorUI here<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "el/elemental_forms.h"
#include "xenia/base/logging.h"
#include "xenia/emulator.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xam_private.h"
#include "xenia/ui/window.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
SHIM_CALL XamIsUIActive_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
XELOGD("XamIsUIActive()");
SHIM_SET_RETURN_32(el::ModalWindow::is_any_visible());
}
class MessageBoxWindow : public el::ModalWindow {
public:
MessageBoxWindow(xe::threading::Fence* fence)
: ModalWindow([fence]() { fence->Signal(); }) {}
~MessageBoxWindow() override = default;
// TODO(benvanik): icon.
void Show(el::Element* root_element, std::wstring title, std::wstring message,
std::vector<std::wstring> buttons, uint32_t default_button,
uint32_t* out_chosen_button) {
title_ = std::move(title);
message_ = std::move(message);
buttons_ = std::move(buttons);
default_button_ = default_button;
out_chosen_button_ = out_chosen_button;
// In case we are cancelled, always set default button.
*out_chosen_button_ = default_button;
ModalWindow::Show(root_element);
EnsureFocus();
}
protected:
void BuildUI() override {
using namespace el::dsl;
set_text(xe::to_string(title_));
auto button_bar = LayoutBoxNode().distribution_position(
LayoutDistributionPosition::kRightBottom);
for (int32_t i = 0; i < buttons_.size(); ++i) {
button_bar.child(ButtonNode(xe::to_string(buttons_[i]).c_str())
.id(100 + i)
.data(100 + i));
}
LoadNodeTree(
LayoutBoxNode()
.axis(Axis::kY)
.gravity(Gravity::kAll)
.position(LayoutPosition::kLeftTop)
.distribution(LayoutDistribution::kAvailable)
.distribution_position(LayoutDistributionPosition::kLeftTop)
.child(LabelNode(xe::to_string(message_).c_str()))
.child(button_bar));
auto default_button = GetElementById<el::Button>(100 + default_button_);
el::Button::set_auto_focus_state(true);
default_button->set_focus(el::FocusReason::kNavigation);
}
bool OnEvent(const el::Event& ev) override {
if (ev.target->IsOfType<el::Button>() &&
(ev.type == el::EventType::kClick ||
ev.special_key == el::SpecialKey::kEnter)) {
int data_value = ev.target->data.as_integer();
if (data_value) {
*out_chosen_button_ = data_value - 100;
}
Die();
return true;
}
return ModalWindow::OnEvent(ev);
}
std::wstring title_;
std::wstring message_;
std::vector<std::wstring> buttons_;
uint32_t default_button_ = 0;
uint32_t* out_chosen_button_ = nullptr;
};
// http://www.se7ensins.com/forums/threads/working-xshowmessageboxui.844116/?jdfwkey=sb0vm
SHIM_CALL XamShowMessageBoxUI_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t user_index = SHIM_GET_ARG_32(0);
uint32_t title_ptr = SHIM_GET_ARG_32(1);
uint32_t text_ptr = SHIM_GET_ARG_32(2);
uint32_t button_count = SHIM_GET_ARG_32(3);
uint32_t button_ptrs = SHIM_GET_ARG_32(4);
uint32_t active_button = SHIM_GET_ARG_32(5);
uint32_t flags = SHIM_GET_ARG_32(6);
uint32_t result_ptr = SHIM_GET_ARG_32(7);
uint32_t overlapped_ptr = SHIM_GET_ARG_32(8);
auto title = xe::load_and_swap<std::wstring>(SHIM_MEM_ADDR(title_ptr));
auto text = xe::load_and_swap<std::wstring>(SHIM_MEM_ADDR(text_ptr));
std::vector<std::wstring> buttons;
std::wstring all_buttons;
for (uint32_t j = 0; j < button_count; ++j) {
uint32_t button_ptr = SHIM_MEM_32(button_ptrs + j * 4);
auto button = xe::load_and_swap<std::wstring>(SHIM_MEM_ADDR(button_ptr));
all_buttons.append(button);
if (j + 1 < button_count) {
all_buttons.append(L" | ");
}
buttons.push_back(button);
}
XELOGD(
"XamShowMessageBoxUI(%d, %.8X(%S), %.8X(%S), %d, %.8X(%S), %d, %X, %.8X, "
"%.8X)",
user_index, title_ptr, title.c_str(), text_ptr, text.c_str(),
button_count, button_ptrs, all_buttons.c_str(), active_button, flags,
result_ptr, overlapped_ptr);
uint32_t chosen_button;
if (FLAGS_headless) {
// Auto-pick the focused button.
chosen_button = active_button;
} else {
auto display_window = kernel_state->emulator()->display_window();
xe::threading::Fence fence;
display_window->loop()->PostSynchronous([&]() {
auto root_element = display_window->root_element();
auto window = new MessageBoxWindow(&fence);
switch (flags & 0xF) {
case 0:
// config.pszMainIcon = nullptr;
break;
case 1:
// config.pszMainIcon = TD_ERROR_ICON;
break;
case 2:
// config.pszMainIcon = TD_WARNING_ICON;
break;
case 3:
// config.pszMainIcon = TD_INFORMATION_ICON;
break;
}
window->Show(root_element, title, text, buttons, active_button,
&chosen_button);
});
fence.Wait();
}
SHIM_SET_MEM_32(result_ptr, chosen_button);
kernel_state->CompleteOverlappedImmediate(overlapped_ptr, X_ERROR_SUCCESS);
SHIM_SET_RETURN_32(X_ERROR_IO_PENDING);
}
class KeyboardInputWindow : public el::ModalWindow {
public:
KeyboardInputWindow(xe::threading::Fence* fence)
: ModalWindow([fence]() { fence->Signal(); }) {}
~KeyboardInputWindow() override = default;
// TODO(benvanik): icon.
void Show(el::Element* root_element, std::wstring title,
std::wstring description, std::wstring default_text,
std::wstring* out_text, size_t max_length) {
title_ = std::move(title);
description_ = std::move(description);
default_text_ = std::move(default_text);
out_text_ = out_text;
max_length_ = max_length;
// Incase we're cancelled, set as the default text.
if (out_text) {
*out_text = default_text;
}
ModalWindow::Show(root_element);
EnsureFocus();
}
protected:
void BuildUI() override {
using namespace el::dsl;
set_text(xe::to_string(title_));
LoadNodeTree(
LayoutBoxNode()
.axis(Axis::kY)
.gravity(Gravity::kAll)
.position(LayoutPosition::kLeftTop)
.min_width(300)
.distribution(LayoutDistribution::kAvailable)
.distribution_position(LayoutDistributionPosition::kLeftTop)
.child(LabelNode(xe::to_string(description_).c_str()))
.child(LayoutBoxNode()
.axis(Axis::kX)
.distribution(LayoutDistribution::kGravity)
.child(TextBoxNode()
.id("text_input")
.gravity(Gravity::kLeftRight)
.placeholder(xe::to_string(default_text_))
.min_width(150)
.autofocus(true)))
.child(LayoutBoxNode()
.distribution_position(
LayoutDistributionPosition::kRightBottom)
.child(ButtonNode("OK").id("ok_button"))
.child(ButtonNode("Cancel").id("cancel_button"))));
}
bool OnEvent(const el::Event& ev) override {
if (ev.special_key == el::SpecialKey::kEnter ||
(ev.target->id() == TBIDC("ok_button") &&
ev.type == el::EventType::kClick)) {
// Pressed enter or clicked OK
// Grab the text.
if (out_text_) {
*out_text_ =
xe::to_wstring(GetElementById<el::TextBox>("text_input")->text());
}
Die();
return true;
} else if (ev.target->id() == TBIDC("cancel_button") &&
ev.type == el::EventType::kClick) {
// Cancel.
Die();
return true;
}
return ModalWindow::OnEvent(ev);
}
std::wstring title_;
std::wstring description_;
std::wstring default_text_;
std::wstring* out_text_ = nullptr;
size_t max_length_ = 0;
};
// http://www.se7ensins.com/forums/threads/release-how-to-use-xshowkeyboardui-release.906568/
dword_result_t XamShowKeyboardUI(dword_t r3, dword_t flags,
lpwstring_t default_text, lpwstring_t title,
lpwstring_t description, lpwstring_t buffer,
dword_t buffer_length,
pointer_t<XAM_OVERLAPPED> overlapped) {
// Unknown parameters. I've only seen zero.
assert_zero(r3);
assert_zero(flags);
if (!buffer) {
return X_ERROR_INVALID_PARAMETER;
}
if (FLAGS_headless) {
// Redirect default_text back into the buffer.
std::memset(buffer, 0, buffer_length * 2);
if (default_text) {
xe::store_and_swap<std::wstring>(buffer, default_text.value());
}
if (overlapped) {
kernel_state()->CompleteOverlappedImmediate(overlapped, X_ERROR_SUCCESS);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_SUCCESS;
}
}
std::wstring out_text;
auto display_window = kernel_state()->emulator()->display_window();
xe::threading::Fence fence;
display_window->loop()->PostSynchronous([&]() {
auto root_element = display_window->root_element();
auto window = new KeyboardInputWindow(&fence);
window->Show(root_element, title ? title.value() : L"",
description ? description.value() : L"",
default_text ? default_text.value() : L"", &out_text,
buffer_length);
});
fence.Wait();
// Zero the output buffer.
std::memset(buffer, 0, buffer_length * 2);
// Truncate the string.
out_text = out_text.substr(0, buffer_length - 1);
xe::store_and_swap<std::wstring>(buffer, out_text);
if (overlapped) {
kernel_state()->CompleteOverlappedImmediate(overlapped, X_ERROR_SUCCESS);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_SUCCESS;
}
}
DECLARE_XAM_EXPORT(XamShowKeyboardUI, ExportTag::kImplemented);
dword_result_t XamShowDeviceSelectorUI(dword_t user_index, dword_t content_type,
dword_t content_flags,
qword_t total_requested,
lpdword_t device_id_ptr,
pointer_t<XAM_OVERLAPPED> overlapped) {
// NOTE: 0xF00D0000 magic from xam_content.cc
switch (content_type) {
case 1: // save game
*device_id_ptr = 0xF00D0000 | 0x0001;
break;
case 2: // marketplace
*device_id_ptr = 0xF00D0000 | 0x0002;
break;
case 3: // title/publisher update?
*device_id_ptr = 0xF00D0000 | 0x0003;
break;
}
if (overlapped) {
kernel_state()->CompleteOverlappedImmediate(overlapped, X_ERROR_SUCCESS);
return X_ERROR_IO_PENDING;
} else {
return X_ERROR_SUCCESS;
}
}
DECLARE_XAM_EXPORT(XamShowDeviceSelectorUI, ExportTag::kImplemented);
class DirtyDiscWindow : public el::ModalWindow {
public:
DirtyDiscWindow(xe::threading::Fence* fence)
: ModalWindow([fence]() { fence->Signal(); }) {}
~DirtyDiscWindow() override = default;
protected:
void BuildUI() override {
using namespace el::dsl;
set_text("Disc Read Error");
LoadNodeTree(
LayoutBoxNode()
.axis(Axis::kY)
.gravity(Gravity::kAll)
.position(LayoutPosition::kLeftTop)
.distribution(LayoutDistribution::kAvailable)
.distribution_position(LayoutDistributionPosition::kLeftTop)
.child(LabelNode(
"There's been an issue reading content from the game disc."))
.child(LabelNode(
"This is likely caused by bad or unimplemented file IO "
"calls."))
.child(LayoutBoxNode()
.distribution_position(
LayoutDistributionPosition::kRightBottom)
.child(ButtonNode("Exit").id("exit_button"))));
}
bool OnEvent(const el::Event& ev) override {
if (ev.target->id() == TBIDC("exit_button") &&
ev.type == el::EventType::kClick) {
Die();
return true;
}
return ModalWindow::OnEvent(ev);
}
};
SHIM_CALL XamShowDirtyDiscErrorUI_shim(PPCContext* ppc_context,
KernelState* kernel_state) {
uint32_t user_index = SHIM_GET_ARG_32(0);
XELOGD("XamShowDirtyDiscErrorUI(%d)", user_index);
if (FLAGS_headless) {
assert_always();
exit(1);
return;
}
auto display_window = kernel_state->emulator()->display_window();
xe::threading::Fence fence;
display_window->loop()->PostSynchronous([&]() {
auto root_element = display_window->root_element();
auto window = new DirtyDiscWindow(&fence);
window->Show(root_element);
});
fence.Wait();
// This is death, and should never return.
// TODO(benvanik): cleaner exit.
assert_always();
exit(1);
}
} // namespace kernel
} // namespace xe
void xe::kernel::xam::RegisterUIExports(
xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {
SHIM_SET_MAPPING("xam.xex", XamIsUIActive, state);
SHIM_SET_MAPPING("xam.xex", XamShowMessageBoxUI, state);
SHIM_SET_MAPPING("xam.xex", XamShowDirtyDiscErrorUI, state);
}
<|endoftext|> |
<commit_before>//
// renderer.cpp
// emptyExample
//
// Created by Mark van de Korput on 16-04-19.
//
//
#include "ofMain.h"
#include "renderer.hpp"
#include "xml_configs.hpp"
using namespace of2030;
using namespace of2030::effects;
SINGLETON_CLASS_IMPLEMENTATION_CODE(Renderer)
Renderer::Renderer() : fbo(NULL), player(NULL), client_id(""), bCallbacksRegistered(false){
}
Renderer::~Renderer(){
destroy();
}
void Renderer::setup(){
if(fbo == NULL)
fbo = &defaultFbo;
if(!fbo->isAllocated()){
if(client_id == "")
fbo->allocate(WIDTH, HEIGHT);
else
fbo->allocate(WIDTH, HEIGHT);
}
if(!player)
player = Player::instance();
if(!bCallbacksRegistered)
registerRealtimeEffectCallback();
}
void Renderer::destroy(){
if(bCallbacksRegistered)
registerRealtimeEffectCallback(false);
}
void Renderer::draw(){
Context context;
fillContextClientInfo(context);
fbo->begin();
ofBackground(0);
vector<effects::Effect*> effects = player->getActiveEffects();
for(auto & effect: effects){
fillEffectSetting(*effect, context.effect_setting);
fillScreenSetting(*effect, context.screen_setting);
effect->draw(context);
}
fbo->end();
ofSetColor(255);
fbo->draw(0,0);
}
void Renderer::registerRealtimeEffectCallback(bool reg){
if(reg){
ofAddListener(player->effect_manager.effectAddedEvent, this, &Renderer::onEffectAdded);
} else {
ofRemoveListener(player->effect_manager.effectAddedEvent, this, &Renderer::onEffectAdded);
}
bCallbacksRegistered = reg;
}
void Renderer::onEffectAdded(Effect &effect){
Context context;
fillContext(context, effect);
effect.setup(context);
}
void Renderer::fillContext(effects::Context &context, Effect &effect){
fillContextClientInfo(context);
fillEffectSetting(effect, context.effect_setting);
fillScreenSetting(effect, context.screen_setting);
}
void Renderer::fillContextClientInfo(effects::Context &context){
context.time = player->getTime();
context.fbo = fbo;
}
void Renderer::fillEffectSetting(effects::Effect &effect, XmlItemSetting &fxsetting){
XmlConfigs *fxs = XmlConfigs::instance();
// effect config
string query = effect.name;
XmlItemSetting *pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
// song specific effect config
query += "." + player->getSong();
pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
// song/clip specific effect config
query += "" + player->getClip();
pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
// trigger-specific config (has priority over song/clip-specific configs)
pSetting = fxs->getItem(effect.name+"."+effect.trigger);
if(pSetting)
fxsetting.merge(*pSetting);
// song/clip/trigger specific configs
query += "." + effect.trigger;
pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
}
void Renderer::fillScreenSetting(effects::Effect &effect, XmlItemSetting &setting){
XmlItemSetting *pSetting = XmlConfigs::screens()->getItem(client_id);
if(pSetting)
setting.merge(*pSetting);
}
<commit_msg>potential bugfix in renderer<commit_after>//
// renderer.cpp
// emptyExample
//
// Created by Mark van de Korput on 16-04-19.
//
//
#include "ofMain.h"
#include "renderer.hpp"
#include "xml_configs.hpp"
using namespace of2030;
using namespace of2030::effects;
SINGLETON_CLASS_IMPLEMENTATION_CODE(Renderer)
Renderer::Renderer() : fbo(NULL), player(NULL), client_id(""), bCallbacksRegistered(false){
}
Renderer::~Renderer(){
destroy();
}
void Renderer::setup(){
if(fbo == NULL)
fbo = &defaultFbo;
if(!fbo->isAllocated()){
if(client_id == "")
fbo->allocate(WIDTH, HEIGHT);
else
fbo->allocate(WIDTH, HEIGHT);
}
if(!player)
player = Player::instance();
if(!bCallbacksRegistered)
registerRealtimeEffectCallback();
}
void Renderer::destroy(){
if(bCallbacksRegistered)
registerRealtimeEffectCallback(false);
}
void Renderer::draw(){
Context context;
fillContextClientInfo(context);
fbo->begin();
ofBackground(0);
vector<effects::Effect*> effects = player->getActiveEffects();
for(auto effect: effects){
fillEffectSetting(*effect, context.effect_setting);
fillScreenSetting(*effect, context.screen_setting);
effect->draw(context);
}
fbo->end();
ofSetColor(255);
fbo->draw(0,0);
}
void Renderer::registerRealtimeEffectCallback(bool reg){
if(reg){
ofAddListener(player->effect_manager.effectAddedEvent, this, &Renderer::onEffectAdded);
} else {
ofRemoveListener(player->effect_manager.effectAddedEvent, this, &Renderer::onEffectAdded);
}
bCallbacksRegistered = reg;
}
void Renderer::onEffectAdded(Effect &effect){
Context context;
fillContext(context, effect);
effect.setup(context);
}
void Renderer::fillContext(effects::Context &context, Effect &effect){
fillContextClientInfo(context);
fillEffectSetting(effect, context.effect_setting);
fillScreenSetting(effect, context.screen_setting);
}
void Renderer::fillContextClientInfo(effects::Context &context){
context.time = player->getTime();
context.fbo = fbo;
}
void Renderer::fillEffectSetting(effects::Effect &effect, XmlItemSetting &fxsetting){
XmlConfigs *fxs = XmlConfigs::instance();
// effect config
string query = effect.name;
XmlItemSetting *pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
// song specific effect config
query += "." + player->getSong();
pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
// song/clip specific effect config
query += "" + player->getClip();
pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
// trigger-specific config (has priority over song/clip-specific configs)
pSetting = fxs->getItem(effect.name+"."+effect.trigger);
if(pSetting)
fxsetting.merge(*pSetting);
// song/clip/trigger specific configs
query += "." + effect.trigger;
pSetting = fxs->getItem(query);
if(pSetting)
fxsetting.merge(*pSetting);
}
void Renderer::fillScreenSetting(effects::Effect &effect, XmlItemSetting &setting){
XmlItemSetting *pSetting = XmlConfigs::screens()->getItem(client_id);
if(pSetting)
setting.merge(*pSetting);
}
<|endoftext|> |
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "SerialUtils.hh"
#include "StringUtils.hh"
#include <errno.h>
#include <rpc/types.h>
#include <rpc/xdr.h>
#include <string>
#include <string.h>
using std::string;
namespace HadoopUtils {
Error::Error(const std::string& msg): error(msg) {
}
Error::Error(const std::string& msg,
const std::string& file, int line,
const std::string& function) {
error = msg + " at " + file + ":" + toString(line) +
" in " + function;
}
const std::string& Error::getMessage() const {
return error;
}
FileInStream::FileInStream()
{
mFile = NULL;
isOwned = false;
}
bool FileInStream::open(const std::string& name)
{
mFile = fopen(name.c_str(), "rb");
isOwned = true;
return (mFile != NULL);
}
bool FileInStream::open(FILE* file)
{
mFile = file;
isOwned = false;
return (mFile != NULL);
}
void FileInStream::read(void *buf, size_t len)
{
size_t result = fread(buf, len, 1, mFile);
if (result == 0) {
if (feof(mFile)) {
HADOOP_ASSERT(false, "end of file");
} else {
HADOOP_ASSERT(false, string("read error on file: ") + strerror(errno));
}
}
}
bool FileInStream::skip(size_t nbytes)
{
return (0==fseek(mFile, nbytes, SEEK_CUR));
}
bool FileInStream::close()
{
int ret = 0;
if (mFile != NULL && isOwned) {
ret = fclose(mFile);
}
mFile = NULL;
return (ret==0);
}
FileInStream::~FileInStream()
{
if (mFile != NULL) {
close();
}
}
FileOutStream::FileOutStream()
{
mFile = NULL;
isOwned = false;
}
bool FileOutStream::open(const std::string& name, bool overwrite)
{
if (!overwrite) {
mFile = fopen(name.c_str(), "rb");
if (mFile != NULL) {
fclose(mFile);
return false;
}
}
mFile = fopen(name.c_str(), "wb");
isOwned = true;
return (mFile != NULL);
}
bool FileOutStream::open(FILE* file)
{
mFile = file;
isOwned = false;
return (mFile != NULL);
}
void FileOutStream::write(const void* buf, size_t len)
{
size_t result = fwrite(buf, len, 1, mFile);
HADOOP_ASSERT(result == 1,
string("write error to file: ") + strerror(errno));
}
bool FileOutStream::advance(size_t nbytes)
{
return (0==fseek(mFile, nbytes, SEEK_CUR));
}
bool FileOutStream::close()
{
int ret = 0;
if (mFile != NULL && isOwned) {
ret = fclose(mFile);
}
mFile = NULL;
return (ret == 0);
}
void FileOutStream::flush()
{
fflush(mFile);
}
FileOutStream::~FileOutStream()
{
if (mFile != NULL) {
close();
}
}
StringInStream::StringInStream(const std::string& str): buffer(str) {
itr = buffer.begin();
}
void StringInStream::read(void *buf, size_t buflen) {
size_t bytes = 0;
char* output = (char*) buf;
std::string::const_iterator end = buffer.end();
while (bytes < buflen) {
output[bytes++] = *itr;
++itr;
if (itr == end) {
break;
}
}
HADOOP_ASSERT(bytes == buflen, "unexpected end of string reached");
}
BufferInStream::BufferInStream(void) {}
bool BufferInStream::open(const char* buf, size_t buflen) {
buffer = buf;
size = buflen;
itr = buffer;
return true;
}
void BufferInStream::read(void *buf, size_t buflen) {
size_t bytes = 0;
char* output = (char*) buf;
const char* end = buffer + size;
while (bytes < buflen) {
output[bytes++] = *itr;
++itr;
if (itr == end) {
break;
}
}
HADOOP_ASSERT(bytes == buflen, "unexpected end of string reached");
}
void serializeInt(int32_t t, OutStream& stream) {
serializeLong(t, stream);
}
void serializeLong(int64_t t, OutStream& stream)
{
if (t >= -112 && t <= 127) {
int8_t b = t;
stream.write(&b, 1);
return;
}
int8_t len = -112;
if (t < 0) {
t ^= -1ll; // reset the sign bit
len = -120;
}
uint64_t tmp = t;
while (tmp != 0) {
tmp = tmp >> 8;
len--;
}
stream.write(&len, 1);
len = (len < -120) ? -(len + 120) : -(len + 112);
for (uint32_t idx = len; idx != 0; idx--) {
uint32_t shiftbits = (idx - 1) * 8;
uint64_t mask = 0xFFll << shiftbits;
uint8_t b = (t & mask) >> shiftbits;
stream.write(&b, 1);
}
}
int32_t deserializeInt(InStream& stream) {
return deserializeLong(stream);
}
int64_t deserializeLong(InStream& stream)
{
int8_t b;
stream.read(&b, 1);
if (b >= -112) {
return b;
}
bool negative;
int len;
if (b < -120) {
negative = true;
len = -120 - b;
} else {
negative = false;
len = -112 - b;
}
uint8_t barr[len];
stream.read(barr, len);
int64_t t = 0;
for (int idx = 0; idx < len; idx++) {
t = t << 8;
t |= (barr[idx] & 0xFF);
}
if (negative) {
t ^= -1ll;
}
return t;
}
void serializeFloat(float t, OutStream& stream)
{
char buf[sizeof(float)];
XDR xdrs;
xdrmem_create(&xdrs, buf, sizeof(float), XDR_ENCODE);
xdr_float(&xdrs, &t);
stream.write(buf, sizeof(float));
}
void deserializeFloat(float& t, InStream& stream)
{
char buf[sizeof(float)];
stream.read(buf, sizeof(float));
XDR xdrs;
xdrmem_create(&xdrs, buf, sizeof(float), XDR_DECODE);
xdr_float(&xdrs, &t);
}
void serializeString(const std::string& t, OutStream& stream)
{
serializeInt(t.length(), stream);
if (t.length() > 0) {
stream.write(t.data(), t.length());
}
}
void serializeBuffer(const char *buf, std::size_t len, OutStream& stream)
{
serializeInt(len, stream);
if (len > 0) {
stream.write(buf, len);
}
}
void deserializeString(std::string& t, InStream& stream)
{
int32_t len = deserializeInt(stream);
if (len > 0) {
// resize the string to the right length
t.resize(len);
// read into the string in 64k chunks
const int bufSize = 65536;
int offset = 0;
char buf[bufSize];
while (len > 0) {
int chunkLength = len > bufSize ? bufSize : len;
stream.read(buf, chunkLength);
t.replace(offset, chunkLength, buf, chunkLength);
offset += chunkLength;
len -= chunkLength;
}
} else {
t.clear();
}
}
}
<commit_msg>Closing an FileOutStream now implies a flush().<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "SerialUtils.hh"
#include "StringUtils.hh"
#include <errno.h>
#include <rpc/types.h>
#include <rpc/xdr.h>
#include <string>
#include <string.h>
using std::string;
namespace HadoopUtils {
Error::Error(const std::string& msg): error(msg) {
}
Error::Error(const std::string& msg,
const std::string& file, int line,
const std::string& function) {
error = msg + " at " + file + ":" + toString(line) +
" in " + function;
}
const std::string& Error::getMessage() const {
return error;
}
FileInStream::FileInStream()
{
mFile = NULL;
isOwned = false;
}
bool FileInStream::open(const std::string& name)
{
mFile = fopen(name.c_str(), "rb");
isOwned = true;
return (mFile != NULL);
}
bool FileInStream::open(FILE* file)
{
mFile = file;
isOwned = false;
return (mFile != NULL);
}
void FileInStream::read(void *buf, size_t len)
{
size_t result = fread(buf, len, 1, mFile);
if (result == 0) {
if (feof(mFile)) {
HADOOP_ASSERT(false, "end of file");
} else {
HADOOP_ASSERT(false, string("read error on file: ") + strerror(errno));
}
}
}
bool FileInStream::skip(size_t nbytes)
{
return (0==fseek(mFile, nbytes, SEEK_CUR));
}
bool FileInStream::close()
{
int ret = 0;
if (mFile != NULL && isOwned) {
ret = fclose(mFile);
}
mFile = NULL;
return (ret==0);
}
FileInStream::~FileInStream()
{
if (mFile != NULL) {
close();
}
}
FileOutStream::FileOutStream()
{
mFile = NULL;
isOwned = false;
}
bool FileOutStream::open(const std::string& name, bool overwrite)
{
if (!overwrite) {
mFile = fopen(name.c_str(), "rb");
if (mFile != NULL) {
fclose(mFile);
return false;
}
}
mFile = fopen(name.c_str(), "wb");
isOwned = true;
return (mFile != NULL);
}
bool FileOutStream::open(FILE* file)
{
mFile = file;
isOwned = false;
return (mFile != NULL);
}
void FileOutStream::write(const void* buf, size_t len)
{
size_t result = fwrite(buf, len, 1, mFile);
HADOOP_ASSERT(result == 1,
string("write error to file: ") + strerror(errno));
}
bool FileOutStream::advance(size_t nbytes)
{
return (0==fseek(mFile, nbytes, SEEK_CUR));
}
bool FileOutStream::close()
{
int ret = 0;
flush();
if (mFile != NULL && isOwned) {
ret = fclose(mFile);
}
mFile = NULL;
return (ret == 0);
}
void FileOutStream::flush()
{
fflush(mFile);
}
FileOutStream::~FileOutStream()
{
if (mFile != NULL) {
close();
}
}
StringInStream::StringInStream(const std::string& str): buffer(str) {
itr = buffer.begin();
}
void StringInStream::read(void *buf, size_t buflen) {
size_t bytes = 0;
char* output = (char*) buf;
std::string::const_iterator end = buffer.end();
while (bytes < buflen) {
output[bytes++] = *itr;
++itr;
if (itr == end) {
break;
}
}
HADOOP_ASSERT(bytes == buflen, "unexpected end of string reached");
}
BufferInStream::BufferInStream(void) {}
bool BufferInStream::open(const char* buf, size_t buflen) {
buffer = buf;
size = buflen;
itr = buffer;
return true;
}
void BufferInStream::read(void *buf, size_t buflen) {
size_t bytes = 0;
char* output = (char*) buf;
const char* end = buffer + size;
while (bytes < buflen) {
output[bytes++] = *itr;
++itr;
if (itr == end) {
break;
}
}
HADOOP_ASSERT(bytes == buflen, "unexpected end of string reached");
}
void serializeInt(int32_t t, OutStream& stream) {
serializeLong(t, stream);
}
void serializeLong(int64_t t, OutStream& stream)
{
if (t >= -112 && t <= 127) {
int8_t b = t;
stream.write(&b, 1);
return;
}
int8_t len = -112;
if (t < 0) {
t ^= -1ll; // reset the sign bit
len = -120;
}
uint64_t tmp = t;
while (tmp != 0) {
tmp = tmp >> 8;
len--;
}
stream.write(&len, 1);
len = (len < -120) ? -(len + 120) : -(len + 112);
for (uint32_t idx = len; idx != 0; idx--) {
uint32_t shiftbits = (idx - 1) * 8;
uint64_t mask = 0xFFll << shiftbits;
uint8_t b = (t & mask) >> shiftbits;
stream.write(&b, 1);
}
}
int32_t deserializeInt(InStream& stream) {
return deserializeLong(stream);
}
int64_t deserializeLong(InStream& stream)
{
int8_t b;
stream.read(&b, 1);
if (b >= -112) {
return b;
}
bool negative;
int len;
if (b < -120) {
negative = true;
len = -120 - b;
} else {
negative = false;
len = -112 - b;
}
uint8_t barr[len];
stream.read(barr, len);
int64_t t = 0;
for (int idx = 0; idx < len; idx++) {
t = t << 8;
t |= (barr[idx] & 0xFF);
}
if (negative) {
t ^= -1ll;
}
return t;
}
void serializeFloat(float t, OutStream& stream)
{
char buf[sizeof(float)];
XDR xdrs;
xdrmem_create(&xdrs, buf, sizeof(float), XDR_ENCODE);
xdr_float(&xdrs, &t);
stream.write(buf, sizeof(float));
}
void deserializeFloat(float& t, InStream& stream)
{
char buf[sizeof(float)];
stream.read(buf, sizeof(float));
XDR xdrs;
xdrmem_create(&xdrs, buf, sizeof(float), XDR_DECODE);
xdr_float(&xdrs, &t);
}
void serializeString(const std::string& t, OutStream& stream)
{
serializeInt(t.length(), stream);
if (t.length() > 0) {
stream.write(t.data(), t.length());
}
}
void serializeBuffer(const char *buf, std::size_t len, OutStream& stream)
{
serializeInt(len, stream);
if (len > 0) {
stream.write(buf, len);
}
}
void deserializeString(std::string& t, InStream& stream)
{
int32_t len = deserializeInt(stream);
if (len > 0) {
// resize the string to the right length
t.resize(len);
// read into the string in 64k chunks
const int bufSize = 65536;
int offset = 0;
char buf[bufSize];
while (len > 0) {
int chunkLength = len > bufSize ? bufSize : len;
stream.read(buf, chunkLength);
t.replace(offset, chunkLength, buf, chunkLength);
offset += chunkLength;
len -= chunkLength;
}
} else {
t.clear();
}
}
}
<|endoftext|> |
<commit_before>#include <ros/console.h>
#include <string>
#include <teraranger_array/RangeArray.h>
#include <teraranger_array/teraranger_evo.h>
#include <teraranger_array/helper_lib.h>
namespace teraranger_array
{
TerarangerHubEvo::TerarangerHubEvo()
{
// Get parameters and namespace
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_,
std::string("/dev/ttyACM0"));
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
if (ns_ != "" && ns_[0] == '/')
{ // Remove first backslash if needed
ns_.erase(0,1);
}
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Publishers
range_publisher_ = nh_.advertise<teraranger_array::RangeArray>("teraranger_evo", 8);
// Serial Port init
serial_port_.setPort(portname_);
serial_port_.setBaudrate(115200);
serial_port_.setParity(serial::parity_none);
serial_port_.setStopbits(serial::stopbits_one);
serial_port_.setBytesize(serial::eightbits);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
serial_port_.setTimeout(to);
serial_port_.open();
if(!serial_port_.isOpen())
{
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:",
ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(),
portname_.c_str());
//Initialize local parameters and measurement array
field_of_view = 0.03491;
max_range = 14.0;
min_range = 0.2;
number_of_sensor = 8;
frame_id = "base_range_";
// Initialize rangeArray
for (size_t i=0; i < number_of_sensor; i++)
{
sensor_msgs::Range range;
range.field_of_view = field_of_view;
range.max_range = max_range;
range.min_range = min_range;
range.radiation_type = sensor_msgs::Range::INFRARED;
range.range = 0.0;
// set the right range frame depending of the namespace
if (ns_ == "")
{
range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i);
}
else
{
range.header.frame_id = ns_ + '_'+ frame_id + boost::lexical_cast<std::string>(i);
}
measure.ranges.push_back(range);
}
// set the right RangeArray frame depending of the namespace
if (ns_ == "")
{
measure.header.frame_id = "base_hub";
}
else
{
measure.header.frame_id = "base_" + ns_;// Remove first slash
}
// This line is needed to start measurements on the hub
setMode(BINARY_MODE, 4);
setMode(TOWER_MODE, 4);
setMode(RATE_ASAP, 5);
setMode(ENABLE_CMD, 5);
setMode(IMU_EULER,4);
imu_status = euler;
// Dynamic reconfigure
dyn_param_server_callback_function_ =
boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubEvo::~TerarangerHubEvo() {}
void TerarangerHubEvo::setMode(const char *c, int length)
{
serial_port_.write((uint8_t*)c, length);
serial_port_.flushOutput();
}
void TerarangerHubEvo::dynParamCallback(
const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level)
{
ROS_INFO("Dynamic reconfigure call");
// Set the mode dynamically
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary)
{
setMode(BINARY_MODE, 4);
}
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text)
{
setMode(TEXT_MODE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Long_range)
{
setMode(LONG_RANGE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Short_range)
{
setMode(SHORT_RANGE, 4);
}
// Set the rate dynamically
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP)
{
setMode(RATE_ASAP, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700)
{
setMode(RATE_700, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600)
{
setMode(RATE_600, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500)
{
setMode(RATE_500, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250)
{
setMode(RATE_250, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100)
{
setMode(RATE_100, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50)
{
setMode(RATE_50, 5);
}
// Set the IMU mode dynamically
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_OFF)
{
setMode(IMU_OFF,4);
imu_status = off;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUAT)
{
setMode(IMU_QUAT,4);
imu_status = quat;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_EULER)
{
setMode(IMU_EULER,4);
imu_status = euler;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUATLIN)
{
setMode(IMU_QUATLIN,4);
imu_status = quatlin;
}
//Set the sequence mode dynamically
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Crosstalk)
{
setMode(CROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Non_crosstalk)
{
setMode(NONCROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Tower_mode)
{
setMode(TOWER_MODE,4);
}
//Set VCP state dynamically
if(config.Enable_VCP)
{
setMode(ENABLE_CMD, 5);
}
else
{
setMode(DISABLE_CMD, 5);
}
}
void TerarangerHubEvo::processRangeFrame(uint8_t* input_buffer, int seq_ctr)
{
//Processing full range frame
uint8_t crc = HelperLib::crc8(input_buffer, 19);
if (crc == input_buffer[RANGE_CRC_POS])
{
//ROS_DEBUG("Frame of size %d : %s ", buffer_ctr, input_buffer);
for (size_t i=0; i < measure.ranges.size(); i++)
{
measure.ranges.at(i).header.stamp = ros::Time::now();
measure.ranges.at(i).header.seq = seq_ctr++;
// Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8
char c1 = input_buffer[2 * (i + 1)];
char c2 = input_buffer[2 * (i + 1) + 1];
ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF));
int16_t current_range = (c1 & 0x0FF) << 8;
current_range |= (c2 & 0x0FF);
float float_range = (float)current_range;
ROS_DEBUG("Value int : %d | float : %f", current_range, float_range);
if (current_range <= 1 || current_range == 255)
{
float_range = -1.0;
}
else
{
float_range = float_range * 0.001;
}
measure.ranges.at(i).range = float_range;
}
measure.header.seq = (int) seq_ctr / 8;
measure.header.stamp = ros::Time::now();
range_publisher_.publish(measure);
}
else
{
ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str());
}
}
void TerarangerHubEvo::processImuFrame(uint8_t* input_buffer, int seq_ctr)
{
//TODO
}
void TerarangerHubEvo::serialDataCallback(uint8_t single_character)
{
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int seq_ctr = 0;
ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character);
if (buffer_ctr == 0)
{
if (single_character == 'T' || single_character == 'I')
{
// Waiting for T or an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
else if (buffer_ctr == 1)
{
if (single_character == 'H' || single_character == 'M')
{
// Waiting for H after a T or an M after an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
if (buffer_ctr > 1)
{
if (input_buffer[0] == 'T')// Parsing ranges
{
// Gathering after-header range data
if (buffer_ctr < RANGES_FRAME_LENGTH)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == RANGES_FRAME_LENGTH)
{
processRangeFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > RANGES_FRAME_LENGTH)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
else if (input_buffer[0] == 'I')// Parsing Imu
{
// ROS_INFO("%d", imu_status);
// Gathering after-header imu data
if (buffer_ctr < IMU_EULER_FRAME_LENGHT)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == IMU_EULER_FRAME_LENGHT)
{
processImuFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > IMU_EULER_FRAME_LENGHT)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
// resetting buffer and ctr
buffer_ctr = 0;
bzero(&input_buffer, BUFFER_SIZE);
// Appending current char to hook next frame
input_buffer[buffer_ctr++] = single_character;
}
}
void TerarangerHubEvo::spin()
{
static uint8_t buffer[1];
while(ros::ok())
{
serial_port_.read(buffer, 1);
serialDataCallback(buffer[0]);
ros::spinOnce();
}
setMode(DISABLE_CMD, 5);
}
}// end of namespace
int main(int argc, char **argv) {
ros::init(argc, argv, "teraranger_hub_evo");
teraranger_array::TerarangerHubEvo node;
node.spin();
return 0;
}
<commit_msg>Remove/add comments<commit_after>#include <ros/console.h>
#include <string>
#include <teraranger_array/RangeArray.h>
#include <teraranger_array/teraranger_evo.h>
#include <teraranger_array/helper_lib.h>
namespace teraranger_array
{
TerarangerHubEvo::TerarangerHubEvo()
{
// Get parameters and namespace
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("portname", portname_,
std::string("/dev/ttyACM0"));
ns_ = ros::this_node::getNamespace();
ns_ = ros::names::clean(ns_);
if (ns_ != "" && ns_[0] == '/')
{ // Remove first backslash if needed
ns_.erase(0,1);
}
ROS_INFO("node namespace: [%s]", ns_.c_str());
// Publishers
range_publisher_ = nh_.advertise<teraranger_array::RangeArray>("teraranger_evo", 8);
// Serial Port init
serial_port_.setPort(portname_);
serial_port_.setBaudrate(115200);
serial_port_.setParity(serial::parity_none);
serial_port_.setStopbits(serial::stopbits_one);
serial_port_.setBytesize(serial::eightbits);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
serial_port_.setTimeout(to);
serial_port_.open();
if(!serial_port_.isOpen())
{
ROS_ERROR("Could not open : %s ", portname_.c_str());
ros::shutdown();
return;
}
// Output loaded parameters to console for double checking
ROS_INFO("[%s] is up and running with the following parameters:",
ros::this_node::getName().c_str());
ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(),
portname_.c_str());
//Initialize local parameters and measurement array
field_of_view = 0.03491;
max_range = 14.0;
min_range = 0.2;
number_of_sensor = 8;
frame_id = "base_range_";
// Initialize rangeArray
for (size_t i=0; i < number_of_sensor; i++)
{
sensor_msgs::Range range;
range.field_of_view = field_of_view;
range.max_range = max_range;
range.min_range = min_range;
range.radiation_type = sensor_msgs::Range::INFRARED;
range.range = 0.0;
// set the right range frame depending of the namespace
if (ns_ == "")
{
range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i);
}
else
{
range.header.frame_id = ns_ + '_'+ frame_id + boost::lexical_cast<std::string>(i);
}
measure.ranges.push_back(range);
}
// set the right RangeArray frame depending of the namespace
if (ns_ == "")
{
measure.header.frame_id = "base_hub";
}
else
{
measure.header.frame_id = "base_" + ns_;// Remove first slash
}
// This line is needed to start measurements on the hub
setMode(BINARY_MODE, 4);
setMode(TOWER_MODE, 4);
setMode(RATE_ASAP, 5);
setMode(ENABLE_CMD, 5);
setMode(IMU_EULER,4);
imu_status = euler;
// Dynamic reconfigure
dyn_param_server_callback_function_ =
boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2);
dyn_param_server_.setCallback(dyn_param_server_callback_function_);
}
TerarangerHubEvo::~TerarangerHubEvo() {}
void TerarangerHubEvo::setMode(const char *c, int length)
{
serial_port_.write((uint8_t*)c, length);
serial_port_.flushOutput();
}
void TerarangerHubEvo::dynParamCallback(
const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level)
{
ROS_INFO("Dynamic reconfigure call");
// Set the mode dynamically
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary)
{
setMode(BINARY_MODE, 4);
}
if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text)
{
setMode(TEXT_MODE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Long_range)
{
setMode(LONG_RANGE, 4);
}
if (config.Range_mode == teraranger_evo_cfg::TerarangerHubEvo_Short_range)
{
setMode(SHORT_RANGE, 4);
}
// Set the rate dynamically
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP)
{
setMode(RATE_ASAP, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700)
{
setMode(RATE_700, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600)
{
setMode(RATE_600, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500)
{
setMode(RATE_500, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250)
{
setMode(RATE_250, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100)
{
setMode(RATE_100, 5);
}
if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50)
{
setMode(RATE_50, 5);
}
// Set the IMU mode dynamically
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_OFF)
{
setMode(IMU_OFF,4);
imu_status = off;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUAT)
{
setMode(IMU_QUAT,4);
imu_status = quat;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_EULER)
{
setMode(IMU_EULER,4);
imu_status = euler;
}
if (config.IMU_mode == teraranger_evo_cfg::TerarangerHubEvo_QUATLIN)
{
setMode(IMU_QUATLIN,4);
imu_status = quatlin;
}
//Set the sequence mode dynamically
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Crosstalk)
{
setMode(CROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Non_crosstalk)
{
setMode(NONCROSSTALK_MODE,4);
}
if(config.Sequence_mode == teraranger_evo_cfg::TerarangerHubEvo_Tower_mode)
{
setMode(TOWER_MODE,4);
}
//Set VCP state dynamically
if(config.Enable_VCP)
{
setMode(ENABLE_CMD, 5);
}
else
{
setMode(DISABLE_CMD, 5);
}
}
void TerarangerHubEvo::processRangeFrame(uint8_t* input_buffer, int seq_ctr)
{
//Processing full range frame
uint8_t crc = HelperLib::crc8(input_buffer, 19);
if (crc == input_buffer[RANGE_CRC_POS])
{
for (size_t i=0; i < measure.ranges.size(); i++)
{
measure.ranges.at(i).header.stamp = ros::Time::now();
measure.ranges.at(i).header.seq = seq_ctr++;
// Convert bytes to range
// Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8
char c1 = input_buffer[2 * (i + 1)];
char c2 = input_buffer[2 * (i + 1) + 1];
ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF));
int16_t current_range = (c1 & 0x0FF) << 8;
current_range |= (c2 & 0x0FF);
float float_range = (float)current_range;
ROS_DEBUG("Value int : %d | float : %f", current_range, float_range);
if (current_range <= 1 || current_range == 255)
{
float_range = -1.0;
}
else
{
float_range = float_range * 0.001;
}
measure.ranges.at(i).range = float_range;
}
measure.header.seq = (int) seq_ctr / 8;
measure.header.stamp = ros::Time::now();
range_publisher_.publish(measure);
}
else
{
ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str());
}
}
void TerarangerHubEvo::processImuFrame(uint8_t* input_buffer, int seq_ctr)
{
//TODO
}
void TerarangerHubEvo::serialDataCallback(uint8_t single_character)
{
static uint8_t input_buffer[BUFFER_SIZE];
static int buffer_ctr = 0;
static int seq_ctr = 0;
ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character);
if (buffer_ctr == 0)
{
if (single_character == 'T' || single_character == 'I')
{
// Waiting for T or an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
else if (buffer_ctr == 1)
{
if (single_character == 'H' || single_character == 'M')
{
// Waiting for H after a T or an M after an I
input_buffer[buffer_ctr++] = single_character;
return;
}
}
if (buffer_ctr > 1)
{
if (input_buffer[0] == 'T')// Parsing ranges
{
// Gathering after-header range data
if (buffer_ctr < RANGES_FRAME_LENGTH)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == RANGES_FRAME_LENGTH)
{
processRangeFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > RANGES_FRAME_LENGTH)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
else if (input_buffer[0] == 'I')// Parsing Imu
{
// ROS_INFO("%d", imu_status);
// Gathering after-header imu data
if (buffer_ctr < IMU_EULER_FRAME_LENGHT)
{
input_buffer[buffer_ctr++] = single_character;
return;
}
else if (buffer_ctr == IMU_EULER_FRAME_LENGHT)
{
processImuFrame(input_buffer, seq_ctr);
}
else if (buffer_ctr > IMU_EULER_FRAME_LENGHT)
{
ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without "
"evaluating data",
ros::this_node::getName().c_str());
}
}
// resetting buffer and ctr
buffer_ctr = 0;
bzero(&input_buffer, BUFFER_SIZE);
// Appending current char to hook next frame
input_buffer[buffer_ctr++] = single_character;
}
}
void TerarangerHubEvo::spin()
{
static uint8_t buffer[1];
while(ros::ok())
{
serial_port_.read(buffer, 1);
serialDataCallback(buffer[0]);
ros::spinOnce();
}
setMode(DISABLE_CMD, 5);
}
}// end of namespace
int main(int argc, char **argv) {
ros::init(argc, argv, "teraranger_hub_evo");
teraranger_array::TerarangerHubEvo node;
node.spin();
return 0;
}
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include "base58.h"
#include "util.h"
#include "bitcoinrpc.h"
using namespace std;
using namespace json_spirit;
BOOST_AUTO_TEST_SUITE(rpc_tests)
static Array
createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
{
Array result;
result.push_back(nRequired);
Array addresses;
if (address1) addresses.push_back(address1);
if (address2) addresses.push_back(address2);
result.push_back(addresses);
return result;
}
// This can be removed this when addmultisigaddress is enabled on main net:
struct TestNetFixture
{
TestNetFixture() { fTestNet = true; }
~TestNetFixture() { fTestNet = false; }
};
BOOST_FIXTURE_TEST_CASE(rpc_addmultisig, TestNetFixture)
{
rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor;
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex+sizeof(address1Hex)-2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex+1, address1Hex+sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>No need for test fixture now that multisig is enabled on main network.<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include "base58.h"
#include "util.h"
#include "bitcoinrpc.h"
using namespace std;
using namespace json_spirit;
BOOST_AUTO_TEST_SUITE(rpc_tests)
static Array
createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
{
Array result;
result.push_back(nRequired);
Array addresses;
if (address1) addresses.push_back(address1);
if (address2) addresses.push_back(address2);
result.push_back(addresses);
return result;
}
BOOST_AUTO_TEST_CASE(rpc_addmultisig)
{
rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor;
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex+sizeof(address1Hex)-2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex+1, address1Hex+sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include "base58.h"
#include "util.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
using namespace std;
using namespace json_spirit;
typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
extern map<string, rpcfn_type> mapCallTable;
BOOST_AUTO_TEST_SUITE(rpc_tests)
static Array
createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
{
Array result;
result.push_back(nRequired);
Array addresses;
if (address1) addresses.push_back(address1);
if (address2) addresses.push_back(address1);
result.push_back(addresses);
return result;
}
// This can be removed this when addmultisigaddress is enabled on main net:
struct TestNetFixture
{
TestNetFixture() { fTestNet = true; }
~TestNetFixture() { fTestNet = false; }
};
BOOST_FIXTURE_TEST_CASE(rpc_addmultisig, TestNetFixture)
{
rpcfn_type addmultisig = mapCallTable["addmultisigaddress"];
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex+sizeof(address1Hex)-2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex+1, address1Hex+sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Wrong address added to collection in test<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include "base58.h"
#include "util.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
using namespace std;
using namespace json_spirit;
typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
extern map<string, rpcfn_type> mapCallTable;
BOOST_AUTO_TEST_SUITE(rpc_tests)
static Array
createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
{
Array result;
result.push_back(nRequired);
Array addresses;
if (address1) addresses.push_back(address1);
if (address2) addresses.push_back(address2);
result.push_back(addresses);
return result;
}
// This can be removed this when addmultisigaddress is enabled on main net:
struct TestNetFixture
{
TestNetFixture() { fTestNet = true; }
~TestNetFixture() { fTestNet = false; }
};
BOOST_FIXTURE_TEST_CASE(rpc_addmultisig, TestNetFixture)
{
rpcfn_type addmultisig = mapCallTable["addmultisigaddress"];
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex+sizeof(address1Hex)-2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex+1, address1Hex+sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <yuni/yuni.h>
#include <yuni/string.h>
#include <yuni/core/system/main.h>
#include <yuni/io/file.h>
#include <nany/nany.h>
#include <memory>
#include <iostream>
#include <cassert>
#include <limits.h>
using namespace Yuni;
static const char* argv0 = "";
struct Options
{
//! Verbose mode
bool verbose = false;
//! Maximum number of jobs
uint32_t jobs = 1;
};
static int printUsage(const char* const argv0)
{
std::cout
<< "Usage: " << argv0 << " [options] file...\n"
<< "Options:\n"
<< " --bugreport Display some useful information to report a bug\n"
<< " (https://github.com/nany-lang/nany/issues/new)\n"
<< " --help, -h Display this information\n"
<< " --version, -v Print the version\n\n";
return EXIT_SUCCESS;
}
static int printBugReportInfo()
{
auto* text = nany_get_info_for_bugreport();
if (text)
{
std::cout << text;
::free(text);
return 0;
}
return EXIT_FAILURE;
}
static int printVersion()
{
std::cout << nany_version() << '\n';
return EXIT_SUCCESS;
}
static int unknownOption(const AnyString& name)
{
std::cerr << argv0 << ": unknown option '" << name << "'\n";
return EXIT_FAILURE;
}
static inline int execute(int argc, char** argv, const Options& options)
{
assert(argc >= 1);
String scriptfile;
IO::Canonicalize(scriptfile, argv[0]);
// nany context
nycontext_t ctx;
nany_initialize(&ctx, nullptr, nullptr);
// for concurrent build
if (options.jobs > 1)
ctx.mt.queueservice = nany_queueservice_create();
nany_source_add_from_file_n(&ctx, scriptfile.c_str(), scriptfile.size());
// building
bool buildstatus;
{
nyreport_t* report = nullptr;
buildstatus = (nany_build(&ctx, &report) == nytrue);
// report printing
// if an error has occured or if in verbose mode
if (YUNI_UNLIKELY((not buildstatus) or options.verbose))
(buildstatus ? nany_report_print_stdout : nany_report_print_stderr)(report);
nany_report_unref(&report);
}
// executing the program
int exitstatus = 66;
if (buildstatus)
{
if (argc == 1)
{
const char* nargv[] = { scriptfile.c_str(), nullptr };
exitstatus = nany_run_main(&ctx, 1, nargv);
}
else
{
auto** nargv = (const char**)::malloc(((size_t) argc + 1) * sizeof(const char**));
if (nargv)
{
for (int i = 1; i < argc; ++i)
nargv[i] = argv[i];
nargv[0] = scriptfile.c_str();
nargv[argc] = nullptr;
exitstatus = nany_run_main(&ctx, argc, nargv);
free(nargv);
}
}
}
nany_uninitialize(&ctx);
return exitstatus;
}
YUNI_MAIN_CONSOLE(argc, argv)
{
argv0 = argv[0];
if (YUNI_UNLIKELY(argc <= 1))
{
std::cerr << argv0 << ": no input script file\n";
return EXIT_FAILURE;
}
try
{
Options options;
int firstarg = -1;
for (int i = 1; i < argc; ++i)
{
const char* const carg = argv[i];
if (carg[0] == '-')
{
if (carg[1] == '-')
{
if (carg[2] != '\0') // to handle '--' option
{
AnyString arg{carg};
if (arg == "--help")
return printUsage(argv[0]);
if (arg == "--version")
return printVersion();
if (arg == "--bugreport")
return printBugReportInfo();
if (arg == "--verbose")
{
options.verbose = true;
continue;
}
return unknownOption(arg);
}
else
{
firstarg = i + 1;
break; // nothing must interpreted after '--'
}
}
else
{
AnyString arg{carg};
if (arg == "-h")
return printUsage(argv[0]);
if (arg == "-v")
return printVersion();
return unknownOption(arg);
}
}
firstarg = i;
break;
}
//
// -- execute the script
//
return execute(argc - firstarg, argv + firstarg, options);
}
catch (std::bad_alloc&)
{
std::cerr << '\n' << argv0 << ": error: failed to allocate memory\n";
}
catch (...)
{
std::cerr << '\n' << argv0 << ": error: unhandled exception\n";
}
return EXIT_FAILURE;
}
<commit_msg>added env var NANY_MEMORY_LIMIT (size in bytes)<commit_after>#include <yuni/yuni.h>
#include <yuni/string.h>
#include <yuni/core/system/main.h>
#include <yuni/core/system/environment.h>
#include <yuni/io/file.h>
#include <nany/nany.h>
#include <memory>
#include <iostream>
#include <cassert>
#include <limits.h>
using namespace Yuni;
static const char* argv0 = "";
struct Options
{
//! Verbose mode
bool verbose = false;
//! Maximum number of jobs
uint32_t jobs = 1;
//! Memory limit (zero means unlimited)
size_t memoryLimit = 0;
};
static int printUsage(const char* const argv0)
{
std::cout
<< "Usage: " << argv0 << " [options] file...\n"
<< "Options:\n"
<< " --bugreport Display some useful information to report a bug\n"
<< " (https://github.com/nany-lang/nany/issues/new)\n"
<< " --help, -h Display this information\n"
<< " --version, -v Print the version\n\n";
return EXIT_SUCCESS;
}
static int printBugReportInfo()
{
auto* text = nany_get_info_for_bugreport();
if (text)
{
std::cout << text;
::free(text);
return 0;
}
return EXIT_FAILURE;
}
static int printVersion()
{
std::cout << nany_version() << '\n';
return EXIT_SUCCESS;
}
static int unknownOption(const AnyString& name)
{
std::cerr << argv0 << ": unknown option '" << name << "'\n";
return EXIT_FAILURE;
}
static inline void initializeContext(nycontext_t& ctx, const Options& options)
{
size_t memoryLimit = options.memoryLimit;
if (memoryLimit == 0)
memoryLimit = static_cast<size_t>(System::Environment::ReadAsUInt64("NANY_MEMORY_LIMIT", 0));
if (memoryLimit == 0)
{
// internal: using nullptr should be slighty faster than
// using 'nany_memalloc_init_default' + custom memalloc as parameter
nany_initialize(&ctx, nullptr, nullptr);
}
else
{
nycontext_memory_t memalloc;
nany_mem_alloc_init_with_limit(&memalloc, memoryLimit);
nany_initialize(&ctx, nullptr, &memalloc);
}
// for concurrent build, create a queue service if more than
// one concurrent job is allowed
if (options.jobs > 1)
ctx.mt.queueservice = nany_queueservice_create();
}
static inline int execute(int argc, char** argv, const Options& options)
{
assert(argc >= 1);
String scriptfile;
IO::Canonicalize(scriptfile, argv[0]);
// nany context
nycontext_t ctx;
initializeContext(ctx, options);
// sources
nany_source_add_from_file_n(&ctx, scriptfile.c_str(), scriptfile.size());
// building
bool buildstatus;
{
nyreport_t* report = nullptr;
buildstatus = (nany_build(&ctx, &report) == nytrue);
// report printing
// if an error has occured or if in verbose mode
if (YUNI_UNLIKELY((not buildstatus) or options.verbose))
(buildstatus ? nany_report_print_stdout : nany_report_print_stderr)(report);
nany_report_unref(&report);
}
// executing the program
int exitstatus = 66;
if (buildstatus)
{
if (argc == 1)
{
const char* nargv[] = { scriptfile.c_str(), nullptr };
exitstatus = nany_run_main(&ctx, 1, nargv);
}
else
{
auto** nargv = (const char**)::malloc(((size_t) argc + 1) * sizeof(const char**));
if (nargv)
{
for (int i = 1; i < argc; ++i)
nargv[i] = argv[i];
nargv[0] = scriptfile.c_str();
nargv[argc] = nullptr;
exitstatus = nany_run_main(&ctx, argc, nargv);
free(nargv);
}
}
}
nany_uninitialize(&ctx);
return exitstatus;
}
YUNI_MAIN_CONSOLE(argc, argv)
{
argv0 = argv[0];
if (YUNI_UNLIKELY(argc <= 1))
{
std::cerr << argv0 << ": no input script file\n";
return EXIT_FAILURE;
}
try
{
Options options;
int firstarg = -1;
for (int i = 1; i < argc; ++i)
{
const char* const carg = argv[i];
if (carg[0] == '-')
{
if (carg[1] == '-')
{
if (carg[2] != '\0') // to handle '--' option
{
AnyString arg{carg};
if (arg == "--help")
return printUsage(argv[0]);
if (arg == "--version")
return printVersion();
if (arg == "--bugreport")
return printBugReportInfo();
if (arg == "--verbose")
{
options.verbose = true;
continue;
}
return unknownOption(arg);
}
else
{
firstarg = i + 1;
break; // nothing must interpreted after '--'
}
}
else
{
AnyString arg{carg};
if (arg == "-h")
return printUsage(argv[0]);
if (arg == "-v")
return printVersion();
return unknownOption(arg);
}
}
firstarg = i;
break;
}
//
// -- execute the script
//
return execute(argc - firstarg, argv + firstarg, options);
}
catch (std::bad_alloc&)
{
std::cerr << '\n' << argv0 << ": error: failed to allocate memory\n";
}
catch (...)
{
std::cerr << '\n' << argv0 << ": error: unhandled exception\n";
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "key.h"
#include "base58.h"
#include "script/script.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_navcoin.h"
#include <string>
#include <vector>
#include <boost/test/unit_test.hpp>
using namespace std;
static const string strSecret1 ("5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj");
static const string strSecret2 ("5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3");
static const string strSecret1C ("Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw");
static const string strSecret2C ("L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g");
static const CNavCoinAddress addr1 ("1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ");
static const CNavCoinAddress addr2 ("1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ");
static const CNavCoinAddress addr1C("1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs");
static const CNavCoinAddress addr2C("1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs");
static const string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF");
#ifdef KEY_TESTS_DUMPINFO
void dumpKeyInfo(uint256 privkey)
{
CKey key;
key.resize(32);
memcpy(&secret[0], &privkey, 32);
vector<unsigned char> sec;
sec.resize(32);
memcpy(&sec[0], &secret[0], 32);
printf(" * secret (hex): %s\n", HexStr(sec).c_str());
for (int nCompressed=0; nCompressed<2; nCompressed++)
{
bool fCompressed = nCompressed == 1;
printf(" * %s:\n", fCompressed ? "compressed" : "uncompressed");
CNavCoinSecret bsecret;
bsecret.SetSecret(secret, fCompressed);
printf(" * secret (base58): %s\n", bsecret.ToString().c_str());
CKey key;
key.SetSecret(secret, fCompressed);
vector<unsigned char> vchPubKey = key.GetPubKey();
printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str());
printf(" * address (base58): %s\n", CNavCoinAddress(vchPubKey).ToString().c_str());
}
}
#endif
BOOST_FIXTURE_TEST_SUITE(key_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(key_test1)
{
CNavCoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1;
BOOST_CHECK( bsecret1.SetString (strSecret1));
BOOST_CHECK( bsecret2.SetString (strSecret2));
BOOST_CHECK( bsecret1C.SetString(strSecret1C));
BOOST_CHECK( bsecret2C.SetString(strSecret2C));
BOOST_CHECK(!baddress1.SetString(strAddressBad));
CKey key1 = bsecret1.GetKey();
BOOST_CHECK(key1.IsCompressed() == false);
CKey key2 = bsecret2.GetKey();
BOOST_CHECK(key2.IsCompressed() == false);
CKey key1C = bsecret1C.GetKey();
BOOST_CHECK(key1C.IsCompressed() == true);
CKey key2C = bsecret2C.GetKey();
BOOST_CHECK(key2C.IsCompressed() == true);
CPubKey pubkey1 = key1. GetPubKey();
CPubKey pubkey2 = key2. GetPubKey();
CPubKey pubkey1C = key1C.GetPubKey();
CPubKey pubkey2C = key2C.GetPubKey();
BOOST_CHECK(key1.VerifyPubKey(pubkey1));
BOOST_CHECK(!key1.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey1));
BOOST_CHECK(key1C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1C));
BOOST_CHECK(key2.VerifyPubKey(pubkey2));
BOOST_CHECK(!key2.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey2));
BOOST_CHECK(key2C.VerifyPubKey(pubkey2C));
BOOST_CHECK(addr1.Get() == CTxDestination(pubkey1.GetID()));
BOOST_CHECK(addr2.Get() == CTxDestination(pubkey2.GetID()));
BOOST_CHECK(addr1C.Get() == CTxDestination(pubkey1C.GetID()));
BOOST_CHECK(addr2C.Get() == CTxDestination(pubkey2C.GetID()));
for (int n=0; n<16; n++)
{
string strMsg = strprintf("Very secret message %i: 11", n);
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// normal signatures
vector<unsigned char> sign1, sign2, sign1C, sign2C;
BOOST_CHECK(key1.Sign (hashMsg, sign1));
BOOST_CHECK(key2.Sign (hashMsg, sign2));
BOOST_CHECK(key1C.Sign(hashMsg, sign1C));
BOOST_CHECK(key2C.Sign(hashMsg, sign2C));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C));
// compact signatures (with key recovery)
vector<unsigned char> csign1, csign2, csign1C, csign2C;
BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C));
BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C));
CPubKey rkey1, rkey2, rkey1C, rkey2C;
BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1));
BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2));
BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C));
BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C));
BOOST_CHECK(rkey1 == pubkey1);
BOOST_CHECK(rkey2 == pubkey2);
BOOST_CHECK(rkey1C == pubkey1C);
BOOST_CHECK(rkey2C == pubkey2C);
}
// test deterministic signing
std::vector<unsigned char> detsig, detsigc;
string strMsg = "Very deterministic message";
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
BOOST_CHECK(key1.Sign(hashMsg, detsig));
BOOST_CHECK(key1C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.Sign(hashMsg, detsig));
BOOST_CHECK(key2C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(key1.SignCompact(hashMsg, detsig));
BOOST_CHECK(key1C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(detsigc == ParseHex("205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.SignCompact(hashMsg, detsig));
BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c52d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(detsigc == ParseHex("2052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Removes Some key tests<commit_after>// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "key.h"
#include "base58.h"
#include "script/script.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_navcoin.h"
#include <string>
#include <vector>
#include <boost/test/unit_test.hpp>
using namespace std;
static const string strSecret1 ("PHSecPt927qh8bVhLhv4Rr66JMUYWRcaQfsdPnP8nucyhE4Lhc8b");
static const string strSecret2 ("PEc7Ctgscq6fJCCBAsmi9NQr2W2dLfpraVJgYqSEhacGP4YwqaDF");
//static const string strSecret1C ("Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw");
//static const string strSecret2C ("L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g");
static const CNavCoinAddress addr1 ("NfWVKf7BxmvNCm8e82eegeKeHyFM2Dy2Nv");
static const CNavCoinAddress addr2 ("NMxJRcqfcgfQvzhKy42zHVSzTfrnS2HLQo");
//static const CNavCoinAddress addr1C("1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs");
//static const CNavCoinAddress addr2C("1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs");
static const string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF");
#ifdef KEY_TESTS_DUMPINFO
void dumpKeyInfo(uint256 privkey)
{
CKey key;
key.resize(32);
memcpy(&secret[0], &privkey, 32);
vector<unsigned char> sec;
sec.resize(32);
memcpy(&sec[0], &secret[0], 32);
printf(" * secret (hex): %s\n", HexStr(sec).c_str());
for (int nCompressed=0; nCompressed<2; nCompressed++)
{
bool fCompressed = nCompressed == 1;
printf(" * %s:\n", fCompressed ? "compressed" : "uncompressed");
CNavCoinSecret bsecret;
bsecret.SetSecret(secret, fCompressed);
printf(" * secret (base58): %s\n", bsecret.ToString().c_str());
CKey key;
key.SetSecret(secret, fCompressed);
vector<unsigned char> vchPubKey = key.GetPubKey();
printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str());
printf(" * address (base58): %s\n", CNavCoinAddress(vchPubKey).ToString().c_str());
}
}
#endif
BOOST_FIXTURE_TEST_SUITE(key_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(key_test1)
{
CNavCoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1;
BOOST_CHECK( bsecret1.SetString (strSecret1));
BOOST_CHECK( bsecret2.SetString (strSecret2));
// BOOST_CHECK( bsecret1C.SetString(strSecret1C));
// BOOST_CHECK( bsecret2C.SetString(strSecret2C));
// BOOST_CHECK(!baddress1.SetString(strAddressBad));
// CKey key1 = bsecret1.GetKey();
// BOOST_CHECK(key1.IsCompressed() == false);
// CKey key2 = bsecret2.GetKey();
// BOOST_CHECK(key2.IsCompressed() == false);
// CKey key1C = bsecret1C.GetKey();
// BOOST_CHECK(key1C.IsCompressed() == true);
// CKey key2C = bsecret2C.GetKey();
// BOOST_CHECK(key2C.IsCompressed() == true);
// CPubKey pubkey1 = key1. GetPubKey();
// CPubKey pubkey2 = key2. GetPubKey();
// CPubKey pubkey1C = key1C.GetPubKey();
// CPubKey pubkey2C = key2C.GetPubKey();
// BOOST_CHECK(key1.VerifyPubKey(pubkey1));
// BOOST_CHECK(!key1.VerifyPubKey(pubkey1C));
// BOOST_CHECK(!key1.VerifyPubKey(pubkey2));
// BOOST_CHECK(!key1.VerifyPubKey(pubkey2C));
// BOOST_CHECK(!key1C.VerifyPubKey(pubkey1));
// BOOST_CHECK(key1C.VerifyPubKey(pubkey1C));
// BOOST_CHECK(!key1C.VerifyPubKey(pubkey2));
// BOOST_CHECK(!key1C.VerifyPubKey(pubkey2C));
// BOOST_CHECK(!key2.VerifyPubKey(pubkey1));
// BOOST_CHECK(!key2.VerifyPubKey(pubkey1C));
// BOOST_CHECK(key2.VerifyPubKey(pubkey2));
// BOOST_CHECK(!key2.VerifyPubKey(pubkey2C));
// BOOST_CHECK(!key2C.VerifyPubKey(pubkey1));
// BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C));
// BOOST_CHECK(!key2C.VerifyPubKey(pubkey2));
// BOOST_CHECK(key2C.VerifyPubKey(pubkey2C));
// BOOST_CHECK(addr1.Get() == CTxDestination(pubkey1.GetID()));
// BOOST_CHECK(addr2.Get() == CTxDestination(pubkey2.GetID()));
// BOOST_CHECK(addr1C.Get() == CTxDestination(pubkey1C.GetID()));
// BOOST_CHECK(addr2C.Get() == CTxDestination(pubkey2C.GetID()));
// for (int n=0; n<16; n++)
// {
// string strMsg = strprintf("Very secret message %i: 11", n);
// uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// // normal signatures
// vector<unsigned char> sign1, sign2, sign1C, sign2C;
// BOOST_CHECK(key1.Sign (hashMsg, sign1));
// BOOST_CHECK(key2.Sign (hashMsg, sign2));
// BOOST_CHECK(key1C.Sign(hashMsg, sign1C));
// BOOST_CHECK(key2C.Sign(hashMsg, sign2C));
// BOOST_CHECK( pubkey1.Verify(hashMsg, sign1));
// BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2));
// BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C));
// BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C));
// BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1));
// BOOST_CHECK( pubkey2.Verify(hashMsg, sign2));
// BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C));
// BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C));
// BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1));
// BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2));
// BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C));
// BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C));
// BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1));
// BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2));
// BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C));
// BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C));
// // compact signatures (with key recovery)
// vector<unsigned char> csign1, csign2, csign1C, csign2C;
// BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
// BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
// BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C));
// BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C));
// CPubKey rkey1, rkey2, rkey1C, rkey2C;
// BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1));
// BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2));
// BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C));
// BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C));
// BOOST_CHECK(rkey1 == pubkey1);
// BOOST_CHECK(rkey2 == pubkey2);
// BOOST_CHECK(rkey1C == pubkey1C);
// BOOST_CHECK(rkey2C == pubkey2C);
// }
// // test deterministic signing
// std::vector<unsigned char> detsig, detsigc;
// string strMsg = "Very deterministic message";
// uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// BOOST_CHECK(key1.Sign(hashMsg, detsig));
// BOOST_CHECK(key1C.Sign(hashMsg, detsigc));
// BOOST_CHECK(detsig == detsigc);
// BOOST_CHECK(detsig == ParseHex("304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
// BOOST_CHECK(key2.Sign(hashMsg, detsig));
// BOOST_CHECK(key2C.Sign(hashMsg, detsigc));
// BOOST_CHECK(detsig == detsigc);
// BOOST_CHECK(detsig == ParseHex("3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
// BOOST_CHECK(key1.SignCompact(hashMsg, detsig));
// BOOST_CHECK(key1C.SignCompact(hashMsg, detsigc));
// BOOST_CHECK(detsig == ParseHex("1c5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
// BOOST_CHECK(detsigc == ParseHex("205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
// BOOST_CHECK(key2.SignCompact(hashMsg, detsig));
// BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc));
// BOOST_CHECK(detsig == ParseHex("1c52d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
// BOOST_CHECK(detsigc == ParseHex("2052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 Communi authors
*
* 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.
*/
#include "commandparser.h"
#include <IrcCommand>
#include <QDateTime>
#include <QHash>
#include <QMap>
CommandParser::Private CommandParser::d;
static QMap<QString, QString>& command_syntaxes()
{
static QMap<QString, QString> syntaxes;
if (syntaxes.isEmpty()) {
syntaxes.insert("ADMIN", "(<server>)");
syntaxes.insert("AWAY", "(<reason...>)");
syntaxes.insert("INFO", "(<server>)");
syntaxes.insert("INVITE", "<user>");
syntaxes.insert("JOIN", "<channel> (<key>)");
syntaxes.insert("KICK", "<user> (<reason...>)");
syntaxes.insert("KNOCK", "<channel> (<message...>)");
syntaxes.insert("LIST", "(<channels>) (<server>)");
syntaxes.insert("ME", "<message...>");
syntaxes.insert("MODE", "<channel/user> (<mode>) (<arg>)");
syntaxes.insert("MOTD", "(<server>)");
syntaxes.insert("NAMES", "(<channel>)");
syntaxes.insert("NICK", "<nick>");
syntaxes.insert("NOTICE", "<channel/user> <message...>");
syntaxes.insert("PART", "(<reason...>)");
syntaxes.insert("PING", "(<user>)");
syntaxes.insert("QUIT" , "(<message...>)");
syntaxes.insert("QUOTE" , "<command> (<parameters...>)");
syntaxes.insert("STATS", "<query> (<server>)");
syntaxes.insert("TIME", "(<user>)");
syntaxes.insert("TOPIC", "(<topic...>)");
syntaxes.insert("TRACE", "(<target>)");
syntaxes.insert("USERS", "(<server>)");
syntaxes.insert("VERSION", "(<user>)");
syntaxes.insert("WHO", "<user>");
syntaxes.insert("WHOIS", "<user>");
syntaxes.insert("WHOWAS", "<user>");
}
return syntaxes;
}
static QString expandAlias(const QString& receiver, const QString& message)
{
QStringList words = message.split(QRegExp("\\s+"), QString::SkipEmptyParts);
QString alias = words.takeFirst().toUpper();
QMap<QString, QString> aliases = CommandParser::aliases();
if (aliases.contains(alias)) {
int pos = 0;
QRegExp regExp("\\$(\\d+)");
QString command = aliases.value(alias);
while ((pos = regExp.indexIn(command)) != -1)
{
int index = regExp.cap(1).toInt();
command.replace(pos, regExp.matchedLength(), words.value(index - 1));
}
command.replace("$*", words.join(" "));
command.replace("$?", receiver);
return command;
}
return message;
}
QStringList CommandParser::availableCommands()
{
QStringList commands = command_syntaxes().keys() + d.aliases.keys();
qSort(commands);
return commands;
}
QStringList CommandParser::suggestedCommands(const QString& command, const QStringList& params)
{
QStringList suggestions;
foreach (const QString& available, availableCommands()) {
if (!command.compare(available, Qt::CaseInsensitive) || (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)))
suggestions += available;
}
return suggestions;
}
QString CommandParser::syntax(const QString& command)
{
QString cmd = command.toUpper();
if (command_syntaxes().contains(cmd))
return cmd + " " + command_syntaxes().value(cmd);
if (d.aliases.contains(cmd))
return d.aliases.value(cmd);
return QString();
}
void CommandParser::addCustomCommand(const QString& command, const QString& syntax)
{
command_syntaxes().insert(command.toUpper(), syntax);
}
void CommandParser::removeCustomCommand(const QString& command)
{
command_syntaxes().remove(command.toUpper());
}
QMap<QString, QString> CommandParser::aliases()
{
return d.aliases;
}
void CommandParser::setAliases(const QMap<QString, QString>& aliases)
{
d.aliases.clear();
QMapIterator<QString, QString> it(aliases);
while (it.hasNext()) {
it.next();
d.aliases[it.key().toUpper()] = it.value();
}
}
IrcCommand* CommandParser::parseCommand(const QString& receiver, const QString& text)
{
if (text.startsWith("/")) {
typedef IrcCommand*(*ParseFunc)(const QString&, const QStringList&);
static QHash<QString, ParseFunc> parseFunctions;
if (parseFunctions.isEmpty()) {
parseFunctions.insert("ADMIN", &CommandParser::parseAdmin);
parseFunctions.insert("AWAY", &CommandParser::parseAway);
parseFunctions.insert("INFO", &CommandParser::parseInfo);
parseFunctions.insert("INVITE", &CommandParser::parseInvite);
parseFunctions.insert("JOIN", &CommandParser::parseJoin);
parseFunctions.insert("KICK", &CommandParser::parseKick);
parseFunctions.insert("KNOCK", &CommandParser::parseKnock);
parseFunctions.insert("LIST", &CommandParser::parseList);
parseFunctions.insert("ME", &CommandParser::parseMe);
parseFunctions.insert("MODE", &CommandParser::parseMode);
parseFunctions.insert("MOTD", &CommandParser::parseMotd);
parseFunctions.insert("NAMES", &CommandParser::parseNames);
parseFunctions.insert("NICK", &CommandParser::parseNick);
parseFunctions.insert("NOTICE", &CommandParser::parseNotice);
parseFunctions.insert("PART", &CommandParser::parsePart);
parseFunctions.insert("PING", &CommandParser::parsePing);
parseFunctions.insert("QUIT", &CommandParser::parseQuit);
parseFunctions.insert("QUOTE", &CommandParser::parseQuote);
parseFunctions.insert("STATS", &CommandParser::parseStats);
parseFunctions.insert("TIME", &CommandParser::parseTime);
parseFunctions.insert("TOPIC", &CommandParser::parseTopic);
parseFunctions.insert("TRACE", &CommandParser::parseTrace);
parseFunctions.insert("USERS", &CommandParser::parseUsers);
parseFunctions.insert("VERSION", &CommandParser::parseVersion);
parseFunctions.insert("WHO", &CommandParser::parseWho);
parseFunctions.insert("WHOIS", &CommandParser::parseWhois);
parseFunctions.insert("WHOWAS", &CommandParser::parseWhowas);
}
const QString expanded = expandAlias(receiver, text.mid(1));
const QStringList words = expanded.split(" ", QString::SkipEmptyParts);
const QString command = words.value(0).toUpper();
ParseFunc parseFunc = parseFunctions.value(command);
if (parseFunc) {
IrcCommand* cmd = parseFunc(receiver, words.mid(1));
if (cmd)
return cmd;
} else if (command_syntaxes().contains(command.toUpper())) {
return parseCustomCommand(command, words.mid(1), command_syntaxes().value(command.toUpper()));
}
} else {
return IrcCommand::createMessage(receiver, text);
}
// unknown command
return 0;
}
IrcCommand* CommandParser::parseCustomCommand(const QString& command, const QStringList& params, const QString& syntax)
{
QStringList tokens = syntax.split(" ", QString::SkipEmptyParts);
int min = 0;
int max = tokens.count();
while (!tokens.isEmpty())
{
QString p = tokens.takeFirst();
if (!p.startsWith("(<"))
++min;
if (tokens.isEmpty() && (p.endsWith("...>") || p.endsWith("...>)")))
max = INT_MAX;
}
if (params.count() >= min && params.count() <= max) {
IrcCommand* cmd = new IrcCommand;
cmd->setType(IrcCommand::Custom);
cmd->setParameters(QStringList(command) + params);
return cmd;
}
return 0;
}
IrcCommand* CommandParser::parseAdmin(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createAdmin(params.value(0));
}
IrcCommand* CommandParser::parseAway(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createAway(params.value(0));
}
IrcCommand* CommandParser::parseInfo(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createUsers(params.join(" "));
}
IrcCommand* CommandParser::parseInvite(const QString& receiver, const QStringList& params)
{
if (params.count() == 1)
return IrcCommand::createInvite(params.at(0), receiver);
return 0;
}
IrcCommand* CommandParser::parseJoin(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1 || params.count() == 2)
return IrcCommand::createJoin(params.at(0), params.value(1));
return 0;
}
IrcCommand* CommandParser::parseKick(const QString& receiver, const QStringList& params)
{
if (params.count() >= 1)
return IrcCommand::createKick(receiver, params.at(0), QStringList(params.mid(1)).join(" "));
return 0;
}
IrcCommand* CommandParser::parseKnock(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() >= 1)
return IrcCommand::createKnock(params.at(0), QStringList(params.mid(1)).join(" "));
return 0;
}
IrcCommand* CommandParser::parseList(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createList(params);
}
IrcCommand* CommandParser::parseMe(const QString& receiver, const QStringList& params)
{
if (!params.isEmpty())
return IrcCommand::createCtcpAction(receiver, params.join(" "));
return 0;
}
IrcCommand* CommandParser::parseMode(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() >= 1 && params.count() <= 4)
return IrcCommand::createMode(params.at(0), params.value(1), params.value(2));
return 0;
}
IrcCommand* CommandParser::parseMotd(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createMotd(params.join(" "));
}
IrcCommand* CommandParser::parseNames(const QString& receiver, const QStringList& params)
{
if (params.isEmpty())
return IrcCommand::createNames(receiver);
return IrcCommand::createNames(params);
}
IrcCommand* CommandParser::parseNick(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createNick(params.at(0));
return 0;
}
IrcCommand* CommandParser::parseNotice(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() >= 2)
return IrcCommand::createNotice(params.at(0), QStringList(params.mid(1)).join(" "));
return 0;
}
IrcCommand* CommandParser::parsePart(const QString& receiver, const QStringList& params)
{
return IrcCommand::createPart(receiver, params.join(" "));
}
IrcCommand* CommandParser::parsePing(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
QString time = QString::number(QDateTime::currentDateTime().toTime_t());
if (params.isEmpty())
return IrcCommand::createQuote(QStringList() << "PING" << time);
return IrcCommand::createCtcpRequest(params.at(0), "PING " + time);
}
IrcCommand* CommandParser::parseQuit(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createQuit(params.join(" "));
}
IrcCommand* CommandParser::parseQuote(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createQuote(params);
}
IrcCommand* CommandParser::parseStats(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (!params.isEmpty())
return IrcCommand::createStats(params.join(" "));
return 0;
}
IrcCommand* CommandParser::parseTime(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.isEmpty())
return IrcCommand::createTime();
return IrcCommand::createCtcpRequest(params.at(0), "TIME");
}
IrcCommand* CommandParser::parseTopic(const QString& receiver, const QStringList& params)
{
return IrcCommand::createTopic(receiver, params.join(" "));
}
IrcCommand* CommandParser::parseTrace(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createTrace(params.join(" "));
}
IrcCommand* CommandParser::parseUsers(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createUsers(params.join(" "));
}
IrcCommand* CommandParser::parseVersion(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.isEmpty())
return IrcCommand::createVersion();
return IrcCommand::createCtcpRequest(params.at(0), "VERSION");
}
IrcCommand* CommandParser::parseWho(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createWho(params.at(0));
return 0;
}
IrcCommand* CommandParser::parseWhois(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createWhois(params.at(0));
return 0;
}
IrcCommand* CommandParser::parseWhowas(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createWhowas(params.at(0));
return 0;
}
<commit_msg>Fix #16: Provide a way to use a slash at the start of a message<commit_after>/*
* Copyright (C) 2008-2013 Communi authors
*
* 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.
*/
#include "commandparser.h"
#include <IrcCommand>
#include <QDateTime>
#include <QHash>
#include <QMap>
CommandParser::Private CommandParser::d;
static QMap<QString, QString>& command_syntaxes()
{
static QMap<QString, QString> syntaxes;
if (syntaxes.isEmpty()) {
syntaxes.insert("ADMIN", "(<server>)");
syntaxes.insert("AWAY", "(<reason...>)");
syntaxes.insert("INFO", "(<server>)");
syntaxes.insert("INVITE", "<user>");
syntaxes.insert("JOIN", "<channel> (<key>)");
syntaxes.insert("KICK", "<user> (<reason...>)");
syntaxes.insert("KNOCK", "<channel> (<message...>)");
syntaxes.insert("LIST", "(<channels>) (<server>)");
syntaxes.insert("ME", "<message...>");
syntaxes.insert("MODE", "<channel/user> (<mode>) (<arg>)");
syntaxes.insert("MOTD", "(<server>)");
syntaxes.insert("NAMES", "(<channel>)");
syntaxes.insert("NICK", "<nick>");
syntaxes.insert("NOTICE", "<channel/user> <message...>");
syntaxes.insert("PART", "(<reason...>)");
syntaxes.insert("PING", "(<user>)");
syntaxes.insert("QUIT" , "(<message...>)");
syntaxes.insert("QUOTE" , "<command> (<parameters...>)");
syntaxes.insert("STATS", "<query> (<server>)");
syntaxes.insert("TIME", "(<user>)");
syntaxes.insert("TOPIC", "(<topic...>)");
syntaxes.insert("TRACE", "(<target>)");
syntaxes.insert("USERS", "(<server>)");
syntaxes.insert("VERSION", "(<user>)");
syntaxes.insert("WHO", "<user>");
syntaxes.insert("WHOIS", "<user>");
syntaxes.insert("WHOWAS", "<user>");
}
return syntaxes;
}
static QString expandAlias(const QString& receiver, const QString& message)
{
QStringList words = message.split(QRegExp("\\s+"), QString::SkipEmptyParts);
QString alias = words.takeFirst().toUpper();
QMap<QString, QString> aliases = CommandParser::aliases();
if (aliases.contains(alias)) {
int pos = 0;
QRegExp regExp("\\$(\\d+)");
QString command = aliases.value(alias);
while ((pos = regExp.indexIn(command)) != -1)
{
int index = regExp.cap(1).toInt();
command.replace(pos, regExp.matchedLength(), words.value(index - 1));
}
command.replace("$*", words.join(" "));
command.replace("$?", receiver);
return command;
}
return message;
}
QStringList CommandParser::availableCommands()
{
QStringList commands = command_syntaxes().keys() + d.aliases.keys();
qSort(commands);
return commands;
}
QStringList CommandParser::suggestedCommands(const QString& command, const QStringList& params)
{
QStringList suggestions;
foreach (const QString& available, availableCommands()) {
if (!command.compare(available, Qt::CaseInsensitive) || (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)))
suggestions += available;
}
return suggestions;
}
QString CommandParser::syntax(const QString& command)
{
QString cmd = command.toUpper();
if (command_syntaxes().contains(cmd))
return cmd + " " + command_syntaxes().value(cmd);
if (d.aliases.contains(cmd))
return d.aliases.value(cmd);
return QString();
}
void CommandParser::addCustomCommand(const QString& command, const QString& syntax)
{
command_syntaxes().insert(command.toUpper(), syntax);
}
void CommandParser::removeCustomCommand(const QString& command)
{
command_syntaxes().remove(command.toUpper());
}
QMap<QString, QString> CommandParser::aliases()
{
return d.aliases;
}
void CommandParser::setAliases(const QMap<QString, QString>& aliases)
{
d.aliases.clear();
QMapIterator<QString, QString> it(aliases);
while (it.hasNext()) {
it.next();
d.aliases[it.key().toUpper()] = it.value();
}
}
IrcCommand* CommandParser::parseCommand(const QString& receiver, const QString& text)
{
if (text.startsWith("//") || text.startsWith("/ ") || !text.startsWith('/')) {
QString message = text;
if (message.startsWith('/'))
message.remove(0, 1);
return IrcCommand::createMessage(receiver, message.trimmed());
} else {
typedef IrcCommand*(*ParseFunc)(const QString&, const QStringList&);
static QHash<QString, ParseFunc> parseFunctions;
if (parseFunctions.isEmpty()) {
parseFunctions.insert("ADMIN", &CommandParser::parseAdmin);
parseFunctions.insert("AWAY", &CommandParser::parseAway);
parseFunctions.insert("INFO", &CommandParser::parseInfo);
parseFunctions.insert("INVITE", &CommandParser::parseInvite);
parseFunctions.insert("JOIN", &CommandParser::parseJoin);
parseFunctions.insert("KICK", &CommandParser::parseKick);
parseFunctions.insert("KNOCK", &CommandParser::parseKnock);
parseFunctions.insert("LIST", &CommandParser::parseList);
parseFunctions.insert("ME", &CommandParser::parseMe);
parseFunctions.insert("MODE", &CommandParser::parseMode);
parseFunctions.insert("MOTD", &CommandParser::parseMotd);
parseFunctions.insert("NAMES", &CommandParser::parseNames);
parseFunctions.insert("NICK", &CommandParser::parseNick);
parseFunctions.insert("NOTICE", &CommandParser::parseNotice);
parseFunctions.insert("PART", &CommandParser::parsePart);
parseFunctions.insert("PING", &CommandParser::parsePing);
parseFunctions.insert("QUIT", &CommandParser::parseQuit);
parseFunctions.insert("QUOTE", &CommandParser::parseQuote);
parseFunctions.insert("STATS", &CommandParser::parseStats);
parseFunctions.insert("TIME", &CommandParser::parseTime);
parseFunctions.insert("TOPIC", &CommandParser::parseTopic);
parseFunctions.insert("TRACE", &CommandParser::parseTrace);
parseFunctions.insert("USERS", &CommandParser::parseUsers);
parseFunctions.insert("VERSION", &CommandParser::parseVersion);
parseFunctions.insert("WHO", &CommandParser::parseWho);
parseFunctions.insert("WHOIS", &CommandParser::parseWhois);
parseFunctions.insert("WHOWAS", &CommandParser::parseWhowas);
}
const QString expanded = expandAlias(receiver, text.mid(1));
const QStringList words = expanded.split(" ", QString::SkipEmptyParts);
const QString command = words.value(0).toUpper();
ParseFunc parseFunc = parseFunctions.value(command);
if (parseFunc) {
IrcCommand* cmd = parseFunc(receiver, words.mid(1));
if (cmd)
return cmd;
} else if (command_syntaxes().contains(command.toUpper())) {
return parseCustomCommand(command, words.mid(1), command_syntaxes().value(command.toUpper()));
}
}
// unknown command
return 0;
}
IrcCommand* CommandParser::parseCustomCommand(const QString& command, const QStringList& params, const QString& syntax)
{
QStringList tokens = syntax.split(" ", QString::SkipEmptyParts);
int min = 0;
int max = tokens.count();
while (!tokens.isEmpty())
{
QString p = tokens.takeFirst();
if (!p.startsWith("(<"))
++min;
if (tokens.isEmpty() && (p.endsWith("...>") || p.endsWith("...>)")))
max = INT_MAX;
}
if (params.count() >= min && params.count() <= max) {
IrcCommand* cmd = new IrcCommand;
cmd->setType(IrcCommand::Custom);
cmd->setParameters(QStringList(command) + params);
return cmd;
}
return 0;
}
IrcCommand* CommandParser::parseAdmin(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createAdmin(params.value(0));
}
IrcCommand* CommandParser::parseAway(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createAway(params.value(0));
}
IrcCommand* CommandParser::parseInfo(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createUsers(params.join(" "));
}
IrcCommand* CommandParser::parseInvite(const QString& receiver, const QStringList& params)
{
if (params.count() == 1)
return IrcCommand::createInvite(params.at(0), receiver);
return 0;
}
IrcCommand* CommandParser::parseJoin(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1 || params.count() == 2)
return IrcCommand::createJoin(params.at(0), params.value(1));
return 0;
}
IrcCommand* CommandParser::parseKick(const QString& receiver, const QStringList& params)
{
if (params.count() >= 1)
return IrcCommand::createKick(receiver, params.at(0), QStringList(params.mid(1)).join(" "));
return 0;
}
IrcCommand* CommandParser::parseKnock(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() >= 1)
return IrcCommand::createKnock(params.at(0), QStringList(params.mid(1)).join(" "));
return 0;
}
IrcCommand* CommandParser::parseList(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createList(params);
}
IrcCommand* CommandParser::parseMe(const QString& receiver, const QStringList& params)
{
if (!params.isEmpty())
return IrcCommand::createCtcpAction(receiver, params.join(" "));
return 0;
}
IrcCommand* CommandParser::parseMode(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() >= 1 && params.count() <= 4)
return IrcCommand::createMode(params.at(0), params.value(1), params.value(2));
return 0;
}
IrcCommand* CommandParser::parseMotd(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createMotd(params.join(" "));
}
IrcCommand* CommandParser::parseNames(const QString& receiver, const QStringList& params)
{
if (params.isEmpty())
return IrcCommand::createNames(receiver);
return IrcCommand::createNames(params);
}
IrcCommand* CommandParser::parseNick(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createNick(params.at(0));
return 0;
}
IrcCommand* CommandParser::parseNotice(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() >= 2)
return IrcCommand::createNotice(params.at(0), QStringList(params.mid(1)).join(" "));
return 0;
}
IrcCommand* CommandParser::parsePart(const QString& receiver, const QStringList& params)
{
return IrcCommand::createPart(receiver, params.join(" "));
}
IrcCommand* CommandParser::parsePing(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
QString time = QString::number(QDateTime::currentDateTime().toTime_t());
if (params.isEmpty())
return IrcCommand::createQuote(QStringList() << "PING" << time);
return IrcCommand::createCtcpRequest(params.at(0), "PING " + time);
}
IrcCommand* CommandParser::parseQuit(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createQuit(params.join(" "));
}
IrcCommand* CommandParser::parseQuote(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createQuote(params);
}
IrcCommand* CommandParser::parseStats(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (!params.isEmpty())
return IrcCommand::createStats(params.join(" "));
return 0;
}
IrcCommand* CommandParser::parseTime(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.isEmpty())
return IrcCommand::createTime();
return IrcCommand::createCtcpRequest(params.at(0), "TIME");
}
IrcCommand* CommandParser::parseTopic(const QString& receiver, const QStringList& params)
{
return IrcCommand::createTopic(receiver, params.join(" "));
}
IrcCommand* CommandParser::parseTrace(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createTrace(params.join(" "));
}
IrcCommand* CommandParser::parseUsers(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
return IrcCommand::createUsers(params.join(" "));
}
IrcCommand* CommandParser::parseVersion(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.isEmpty())
return IrcCommand::createVersion();
return IrcCommand::createCtcpRequest(params.at(0), "VERSION");
}
IrcCommand* CommandParser::parseWho(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createWho(params.at(0));
return 0;
}
IrcCommand* CommandParser::parseWhois(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createWhois(params.at(0));
return 0;
}
IrcCommand* CommandParser::parseWhowas(const QString& receiver, const QStringList& params)
{
Q_UNUSED(receiver);
if (params.count() == 1)
return IrcCommand::createWhowas(params.at(0));
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/error.h>
#include "zorbaerrors/errors.h"
#include "zorbaerrors/error_messages.h"
namespace zorba { namespace error {
std::string
ZorbaError::toString(const XQUERY_ERROR& code)
{
return ErrorMessages::getNameForErrorCode(code);
}
ZorbaError::~ZorbaError()
{
free();
}
void ZorbaError::free()
{
delete this;
}
ZorbaError::ZorbaError(
XQUERY_ERROR& aErrorCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(toString(aErrorCode)),
thePrefix("err"),
theNamespace(XQUERY_ERR_NS),
theErrorCode(aErrorCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
}
ZorbaError::ZorbaError(
const xqpString& aErrLocalName,
const xqpString& aErrPrefix,
const xqpString& aErrNamespace,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(aErrLocalName),
thePrefix(aErrPrefix),
theNamespace(aErrNamespace),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
// compute err code from qname
if (aErrNamespace.getStore()->byteEqual(XQUERY_ERR_NS))
theErrorCode = ErrorMessages::getErrorCodeForName(aErrLocalName.getStore()->c_str());
else
theErrorCode = XQP0021_USER_ERROR;
}
ZorbaError::ZorbaError(const ZorbaError& other)
:
theLocalName(other.theLocalName),
thePrefix(other.thePrefix),
theNamespace(other.theNamespace),
theErrorCode(other.theErrorCode),
theDescription(other.theDescription),
theQueryLine(other.theQueryLine),
theQueryColumn(other.theQueryColumn),
theQueryFileName(other.theQueryFileName),
theFileName(other.theFileName),
theLineNumber(other.theLineNumber)
{
}
std::string
ZorbaError::toString()
{
std::ostringstream strstream;
strstream << "Code : " << ErrorMessages::getNameForErrorCode(theErrorCode)
<< std::endl << "Description : " << theDescription << std::endl;
return strstream.str();
}
bool
ZorbaError::isXPathStaticError() const
{
return (XPST0001 <= theErrorCode && theErrorCode <= XPST0083);
}
bool
ZorbaError::isXPathDynamicError() const
{
return (XPDY0002 <= theErrorCode && theErrorCode <= XPDY0050);
}
bool
ZorbaError::isXPathTypeError() const
{
return XPTY0004 <= theErrorCode && theErrorCode <= XPTY0020;
}
bool
ZorbaError::isXQueryDynamicError() const
{
return ((XQDY0025 <= theErrorCode &&
theErrorCode <= XQDY0092) ||
XUDY0009 == theErrorCode ||
(XUDY0014 <= theErrorCode &&
theErrorCode <= XUDY0021) ||
(XUDY0023 <= theErrorCode &&
theErrorCode <= XUDY0025) ||
theErrorCode == XUDY0027 ||
theErrorCode == XUDY0029 ||
theErrorCode == XUDY0030);
}
bool
ZorbaError::isXQueryStaticError() const
{
return ((XQST0009 <= theErrorCode &&
theErrorCode <= XQST0093) ||
(XUST0001 <= theErrorCode &&
theErrorCode <= XUST0003) ||
theErrorCode == XUST0028);
}
bool
ZorbaError::isXQueryTypeError() const
{
return ((XQTY0023 <= theErrorCode &&
theErrorCode <= XQTY0086) ||
(XUTY0004 <= theErrorCode &&
theErrorCode <= XUTY0008) ||
(XUTY0010 <= theErrorCode &&
theErrorCode <= XUTY0013) ||
theErrorCode == XUTY0022);
}
bool
ZorbaError::isFunctionError() const
{
return FOER0000 <= theErrorCode && theErrorCode <= FOTY0012;
}
bool
ZorbaError::isSerializationError() const
{
return SENR0001 <= theErrorCode && theErrorCode <= SEPM0016;
}
bool
ZorbaError::isInternalError() const
{
return XQP0000_DYNAMIC_RUNTIME_ERROR <= theErrorCode &&
theErrorCode <= MAX_ZORBA_ERROR_CODE;
}
bool
ZorbaError::isStaticError() const
{
return isXPathStaticError() || isXQueryStaticError();
}
bool
ZorbaError::isDynamicError() const
{
return isXPathDynamicError() || isXQueryDynamicError() || isFunctionError();
}
bool
ZorbaError::isTypeError() const
{
return isXPathTypeError() || isXQueryTypeError();
}
ZorbaWarning::ZorbaWarning(
WarningCode aWarningCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theCode(aWarningCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
}
} /* namespace error */
} /* namespace zorba */
<commit_msg>error item<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/error.h>
#include "zorbaerrors/errors.h"
#include "zorbaerrors/error_messages.h"
namespace zorba { namespace error {
std::string
ZorbaError::toString(const XQUERY_ERROR& code)
{
return ErrorMessages::getNameForErrorCode(code);
}
ZorbaError::~ZorbaError()
{
}
void ZorbaError::free()
{
delete this;
}
ZorbaError::ZorbaError(
XQUERY_ERROR& aErrorCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(toString(aErrorCode)),
thePrefix("err"),
theNamespace(XQUERY_ERR_NS),
theErrorCode(aErrorCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
}
ZorbaError::ZorbaError(
const xqpString& aErrLocalName,
const xqpString& aErrPrefix,
const xqpString& aErrNamespace,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theLocalName(aErrLocalName),
thePrefix(aErrPrefix),
theNamespace(aErrNamespace),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
// compute err code from qname
if (aErrNamespace.getStore()->byteEqual(XQUERY_ERR_NS))
theErrorCode = ErrorMessages::getErrorCodeForName(aErrLocalName.getStore()->c_str());
else
theErrorCode = XQP0021_USER_ERROR;
}
ZorbaError::ZorbaError(const ZorbaError& other)
:
theLocalName(other.theLocalName),
thePrefix(other.thePrefix),
theNamespace(other.theNamespace),
theErrorCode(other.theErrorCode),
theDescription(other.theDescription),
theQueryLine(other.theQueryLine),
theQueryColumn(other.theQueryColumn),
theQueryFileName(other.theQueryFileName),
theFileName(other.theFileName),
theLineNumber(other.theLineNumber)
{
}
std::string
ZorbaError::toString()
{
std::ostringstream strstream;
strstream << "Code : " << ErrorMessages::getNameForErrorCode(theErrorCode)
<< std::endl << "Description : " << theDescription << std::endl;
return strstream.str();
}
bool
ZorbaError::isXPathStaticError() const
{
return (XPST0001 <= theErrorCode && theErrorCode <= XPST0083);
}
bool
ZorbaError::isXPathDynamicError() const
{
return (XPDY0002 <= theErrorCode && theErrorCode <= XPDY0050);
}
bool
ZorbaError::isXPathTypeError() const
{
return XPTY0004 <= theErrorCode && theErrorCode <= XPTY0020;
}
bool
ZorbaError::isXQueryDynamicError() const
{
return ((XQDY0025 <= theErrorCode &&
theErrorCode <= XQDY0092) ||
XUDY0009 == theErrorCode ||
(XUDY0014 <= theErrorCode &&
theErrorCode <= XUDY0021) ||
(XUDY0023 <= theErrorCode &&
theErrorCode <= XUDY0025) ||
theErrorCode == XUDY0027 ||
theErrorCode == XUDY0029 ||
theErrorCode == XUDY0030);
}
bool
ZorbaError::isXQueryStaticError() const
{
return ((XQST0009 <= theErrorCode &&
theErrorCode <= XQST0093) ||
(XUST0001 <= theErrorCode &&
theErrorCode <= XUST0003) ||
theErrorCode == XUST0028);
}
bool
ZorbaError::isXQueryTypeError() const
{
return ((XQTY0023 <= theErrorCode &&
theErrorCode <= XQTY0086) ||
(XUTY0004 <= theErrorCode &&
theErrorCode <= XUTY0008) ||
(XUTY0010 <= theErrorCode &&
theErrorCode <= XUTY0013) ||
theErrorCode == XUTY0022);
}
bool
ZorbaError::isFunctionError() const
{
return FOER0000 <= theErrorCode && theErrorCode <= FOTY0012;
}
bool
ZorbaError::isSerializationError() const
{
return SENR0001 <= theErrorCode && theErrorCode <= SEPM0016;
}
bool
ZorbaError::isInternalError() const
{
return XQP0000_DYNAMIC_RUNTIME_ERROR <= theErrorCode &&
theErrorCode <= MAX_ZORBA_ERROR_CODE;
}
bool
ZorbaError::isStaticError() const
{
return isXPathStaticError() || isXQueryStaticError();
}
bool
ZorbaError::isDynamicError() const
{
return isXPathDynamicError() || isXQueryDynamicError() || isFunctionError();
}
bool
ZorbaError::isTypeError() const
{
return isXPathTypeError() || isXQueryTypeError();
}
ZorbaWarning::ZorbaWarning(
WarningCode aWarningCode,
const xqpString& aDescription,
unsigned int aQueryLine,
unsigned int aQueryColumn,
const std::string& aQueryFileName,
const std::string& aFileName,
int aLineNumber)
:
theCode(aWarningCode),
theDescription(aDescription),
theQueryLine(aQueryLine),
theQueryColumn(aQueryColumn),
theQueryFileName(aQueryFileName),
theFileName(aFileName),
theLineNumber(aLineNumber)
{
}
} /* namespace error */
} /* namespace zorba */
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.