<commit_before>#include "chimera/render/Plane.hpp"
#include "chimera/render/VertexData.hpp"

namespace Chimera {
Plane::Plane() {}

Plane::Plane(const Plane& _cpy) {
    this->point = _cpy.point;
    this->normal = _cpy.normal;
    this->ND = _cpy.ND;
    this->O = _cpy.O;
}

Plane::Plane(const glm::vec3& _position, const glm::vec3& _normal) { this->set(_position, _normal); }

Plane::~Plane() {}

void Plane::set(const glm::vec3& pA, const glm::vec3& B, const glm::vec3& C) {
    point = pA;
    normal = glm::normalize(glm::cross(B - pA, C - pA));
    ND = dot(normal, pA);
    O = normal.z < 0.0f ? (normal.y < 0.0f ? (normal.x < 0.0f ? 0 : 1) : (normal.x < 0.0f ? 2 : 3))
                        : (normal.y < 0.0f ? (normal.x < 0.0f ? 4 : 5) : (normal.x < 0.0f ? 6 : 7));
}

void Plane::set(const glm::vec3& pA, const glm::vec3& _normal) {
    point = pA;       //_point->vertex[0].position;
    normal = _normal; //_point->normal();
    ND = dot(normal, pA);
    O = normal.z < 0.0f ? (normal.y < 0.0f ? (normal.x < 0.0f ? 0 : 1) : (normal.x < 0.0f ? 2 : 3))
                        : (normal.y < 0.0f ? (normal.x < 0.0f ? 4 : 5) : (normal.x < 0.0f ? 6 : 7));
}

SIDE Plane::classifyPoint(glm::vec3* point) {
    // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm
    glm::vec3 dir = this->point - (*point);
    float clipTest = glm::dot(dir, this->normal);

    clipTest = fabs(clipTest) < EPSILON ? 0.0f : clipTest;

    if (clipTest < 0.0f)
        return SIDE::CP_FRONT;
    else if (clipTest > 0.0f)
        return SIDE::CP_BACK;

    return SIDE::CP_ONPLANE;
}

SIDE Plane::classifyPoly(const glm::vec3& pA, const glm::vec3& pB, const glm::vec3& pC, glm::vec3* clipTest) {
    // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm
    unsigned short infront = 0;
    unsigned short behind = 0;
    unsigned short onPlane = 0;
    float result[3];

    result[0] = glm::dot((this->point - pA), this->normal); // Clip Test poin A
    result[1] = glm::dot((this->point - pB), this->normal); // Clip Test poin B
    result[2] = glm::dot((this->point - pC), this->normal); // Clip Test poin C

    for (unsigned short a = 0; a < 3; a++) {
        result[a] = fabs(result[a]) < EPSILON ? 0.0f : result[a];
        if (result[a] > 0.0f) {
            behind++;
        } else if (result[a] < 0.0f) {
            infront++;
        } else {
            onPlane++;
            infront++;
            behind++;
        }
    }

    clipTest->x = result[0];
    clipTest->y = result[1];
    clipTest->z = result[2];

    if (onPlane == 3)
        return SIDE::CP_ONPLANE;

    if (behind == 3)
        return SIDE::CP_BACK;

    if (infront == 3)
        return SIDE::CP_FRONT;

    return SIDE::CP_SPANNING;
}

bool Plane::intersect(glm::vec3* linestart, glm::vec3* lineend, glm::vec3* intersection, float* percentage) {

    glm::vec3 direction = (*lineend) - (*linestart);
    float linelength = glm::dot(direction, this->normal);
    if (fabsf(linelength) < 0.0001)
        return false;

    glm::vec3 L1 = this->point - (*linestart);

    float dist_from_plane = glm::dot(L1, this->normal);
    *percentage = dist_from_plane / linelength;

    if (*percentage < 0.0f)
        return false;
    else if (*percentage > 1.0f)
        return false;

    *intersection = (*linestart) + (direction * (*percentage));
    return true;
}

bool Plane::AABBBehind(const glm::vec3* AABBVertices) { return glm::dot(normal, AABBVertices[O]) < ND; }

float Plane::AABBDistance(const glm::vec3* AABBVertices) { return glm::dot(normal, AABBVertices[O]); }

} // namespace Chimera<commit_msg>matematica melhor no cliptest<commit_after>#include "chimera/render/Plane.hpp"
#include "chimera/render/VertexData.hpp"

namespace Chimera {
Plane::Plane() {}

Plane::Plane(const Plane& _cpy) {
    this->point = _cpy.point;
    this->normal = _cpy.normal;
    this->ND = _cpy.ND;
    this->O = _cpy.O;
}

Plane::Plane(const glm::vec3& _position, const glm::vec3& _normal) { this->set(_position, _normal); }

Plane::~Plane() {}

void Plane::set(const glm::vec3& pA, const glm::vec3& B, const glm::vec3& C) {
    point = pA;
    normal = glm::normalize(glm::cross(B - pA, C - pA));
    ND = dot(normal, pA);
    O = normal.z < 0.0f ? (normal.y < 0.0f ? (normal.x < 0.0f ? 0 : 1) : (normal.x < 0.0f ? 2 : 3))
                        : (normal.y < 0.0f ? (normal.x < 0.0f ? 4 : 5) : (normal.x < 0.0f ? 6 : 7));
}

void Plane::set(const glm::vec3& pA, const glm::vec3& _normal) {
    point = pA;       //_point->vertex[0].position;
    normal = _normal; //_point->normal();
    ND = dot(normal, pA);
    O = normal.z < 0.0f ? (normal.y < 0.0f ? (normal.x < 0.0f ? 0 : 1) : (normal.x < 0.0f ? 2 : 3))
                        : (normal.y < 0.0f ? (normal.x < 0.0f ? 4 : 5) : (normal.x < 0.0f ? 6 : 7));
}

SIDE Plane::classifyPoint(glm::vec3* point) {
    // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm
    glm::vec3 dir = this->point - (*point);
    float clipTest = glm::dot(dir, this->normal);

    if (fabs(clipTest) < EPSILON)
        SIDE::CP_ONPLANE;

    if (clipTest < 0.0f)
        return SIDE::CP_FRONT;

    return SIDE::CP_BACK;
}

SIDE Plane::classifyPoly(const glm::vec3& pA, const glm::vec3& pB, const glm::vec3& pC, glm::vec3* clipTest) {
    // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm
    unsigned short infront = 0;
    unsigned short behind = 0;
    unsigned short onPlane = 0;
    float result[3];

    result[0] = glm::dot((this->point - pA), this->normal); // Clip Test poin A
    result[1] = glm::dot((this->point - pB), this->normal); // Clip Test poin B
    result[2] = glm::dot((this->point - pC), this->normal); // Clip Test poin C

    for (unsigned short a = 0; a < 3; a++) {
        if (fabs(result[a]) < EPSILON) {
            result[a] = 0.0f;
            onPlane++;
            infront++;
            behind++;
        } else if (result[a] > 0.0f) {
            behind++;
        } else { // result[a] < 0.0f
            infront++;
        }
    }

    clipTest->x = result[0];
    clipTest->y = result[1];
    clipTest->z = result[2];

    if (onPlane == 3)
        return SIDE::CP_ONPLANE;

    if (behind == 3)
        return SIDE::CP_BACK;

    if (infront == 3)
        return SIDE::CP_FRONT;

    return SIDE::CP_SPANNING;
}

bool Plane::intersect(glm::vec3* linestart, glm::vec3* lineend, glm::vec3* intersection, float* percentage) {

    glm::vec3 direction = (*lineend) - (*linestart);
    float linelength = glm::dot(direction, this->normal);
    if (fabsf(linelength) < 0.0001)
        return false;

    glm::vec3 L1 = this->point - (*linestart);

    float dist_from_plane = glm::dot(L1, this->normal);
    *percentage = dist_from_plane / linelength;

    if (*percentage < 0.0f)
        return false;
    else if (*percentage > 1.0f)
        return false;

    *intersection = (*linestart) + (direction * (*percentage));
    return true;
}

bool Plane::AABBBehind(const glm::vec3* AABBVertices) { return glm::dot(normal, AABBVertices[O]) < ND; }

float Plane::AABBDistance(const glm::vec3* AABBVertices) { return glm::dot(normal, AABBVertices[O]); }

} // namespace Chimera<|endoftext|>


<commit_before><commit_msg>Make breakpad work in the seccomp sandbox. Take advantage of a feature in linux_syscall_support.h that allows us to mark all places where we embedd direct system calls. This allows the sandbox to rewrite them as needed.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove a DCHECK when failing to secure the shared memory used to hold the current version. This may well fail on older (read non-NTFS) systems since you can't secure file mappings without a securable file system underneath.<commit_after><|endoftext|>


<commit_before>/*
    Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>

    This file is part of Magnum.

    Magnum is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License version 3
    only, as published by the Free Software Foundation.

    Magnum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License version 3 for more details.
*/

#include "Object.h"

#include <stack>

#include "Scene.h"
#include "Camera.h"

using namespace std;
using namespace Magnum::Math;

namespace Magnum { namespace SceneGraph {

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> ObjectType* Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setParent(ObjectType* parent) {
    /* Skip if nothing to do or this is scene */
    if(_parent == parent || isScene()) return static_cast<ObjectType*>(this);

    /* Add the object to children list of new parent */
    if(parent != nullptr) {

        /* Only Fry can be his own grandfather */
        ObjectType* p = parent;
        while(p != nullptr) {
            if(p == this) return static_cast<ObjectType*>(this);
            p = p->parent();
        }

        parent->_children.insert(static_cast<ObjectType*>(this));
    }

    /* Remove the object from old parent children list */
    if(_parent != nullptr)
        _parent->_children.erase(static_cast<ObjectType*>(this));

    /* Set new parent */
    _parent = parent;

    setDirty();
    return static_cast<ObjectType*>(this);
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> MatrixType Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::absoluteTransformation(CameraType* camera) {
    /* Shortcut for absolute transformation of camera relative to itself */
    if(camera == this) return MatrixType();

    MatrixType t = _transformation;

    ObjectType* p = parent();
    while(p != nullptr) {
        t = p->transformation()*t;

        /* We got to the scene, multiply with camera matrix */
        if(p->isScene()) {
            if(camera) {
                CORRADE_ASSERT(camera->scene() == scene(), "Object::absoluteTransformation(): the camera is not part of the same scene as object!", t);
                t = camera->cameraMatrix()*t;
            }

            break;
        }

        p = p->parent();
    }

    CORRADE_ASSERT(p != nullptr || camera == nullptr, "Object::absoluteTransformation(): the object is not part of camera scene!", t);

    return t;
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::~Object() {
    /* Remove the object from parent's children */
    setParent(nullptr);

    /* Delete all children */
    while(!_children.empty())
        delete *_children.begin();
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> SceneType* Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::scene() {
    /* Goes up the family tree until it finds object which is parent of itself
       (that's the scene) */
    ObjectType* p = parent();
    while(p != nullptr) {
        if(p->isScene()) return static_cast<SceneType*>(p);
        p = p->parent();
    }

    return nullptr;
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> ObjectType* Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setTransformation(const MatrixType& transformation) {
    /* Setting transformation is forbidden for the scene */
    if(isScene()) return static_cast<ObjectType*>(this);

    _transformation = transformation;
    setDirty();
    return static_cast<ObjectType*>(this);
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> void Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setDirty() {
    /* The object (and all its children) are already dirty, nothing to do */
    if(dirty) return;

    dirty = true;

    /* Make all children dirty */
    for(typename set<ObjectType*>::iterator it = _children.begin(); it != _children.end(); ++it)
        (*it)->setDirty();
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> void Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setClean() {
    /* The object (and all its parents) are already clean, nothing to do */
    if(!dirty) return;

    /* Collect all parents */
    stack<ObjectType*> objects;
    ObjectType* p = static_cast<ObjectType*>(this);
    for(;;) {
        objects.push(p);

        /* Stop on root object / clean object */
        if(p->parent() == nullptr || !p->parent()->isDirty())
            break;

        p = p->parent();
    }

    /* Call setClean(const Matrix4&) for every parent and also this object */
    ObjectType* o = objects.top();
    objects.pop();
    MatrixType absoluteTransformation = o->absoluteTransformation();
    o->clean(absoluteTransformation);
    while(!objects.empty()) {
        o = objects.top();
        objects.pop();
        absoluteTransformation = absoluteTransformation*o->transformation();
        o->clean(absoluteTransformation);
    }
}

/* Explicitly instantiate the templates */
template class Object<Matrix3, Vector2, Object2D, Scene2D, Camera2D>;
template class Object<Matrix4, Vector3, Object3D, Scene3D, Camera3D>;

}}
<commit_msg>SceneGraph: Added @todos for some Object weirdness.<commit_after>/*
    Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>

    This file is part of Magnum.

    Magnum is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License version 3
    only, as published by the Free Software Foundation.

    Magnum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License version 3 for more details.
*/

#include "Object.h"

#include <stack>

#include "Scene.h"
#include "Camera.h"

using namespace std;
using namespace Magnum::Math;

namespace Magnum { namespace SceneGraph {

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> ObjectType* Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setParent(ObjectType* parent) {
    /* Skip if nothing to do or this is scene */
    if(_parent == parent || isScene()) return static_cast<ObjectType*>(this);

    /* Add the object to children list of new parent */
    if(parent != nullptr) {

        /* Only Fry can be his own grandfather */
        ObjectType* p = parent;
        while(p != nullptr) {
            /** @todo Assert for this */
            if(p == this) return static_cast<ObjectType*>(this);
            p = p->parent();
        }

        parent->_children.insert(static_cast<ObjectType*>(this));
    }

    /* Remove the object from old parent children list */
    if(_parent != nullptr)
        _parent->_children.erase(static_cast<ObjectType*>(this));

    /* Set new parent */
    _parent = parent;

    setDirty();
    return static_cast<ObjectType*>(this);
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> MatrixType Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::absoluteTransformation(CameraType* camera) {
    /* Shortcut for absolute transformation of camera relative to itself */
    if(camera == this) return MatrixType();

    MatrixType t = _transformation;

    ObjectType* p = parent();
    while(p != nullptr) {
        t = p->transformation()*t;

        /* We got to the scene, multiply with camera matrix */
        if(p->isScene()) {
            if(camera) {
                CORRADE_ASSERT(camera->scene() == scene(), "Object::absoluteTransformation(): the camera is not part of the same scene as object!", t);
                t = camera->cameraMatrix()*t;
            }

            break;
        }

        p = p->parent();
    }

    CORRADE_ASSERT(p != nullptr || camera == nullptr, "Object::absoluteTransformation(): the object is not part of camera scene!", t);

    return t;
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::~Object() {
    /* Remove the object from parent's children */
    setParent(nullptr);

    /* Delete all children */
    while(!_children.empty())
        delete *_children.begin();
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> SceneType* Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::scene() {
    /* Goes up the family tree until it finds object which is parent of itself
       (that's the scene) */
    ObjectType* p = parent();
    while(p != nullptr) {
        if(p->isScene()) return static_cast<SceneType*>(p);
        p = p->parent();
    }

    return nullptr;
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> ObjectType* Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setTransformation(const MatrixType& transformation) {
    /* Setting transformation is forbidden for the scene */
    /** @todo Assert for this? */
    if(isScene()) return static_cast<ObjectType*>(this);

    _transformation = transformation;
    setDirty();
    return static_cast<ObjectType*>(this);
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> void Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setDirty() {
    /* The object (and all its children) are already dirty, nothing to do */
    if(dirty) return;

    dirty = true;

    /* Make all children dirty */
    for(typename set<ObjectType*>::iterator it = _children.begin(); it != _children.end(); ++it)
        (*it)->setDirty();
}

template<class MatrixType, class VectorType, class ObjectType, class SceneType, class CameraType> void Object<MatrixType, VectorType, ObjectType, SceneType, CameraType>::setClean() {
    /* The object (and all its parents) are already clean, nothing to do */
    if(!dirty) return;

    /* Collect all parents */
    stack<ObjectType*> objects;
    ObjectType* p = static_cast<ObjectType*>(this);
    for(;;) {
        objects.push(p);

        /* Stop on root object / clean object */
        if(p->parent() == nullptr || !p->parent()->isDirty())
            break;

        p = p->parent();
    }

    /* Call setClean(const Matrix4&) for every parent and also this object */
    ObjectType* o = objects.top();
    objects.pop();
    MatrixType absoluteTransformation = o->absoluteTransformation();
    o->clean(absoluteTransformation);
    while(!objects.empty()) {
        o = objects.top();
        objects.pop();
        absoluteTransformation = absoluteTransformation*o->transformation();
        o->clean(absoluteTransformation);
    }
}

/* Explicitly instantiate the templates */
template class Object<Matrix3, Vector2, Object2D, Scene2D, Camera2D>;
template class Object<Matrix4, Vector3, Object3D, Scene3D, Camera3D>;

}}
<|endoftext|>


<commit_before>#include <stddef.h>
#include <stdlib.h>
#include <iostream>
#include "novoht.h"
#include <new>

int main (int argc, char ** argv){
   NoVoHT map("append.txt", 1000, -1);
   map.append("two","appone");
   map.append("two", "apptwo");
   map.append("two", "appthree");
   map.append("two", "appthree");
   map.append("two", "appthree");
   map.append("two", "appthree");
   map.append("two", "appthree");
   map.append("two", "appthree");
   map.append("two", "appthree");
   map.append("two", "appthree");
   map.append("two", "applast");
   map.append("three", "appthree");
   map.append("three", "appthree");
   map.append("three", "appthree");
   map.append("three", "appthree");
   map.append("three", "appthree");
   map.append("three", "appthree");
   map.append("three", "appthree");
   map.append("three", "applast");
   cout << map.getSize() << endl;

   return 0;
}
<commit_msg>Appendtest now performs benchmark of append operation.<commit_after>#include <stddef.h>
#include <stdlib.h>
#include <iostream>
#include "novoht.h"
#include <new>
#include <sys/time.h>

struct timeval tp;
double diffclock(clock_t clock1, clock_t clock2){
   double clock_ts=clock1-clock2;
   double diffms=(clock_ts*1000)/CLOCKS_PER_SEC;
   return diffms;
}
double getTime_usec() {
   gettimeofday(&tp, NULL);
   return static_cast<double>(tp.tv_sec) * 1E6+ static_cast<double>(tp.tv_usec);
}
int main (int argc, char ** argv){
   NoVoHT map("append.txt", atoi(argv[1])*2, -1);
   double a = getTime_usec();
   for (int i =0; i < atoi(argv[1])/2; i++){
      if (map.append("two","append") < 0)
         cerr << "Append Problem" << endl;
      if (map.append("three","Append") < 0)
         cerr << "Append Problem" << endl;
   }
   double b = getTime_usec();
   map.remove("two");
   map.remove("three");
   double c =getTime_usec();
   for (int i =0; i < atoi(argv[1]); i++){
      if (map.append("two","append") < 0)
         cerr << "Append Problem" << endl;
   }
   double d = getTime_usec();
   cout << "Alternating appends " << (b - a)/1E3 << " milliseconds" << endl;
   cout << "Consecutive appends " << (d - c)/1E3 << " milliseconds" << endl;

   return 0;
}
<|endoftext|>


<commit_before>/*
 * Co-created by Sidhujag & Saffroncoin Developer - Roshan
 * Syscoin Developers 2014
 */
#include "myaliaslistpage.h"
#include "ui_myaliaslistpage.h"
#include "aliastablemodel.h"
#include "clientmodel.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "bitcoingui.h"
#include "editaliasdialog.h"
#include "csvmodelwriter.h"
#include "guiutil.h"

#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
MyAliasListPage::MyAliasListPage(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MyAliasListPage),
    model(0),
    optionsModel(0)
{
    ui->setupUi(this);

#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
    ui->newAlias->setIcon(QIcon());
    ui->copyAlias->setIcon(QIcon());
    ui->exportButton->setIcon(QIcon());
#endif

	ui->buttonBox->setVisible(false);

    ui->labelExplanation->setText(tr("These are your registered Syscoin Aliases. New Syscoin Aliases take 120 confirmations to appear in this table. Alias updates take 1 confirmation to appear in this table.

Alias transfers require clicking refresh after 1 confirmation for the table to update."));

    // Context menu actions
    QAction *copyAliasAction = new QAction(ui->copyAlias->text(), this);
    QAction *copyAliasValueAction = new QAction(tr("Copy Va&lue"), this);
    QAction *editAction = new QAction(tr("&Edit"), this);
    QAction *transferAliasAction = new QAction(tr("&Transfer Alias"), this);

    // Build context menu
    contextMenu = new QMenu();
    contextMenu->addAction(copyAliasAction);
    contextMenu->addAction(copyAliasValueAction);
    contextMenu->addAction(editAction);
    contextMenu->addSeparator();
    contextMenu->addAction(transferAliasAction);

    // Connect signals for context menu actions
    connect(copyAliasAction, SIGNAL(triggered()), this, SLOT(on_copyAlias_clicked()));
    connect(copyAliasValueAction, SIGNAL(triggered()), this, SLOT(onCopyAliasValueAction()));
    connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
	connect(transferAliasAction, SIGNAL(triggered()), this, SLOT(onTransferAliasAction()));

    connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));

    // Pass through accept action from button box
    connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
}

MyAliasListPage::~MyAliasListPage()
{
    delete ui;
}
void MyAliasListPage::showEvent ( QShowEvent * event )
{
    if(!walletModel) return;
	if(walletModel->getEncryptionStatus() == WalletModel::Locked)
	{
        ui->labelExplanation->setText(tr("WARNING: Your wallet is currently locked. For security purposes you'll need to enter your passphrase in order to interact with Syscoin Aliases. Because your wallet is locked you must manually refresh this table after creating, updateing or transferring an Alias.  more info

These are your registered Syscoin Aliases. New Syscoin Aliases take 120 confirmations to appear in this table. Alias updates take 1 confirmation to appear in this table.

Alias transfers require clicking refresh after 1 confirmation for the table to update."));
		ui->labelExplanation->setTextFormat(Qt::RichText);
		ui->labelExplanation->setTextInteractionFlags(Qt::TextBrowserInteraction);
		ui->labelExplanation->setOpenExternalLinks(true);
	}
}
void MyAliasListPage::setModel(WalletModel *walletModel, AliasTableModel *model)
{
    this->model = model;
	this->walletModel = walletModel;
    if(!model) return;
    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(model);
    proxyModel->setDynamicSortFilter(true);
    proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

		// Receive filter
		proxyModel->setFilterRole(AliasTableModel::TypeRole);
		proxyModel->setFilterFixedString(AliasTableModel::Alias);

		ui->tableView->setModel(proxyModel);
		ui->tableView->sortByColumn(0, Qt::AscendingOrder);
        ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
        ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    // Set column widths
#if QT_VERSION < 0x050000
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::Name, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::Value, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::LastUpdateHeight, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::ExpiresOn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::ExpiresIn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::Expired, QHeaderView::ResizeToContents);
#else
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::Name, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::Value, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::LastUpdateHeight, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::ExpiresOn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::ExpiresIn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::Expired, QHeaderView::ResizeToContents);
#endif

    connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(selectionChanged()));

    // Select row for newly created alias
    connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAlias(QModelIndex,int,int)));

    selectionChanged();
}

void MyAliasListPage::setOptionsModel(ClientModel* clientmodel, OptionsModel *optionsModel)
{
    this->optionsModel = optionsModel;
	this->clientModel = clientmodel;
}

void MyAliasListPage::on_copyAlias_clicked()
{
    GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Name);
}

void MyAliasListPage::onCopyAliasValueAction()
{
    GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Value);
}

void MyAliasListPage::onEditAction()
{
    if(!ui->tableView->selectionModel())
        return;
    QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
    if(indexes.isEmpty())
        return;

    EditAliasDialog dlg(EditAliasDialog::EditAlias);
    dlg.setModel(walletModel, model);
    QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
    dlg.loadRow(origIndex.row());
    dlg.exec();
}

void MyAliasListPage::onTransferAliasAction()
{
    if(!ui->tableView->selectionModel())
        return;
    QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
    if(indexes.isEmpty())
        return;

    EditAliasDialog dlg(EditAliasDialog::TransferAlias);
    dlg.setModel(walletModel, model);
    QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
    dlg.loadRow(origIndex.row());
    dlg.exec();
}
void MyAliasListPage::on_refreshButton_clicked()
{
    if(!model)
        return;
    WalletModel::UnlockContext ctx(walletModel->requestUnlock());
    if(!ctx.isValid())
    {
        return;
    }
    model->refreshAliasTable();
}
void MyAliasListPage::on_newAlias_clicked()
{
    if(!model)
        return;

    EditAliasDialog dlg(EditAliasDialog::NewAlias, this);
    dlg.setModel(walletModel,model);
    if(dlg.exec())
    {
        newAliasToSelect = dlg.getAlias();
    }
}
void MyAliasListPage::selectionChanged()
{
    // Set button states based on selected tab and selection
    QTableView *table = ui->tableView;
    if(!table->selectionModel())
        return;

    if(table->selectionModel()->hasSelection())
    {
        ui->copyAlias->setEnabled(true);
    }
    else
    {
        ui->copyAlias->setEnabled(false);
    }
}

void MyAliasListPage::done(int retval)
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel() || !table->model())
        return;

    // Figure out which alias was selected, and return it
    QModelIndexList indexes = table->selectionModel()->selectedRows(AliasTableModel::Name);

    foreach (QModelIndex index, indexes)
    {
        QVariant alias = table->model()->data(index);
        returnValue = alias.toString();
    }

    if(returnValue.isEmpty())
    {
        // If no alias entry selected, return rejected
        retval = Rejected;
    }

    QDialog::done(retval);
}

void MyAliasListPage::on_exportButton_clicked()
{
    // CSV is currently the only supported format
    QString filename = GUIUtil::getSaveFileName(
            this,
            tr("Export Alias Data"), QString(),
            tr("Comma separated file (*.csv)"));

    if (filename.isNull()) return;

    CSVModelWriter writer(filename);

    // name, column, role
    writer.setModel(proxyModel);
    writer.addColumn("Alias", AliasTableModel::Name, Qt::EditRole);
    writer.addColumn("Value", AliasTableModel::Value, Qt::EditRole);
	writer.addColumn("Last Update", AliasTableModel::LastUpdateHeight, Qt::EditRole);
	writer.addColumn("Expires On", AliasTableModel::ExpiresOn, Qt::EditRole);
	writer.addColumn("Expires In", AliasTableModel::ExpiresIn, Qt::EditRole);
	writer.addColumn("Expired", AliasTableModel::Expired, Qt::EditRole);
    if(!writer.write())
    {
        QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
                              QMessageBox::Abort, QMessageBox::Abort);
    }
}

void MyAliasListPage::contextualMenu(const QPoint &point)
{
    QModelIndex index = ui->tableView->indexAt(point);
    if(index.isValid()) {
        contextMenu->exec(QCursor::pos());
    }
}

void MyAliasListPage::selectNewAlias(const QModelIndex &parent, int begin, int /*end*/)
{
    QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AliasTableModel::Name, parent));
    if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAliasToSelect))
    {
        // Select row of newly created alias, once
        ui->tableView->setFocus();
        ui->tableView->selectRow(idx.row());
        newAliasToSelect.clear();
    }
}
bool MyAliasListPage::handleURI(const QString& strURI)
{

    return false;
}
<commit_msg>Label Updates<commit_after>/*
 * Co-created by Sidhujag & Saffroncoin Developer - Roshan
 * Syscoin Developers 2014
 */
#include "myaliaslistpage.h"
#include "ui_myaliaslistpage.h"
#include "aliastablemodel.h"
#include "clientmodel.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "bitcoingui.h"
#include "editaliasdialog.h"
#include "csvmodelwriter.h"
#include "guiutil.h"

#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
MyAliasListPage::MyAliasListPage(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MyAliasListPage),
    model(0),
    optionsModel(0)
{
    ui->setupUi(this);

#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
    ui->newAlias->setIcon(QIcon());
    ui->copyAlias->setIcon(QIcon());
    ui->exportButton->setIcon(QIcon());
#endif

	ui->buttonBox->setVisible(false);

    ui->labelExplanation->setText(tr("These are your registered Syscoin Aliases. Alias updates take 1 confirmation to appear in this table. Alias transfers require clicking refresh after 1 confirmation for the table to update."));

    // Context menu actions
    QAction *copyAliasAction = new QAction(ui->copyAlias->text(), this);
    QAction *copyAliasValueAction = new QAction(tr("Copy Va&lue"), this);
    QAction *editAction = new QAction(tr("&Edit"), this);
    QAction *transferAliasAction = new QAction(tr("&Transfer Alias"), this);

    // Build context menu
    contextMenu = new QMenu();
    contextMenu->addAction(copyAliasAction);
    contextMenu->addAction(copyAliasValueAction);
    contextMenu->addAction(editAction);
    contextMenu->addSeparator();
    contextMenu->addAction(transferAliasAction);

    // Connect signals for context menu actions
    connect(copyAliasAction, SIGNAL(triggered()), this, SLOT(on_copyAlias_clicked()));
    connect(copyAliasValueAction, SIGNAL(triggered()), this, SLOT(onCopyAliasValueAction()));
    connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
	connect(transferAliasAction, SIGNAL(triggered()), this, SLOT(onTransferAliasAction()));

    connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));

    // Pass through accept action from button box
    connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
}

MyAliasListPage::~MyAliasListPage()
{
    delete ui;
}
void MyAliasListPage::showEvent ( QShowEvent * event )
{
    if(!walletModel) return;
	if(walletModel->getEncryptionStatus() == WalletModel::Locked)
	{
        ui->labelExplanation->setText(tr("WARNING: Your wallet is currently locked. For security purposes you'll need to enter your passphrase in order to interact with Syscoin Aliases. Because your wallet is locked you must manually refresh this table after creating, updateing or transferring an Alias.  more info

These are your registered Syscoin Aliases. Alias updates take 1 confirmation to appear in this table. Alias transfers require clicking refresh after 1 confirmation for the table to update."));
		ui->labelExplanation->setTextFormat(Qt::RichText);
		ui->labelExplanation->setTextInteractionFlags(Qt::TextBrowserInteraction);
		ui->labelExplanation->setOpenExternalLinks(true);
	}
}
void MyAliasListPage::setModel(WalletModel *walletModel, AliasTableModel *model)
{
    this->model = model;
	this->walletModel = walletModel;
    if(!model) return;
    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(model);
    proxyModel->setDynamicSortFilter(true);
    proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

		// Receive filter
		proxyModel->setFilterRole(AliasTableModel::TypeRole);
		proxyModel->setFilterFixedString(AliasTableModel::Alias);

		ui->tableView->setModel(proxyModel);
		ui->tableView->sortByColumn(0, Qt::AscendingOrder);
        ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
        ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    // Set column widths
#if QT_VERSION < 0x050000
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::Name, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::Value, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::LastUpdateHeight, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::ExpiresOn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::ExpiresIn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setResizeMode(AliasTableModel::Expired, QHeaderView::ResizeToContents);
#else
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::Name, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::Value, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::LastUpdateHeight, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::ExpiresOn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::ExpiresIn, QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(AliasTableModel::Expired, QHeaderView::ResizeToContents);
#endif

    connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(selectionChanged()));

    // Select row for newly created alias
    connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAlias(QModelIndex,int,int)));

    selectionChanged();
}

void MyAliasListPage::setOptionsModel(ClientModel* clientmodel, OptionsModel *optionsModel)
{
    this->optionsModel = optionsModel;
	this->clientModel = clientmodel;
}

void MyAliasListPage::on_copyAlias_clicked()
{
    GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Name);
}

void MyAliasListPage::onCopyAliasValueAction()
{
    GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Value);
}

void MyAliasListPage::onEditAction()
{
    if(!ui->tableView->selectionModel())
        return;
    QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
    if(indexes.isEmpty())
        return;

    EditAliasDialog dlg(EditAliasDialog::EditAlias);
    dlg.setModel(walletModel, model);
    QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
    dlg.loadRow(origIndex.row());
    dlg.exec();
}

void MyAliasListPage::onTransferAliasAction()
{
    if(!ui->tableView->selectionModel())
        return;
    QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
    if(indexes.isEmpty())
        return;

    EditAliasDialog dlg(EditAliasDialog::TransferAlias);
    dlg.setModel(walletModel, model);
    QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
    dlg.loadRow(origIndex.row());
    dlg.exec();
}
void MyAliasListPage::on_refreshButton_clicked()
{
    if(!model)
        return;
    WalletModel::UnlockContext ctx(walletModel->requestUnlock());
    if(!ctx.isValid())
    {
        return;
    }
    model->refreshAliasTable();
}
void MyAliasListPage::on_newAlias_clicked()
{
    if(!model)
        return;

    EditAliasDialog dlg(EditAliasDialog::NewAlias, this);
    dlg.setModel(walletModel,model);
    if(dlg.exec())
    {
        newAliasToSelect = dlg.getAlias();
    }
}
void MyAliasListPage::selectionChanged()
{
    // Set button states based on selected tab and selection
    QTableView *table = ui->tableView;
    if(!table->selectionModel())
        return;

    if(table->selectionModel()->hasSelection())
    {
        ui->copyAlias->setEnabled(true);
    }
    else
    {
        ui->copyAlias->setEnabled(false);
    }
}

void MyAliasListPage::done(int retval)
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel() || !table->model())
        return;

    // Figure out which alias was selected, and return it
    QModelIndexList indexes = table->selectionModel()->selectedRows(AliasTableModel::Name);

    foreach (QModelIndex index, indexes)
    {
        QVariant alias = table->model()->data(index);
        returnValue = alias.toString();
    }

    if(returnValue.isEmpty())
    {
        // If no alias entry selected, return rejected
        retval = Rejected;
    }

    QDialog::done(retval);
}

void MyAliasListPage::on_exportButton_clicked()
{
    // CSV is currently the only supported format
    QString filename = GUIUtil::getSaveFileName(
            this,
            tr("Export Alias Data"), QString(),
            tr("Comma separated file (*.csv)"));

    if (filename.isNull()) return;

    CSVModelWriter writer(filename);

    // name, column, role
    writer.setModel(proxyModel);
    writer.addColumn("Alias", AliasTableModel::Name, Qt::EditRole);
    writer.addColumn("Value", AliasTableModel::Value, Qt::EditRole);
	writer.addColumn("Last Update", AliasTableModel::LastUpdateHeight, Qt::EditRole);
	writer.addColumn("Expires On", AliasTableModel::ExpiresOn, Qt::EditRole);
	writer.addColumn("Expires In", AliasTableModel::ExpiresIn, Qt::EditRole);
	writer.addColumn("Expired", AliasTableModel::Expired, Qt::EditRole);
    if(!writer.write())
    {
        QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
                              QMessageBox::Abort, QMessageBox::Abort);
    }
}

void MyAliasListPage::contextualMenu(const QPoint &point)
{
    QModelIndex index = ui->tableView->indexAt(point);
    if(index.isValid()) {
        contextMenu->exec(QCursor::pos());
    }
}

void MyAliasListPage::selectNewAlias(const QModelIndex &parent, int begin, int /*end*/)
{
    QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AliasTableModel::Name, parent));
    if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAliasToSelect))
    {
        // Select row of newly created alias, once
        ui->tableView->setFocus();
        ui->tableView->selectRow(idx.row());
        newAliasToSelect.clear();
    }
}
bool MyAliasListPage::handleURI(const QString& strURI)
{

    return false;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2018 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 <qt/transactiondesc.h>

#include <qt/bitcoinunits.h>
#include <qt/guiutil.h>
#include <qt/paymentserver.h>
#include <qt/transactionrecord.h>

#include <consensus/consensus.h>
#include <interfaces/node.h>
#include <key_io.h>
#include <validation.h>
#include


<commit_before>#include "rdb_protocol/parser.hpp"

namespace rdb_protocol {

query_http_app_t::query_http_app_t(namespace_interface_t<rdb_protocol_t> * _namespace_if)
    : namespace_if(_namespace_if)
{ }

http_res_t query_http_app_t::handle(const http_req_t &req) {
    try {
        switch (req.method) {
        case GET:
            {
                rdb_protocol_t::read_t read;

                http_req_t::resource_t::iterator it = req.resource.begin();
                rassert(it != req.resource.end());

                store_key_t key(*it);
                read.read = rdb_protocol_t::point_read_t(key);
                cond_t cond;
                rdb_protocol_t::read_response_t read_res = namespace_if->read(read, order_source.check_in("dummy parser"), &cond);

                http_res_t res;

                rdb_protocol_t::point_read_response_t response = boost::get<rdb_protocol_t::point_read_response_t>(read_res.response);
                if (response.data) {
                    boost::scoped_ptr<char> json(cJSON_Print(response.data.get()->get()));
                    res.code = 200;
                    res.set_body("application/json", json.get());
                } else {
                    res.code = 404;
                }
                return res;
            }
            break;
        case PUT:
        case POST:
            {
                rdb_protocol_t::write_t write;

                rassert(req.resource.begin() == req.resource.end());

                cJSON *doc = cJSON_Parse(req.body.c_str());

                if (doc == NULL) {
                    return http_res_t(400);
                }

                cJSON *id = cJSON_GetObjectItem(doc, "id");

                if (id == NULL || id->type != cJSON_String) {
                    cJSON_Delete(doc);
                    return http_res_t(400);
                }

                store_key_t key(id->valuestring);
                write.write = rdb_protocol_t::point_write_t(key, boost::make_shared<scoped_cJSON_t>(doc));

                cond_t cond;
                rdb_protocol_t::write_response_t write_res = namespace_if->write(write, order_source.check_in("dummy parser"), &cond);

                return http_res_t(204);
            }
            break;

        case HEAD:
        case DELETE:
        case TRACE:
        case OPTIONS:
        case CONNECT:
        case PATCH:
        default:
            return http_res_t(400);
        }
        crash("Unreachable\n");
    } catch(cannot_perform_query_exc_t e) {
        http_res_t res;
        res.set_body("text/plain", e.what());
        return http_res_t(500);
    }
}

} //namespace mock
<commit_msg>Undid the changes made by last commit.<commit_after>#include "rdb_protocol/parser.hpp"

namespace rdb_protocol {

query_http_app_t::query_http_app_t(namespace_interface_t<rdb_protocol_t> * _namespace_if)
    : namespace_if(_namespace_if)
{ }

http_res_t query_http_app_t::handle(const http_req_t &req) {
    try {
        switch (req.method) {
        case GET:
            {
                rdb_protocol_t::read_t read;

                http_req_t::resource_t::iterator it = req.resource.begin();
                rassert(it != req.resource.end());

                store_key_t key(*it);
                read.read = rdb_protocol_t::point_read_t(key);
                cond_t cond;
                rdb_protocol_t::read_response_t read_res = namespace_if->read(read, order_source.check_in("dummy parser"), &cond);

                http_res_t res;

                rdb_protocol_t::point_read_response_t response = boost::get<rdb_protocol_t::point_read_response_t>(read_res.response);
                if (response.data) {
                    boost::scoped_ptr<char> json(cJSON_Print(response.data.get()->get()));
                    res.code = 200;
                    res.set_body("application/json", json.get());
                } else {
                    res.code = 404;
                }
                return res;
            }
            break;
        case PUT:
        case POST:
            {
                rdb_protocol_t::write_t write;

                rassert(req.resource.begin() == req.resource.end());

                cJSON *doc = cJSON_Parse(req.body.c_str());

                if (doc == NULL) {
                    return http_res_t(400);
                }

                cJSON *id = cJSON_GetObjectItem(doc, "id");

                if (id == NULL || id->type != cJSON_String) {
                    cJSON_Delete(doc);
                    return http_res_t(400);
                }

                store_key_t key(id->valuestring);
                write.write = rdb_protocol_t::point_write_t(key, boost::make_shared<scoped_cJSON_t>(doc));

                cond_t cond;
                rdb_protocol_t::write_response_t write_res = namespace_if->write(write, order_source.check_in("dummy parser"), &cond);

                return http_res_t(204);
            }
            break;

        default:
            return http_res_t(400);
        }
        crash("Unreachable\n");
    } catch(cannot_perform_query_exc_t e) {
        http_res_t res;
        res.set_body("text/plain", e.what());
        return http_res_t(500);
    }
}

} //namespace mock
<|endoftext|>


<commit_before>/*
 *
 * Copyright (c) 2013, Ford Motor Company
 * 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 Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "transport_manager/bluetooth/bluetooth_socket_connection.h"

#include <unistd.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include <bluetooth/rfcomm.h>

#include "transport_manager/bluetooth/bluetooth_device.h"
#include "transport_manager/transport_adapter/transport_adapter_controller.h"

#include "utils/logger.h"

namespace transport_manager {
namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")

BluetoothSocketConnection::BluetoothSocketConnection(
  const DeviceUID& device_uid, const ApplicationHandle& app_handle,
  TransportAdapterController* controller)
  : ThreadedSocketConnection(device_uid, app_handle, controller) {
}

BluetoothSocketConnection::~BluetoothSocketConnection() {
}

bool BluetoothSocketConnection::Establish(ConnectError** error) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "error: " << error);
  DeviceSptr device = controller()->FindDevice(device_handle());

  BluetoothDevice* bluetooth_device =
    static_cast<BluetoothDevice*>(device.get());

  uint8_t rfcomm_channel;
  if (!bluetooth_device->GetRfcommChannel(application_handle(),
                                          &rfcomm_channel)) {
    LOG4CXX_DEBUG(logger_,
                   "Application " << application_handle() << " not found");
    *error = new ConnectError();
    LOG4CXX_TRACE(logger_, "exit with FALSE");
    return false;
  }

  struct sockaddr_rc remoteSocketAddress = { 0 };
  remoteSocketAddress.rc_family = AF_BLUETOOTH;
  memcpy(&remoteSocketAddress.rc_bdaddr, &bluetooth_device->address(),
         sizeof(bdaddr_t));
  remoteSocketAddress.rc_channel = rfcomm_channel;

  int rfcomm_socket;

  int attempts = 4;
  int connect_status = 0;
  LOG4CXX_DEBUG(logger_, "start rfcomm Connect attempts");
  do {
    rfcomm_socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    if (-1 == rfcomm_socket) {
      LOG4CXX_ERROR_WITH_ERRNO(logger_,
                               "Failed to create RFCOMM socket for device " << device_handle());
      *error = new ConnectError();
      LOG4CXX_TRACE(logger_, "exit with FALSE");
      return false;
    }
    connect_status = ::connect(rfcomm_socket,
                               (struct sockaddr*) &remoteSocketAddress,
                               sizeof(remoteSocketAddress));
    if (0 == connect_status) {
      LOG4CXX_DEBUG(logger_, "rfcomm Connect ok");
      break;
    }
    if (errno != 111 && errno != 104) {
      LOG4CXX_DEBUG(logger_, "rfcomm Connect errno " << errno);
      break;
    }
    if (errno) {
      LOG4CXX_DEBUG(logger_, "rfcomm Connect errno " << errno);
      close(rfcomm_socket);
    }
    sleep(2);
  } while (--attempts > 0);
  LOG4CXX_INFO(logger_, "rfcomm Connect attempts finished");
  if (0 != connect_status) {
    LOG4CXX_DEBUG(logger_,
                  "Failed to Connect to remote device " << BluetoothDevice::GetUniqueDeviceId(
                    remoteSocketAddress.rc_bdaddr) << " for session " << this);
    *error = new ConnectError();
    LOG4CXX_TRACE(logger_, "exit with FALSE");
    return false;
  }

  set_socket(rfcomm_socket);
  LOG4CXX_TRACE(logger_, "exit with TRUE");
  return true;
}

}  // namespace transport_adapter
}  // namespace transport_manager
<commit_msg>Close socket connection before returning from function (CID 80039)<commit_after>/*
 *
 * Copyright (c) 2013, Ford Motor Company
 * 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 Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "transport_manager/bluetooth/bluetooth_socket_connection.h"

#include <unistd.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include <bluetooth/rfcomm.h>

#include "transport_manager/bluetooth/bluetooth_device.h"
#include "transport_manager/transport_adapter/transport_adapter_controller.h"

#include "utils/logger.h"

namespace transport_manager {
namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")

BluetoothSocketConnection::BluetoothSocketConnection(
  const DeviceUID& device_uid, const ApplicationHandle& app_handle,
  TransportAdapterController* controller)
  : ThreadedSocketConnection(device_uid, app_handle, controller) {
}

BluetoothSocketConnection::~BluetoothSocketConnection() {
}

bool BluetoothSocketConnection::Establish(ConnectError** error) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "error: " << error);
  DeviceSptr device = controller()->FindDevice(device_handle());

  BluetoothDevice* bluetooth_device =
    static_cast<BluetoothDevice*>(device.get());

  uint8_t rfcomm_channel;
  if (!bluetooth_device->GetRfcommChannel(application_handle(),
                                          &rfcomm_channel)) {
    LOG4CXX_DEBUG(logger_,
                   "Application " << application_handle() << " not found");
    *error = new ConnectError();
    LOG4CXX_TRACE(logger_, "exit with FALSE");
    return false;
  }

  struct sockaddr_rc remoteSocketAddress = { 0 };
  remoteSocketAddress.rc_family = AF_BLUETOOTH;
  memcpy(&remoteSocketAddress.rc_bdaddr, &bluetooth_device->address(),
         sizeof(bdaddr_t));
  remoteSocketAddress.rc_channel = rfcomm_channel;

  int rfcomm_socket;

  int attempts = 4;
  int connect_status = 0;
  LOG4CXX_DEBUG(logger_, "start rfcomm Connect attempts");
  do {
    rfcomm_socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    if (-1 == rfcomm_socket) {
      LOG4CXX_ERROR_WITH_ERRNO(logger_,
                               "Failed to create RFCOMM socket for device " << device_handle());
      *error = new ConnectError();
      LOG4CXX_TRACE(logger_, "exit with FALSE");
      return false;
    }
    connect_status = ::connect(rfcomm_socket,
                               (struct sockaddr*) &remoteSocketAddress,
                               sizeof(remoteSocketAddress));
    if (0 == connect_status) {
      LOG4CXX_DEBUG(logger_, "rfcomm Connect ok");
      break;
    }
    if (errno != 111 && errno != 104) {
      LOG4CXX_DEBUG(logger_, "rfcomm Connect errno " << errno);
      break;
    }
    if (errno) {
      LOG4CXX_DEBUG(logger_, "rfcomm Connect errno " << errno);
      close(rfcomm_socket);
    }
    sleep(2);
  } while (--attempts > 0);
  LOG4CXX_INFO(logger_, "rfcomm Connect attempts finished");
  if (0 != connect_status) {
    LOG4CXX_DEBUG(logger_,
                  "Failed to Connect to remote device " << BluetoothDevice::GetUniqueDeviceId(
                    remoteSocketAddress.rc_bdaddr) << " for session " << this);
    *error = new ConnectError();
    close(rfcomm_socket);
    LOG4CXX_TRACE(logger_, "exit with FALSE");
    return false;
  }

  set_socket(rfcomm_socket);
  LOG4CXX_TRACE(logger_, "exit with TRUE");
  return true;
}

}  // namespace transport_adapter
}  // namespace transport_manager
<|endoftext|>


<commit_before>/*

 [TridentTD] : MANABU's Esp8266 IoT Library
 www.facebook.com/miniNodeMCU

 TridentTD_Ubidots.cpp - A simple client for UBIDOTS

 20/06/2559 Buddism Era  (2016)

Copyright (c) 2016 TridentTD

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 "TridentTD_Ubidots.h"

/**
 * Constructor.
 */
TridentTD_Ubidots::TridentTD_Ubidots(char* token){
    _token = token;
    maxValues       = 10;  //
    currentValue    = 0;
    _variable_count = 30;

    val        = (Value *)malloc(maxValues*sizeof(Value));
    ubidotsVar = (Variable *)malloc(_variable_count*sizeof(Variable));
}

bool TridentTD_Ubidots::loadAll(){
  if(WiFi.status() != WL_CONNECTED){ return -1; }

  float num;
  String response;
  int start_idx;
  int end_idx;

  //------------ Ubidots API ----------------------------
  String url = "http://things.ubidots.com/api/v1.6/variables/";
         url += "?token=";
         url += _token;
  _http.begin(url);

  int httpCode = _http.GET();
  if(httpCode > 0) {
      //DEBUG_PRINT("[UBIDOTS] http code: "); DEBUG_PRINTLN(httpCode);
      // file found at server
      if(httpCode == HTTP_CODE_OK) {
          String payload = _http.getString();
          DEBUG_PRINTLN(payload);

          _http.end();

          _variable_count = payload.substring( 9+ payload.indexOf("\"count\":"), payload.indexOf(", \"next\"")).toInt();

          DEBUG_PRINTLN(_variable_count);

          int start_idx = 12+ payload.indexOf("\"results\":");
          for(byte i =0; i < _variable_count ; i++){
            int end_idx = payload.indexOf("{\"id\":", payload.indexOf("\"derived_expr\":" , start_idx) );
            String variable_json = payload.substring(start_idx,end_idx);

			DEBUG_PRINTLN(variable_json);
            start_idx = end_idx;

            (ubidotsVar+i)->variable_id   = variable_json.substring( 8+ variable_json.indexOf("{\"id\": \""),  variable_json.indexOf("\", \"name\""));
            (ubidotsVar+i)->variable_name = variable_json.substring( 9+ variable_json.indexOf("\"name\": \""), variable_json.indexOf("\", \"icon\""));
            (ubidotsVar+i)->timestamp     = variable_json.substring( 28+ variable_json.indexOf("\"last_value\": {\"timestamp\":"), variable_json.indexOf("\", \"value\"")).toFloat();
            (ubidotsVar+i)->last_value    = variable_json.substring( 9+ variable_json.indexOf( "\"value\":" , variable_json.indexOf("\"last_value\": {\"timestamp\":")), variable_json.indexOf("\", \"context\"")).toFloat();

            DEBUG_PRINTLN((ubidotsVar+i)->variable_id);
            DEBUG_PRINTLN((ubidotsVar+i)->variable_name);
            DEBUG_PRINTLN((ubidotsVar+i)->timestamp);
            DEBUG_PRINTLN((ubidotsVar+i)->last_value);
          }

          return true;
      }
  } else {
      DEBUG_PRINT("[HTTP] GET... failed, error: "); DEBUG_PRINTLN(_http.errorToString(httpCode).c_str());
      _http.end();
      return false;
  }
}

float TridentTD_Ubidots::getValue(String variable_name){
  if(WiFi.status() != WL_CONNECTED){ return -10000; }

  float num;
  String response;
  int start_idx;
  int end_idx;

  String variable_id = "";

  for(byte i =0; i < _variable_count ; i++){
    if((ubidotsVar+i)->variable_name == variable_name ) {
      variable_id = ((ubidotsVar+i)->variable_id);
    }
  }

  if(variable_id == "") {
	Serial.println("[Ubidots] "+variable_name+" Not Found");
	return -10002;
  }

  //------------ Ubidots API ----------------------------
  String url = "http://things.ubidots.com/api/v1.6/variables/";
         url += variable_id;
         url += "/values/?page_size=1&token=";
         url += _token;
  _http.begin(url);

  int httpCode = _http.GET();
  if(httpCode > 0) {
      //DEBUG_PRINT("[UBIDOTS] http code: "); DEBUG_PRINTLN(httpCode);
      // file found at server
      if(httpCode == HTTP_CODE_OK) {
          String payload = _http.getString();
          _http.end();

          //DEBUG_PRINTLN(payload);
          start_idx = 9+ payload.indexOf("\"value\":");
          end_idx   = payload.indexOf(", \"timestamp\"");
          num       = payload.substring(start_idx,end_idx).toFloat();

          //DEBUG_PRINTLN("[UBIDOTS] variable_id : "+ String(variable_id) + ";value : "+payload.substring(start_idx,end_idx));
          return num;
      }
  } else {
      //DEBUG_PRINT("[HTTP] GET... failed, error: "); DEBUG_PRINTLN(_http.errorToString(httpCode).c_str());
      _http.end();
      return -10001;
  }
}

void TridentTD_Ubidots::setValue(String variable_name, double value){
  uint8_t i;
  int8_t variable_idx = -1;

  String variable_id = "";
  for(byte i =0; i < _variable_count ; i++){
    if((ubidotsVar+i)->variable_name == variable_name ) {
      variable_id = ((ubidotsVar+i)->variable_id);
    }
  }
  if(variable_id == "") { return; }

  for(i=0; i<= currentValue; i++){
    if( (val+i)->variable_id == variable_id) { variable_idx = i; }
  }
  if(variable_idx == -1) {
    (val+currentValue)->variable_id = variable_id;
    (val+currentValue)->value_id = value;
    currentValue++;
  }else{
    (val+variable_idx)->variable_id = variable_id;
    (val+variable_idx)->value_id = value;
  }

  if(currentValue>maxValues){
    Serial.println(F("You are sending more than 5 consecutives variables, you just could send 5 variables. Then other variables will be deleted!"));
    currentValue = maxValues;
  }
}

bool TridentTD_Ubidots::sendAll(){
    int i;
    String allvalues;
    String str;
    allvalues = "[";
    for(i=0; i<currentValue;){
        str = String(((val+i)->value_id),5);
        allvalues += "{\"variable\": \"";
        allvalues += String((val + i)->variable_id);
        allvalues += "\", \"value\":";
        allvalues += str;
        allvalues += "}";
        i++;
        if(i<currentValue){
            allvalues += ", ";
        }
    }
    allvalues += "]";
    i = allvalues.length();

    currentValue=1;  // reset ตัวแปร value

    DEBUG_PRINTLN("[UBIDOTS] allvalues : " +allvalues);

  //------------ Ubidots API ----------------------------
  String url = "http://things.ubidots.com/api/v1.6/collections/values/?token=";
         url += _token;
  _http.begin(url);
  _http.addHeader("Content-Type","application/json");

  int httpCode = _http.POST(allvalues);
  if(httpCode > 0) {
      //DEBUG_PRINT("[UBIDOTS] http code: "); DEBUG_PRINTLN(httpCode);
      // file found at server
      if(httpCode == HTTP_CODE_OK) {
          String payload = _http.getString();
          _http.end();

          DEBUG_PRINTLN("[UBIDOTS] return    : " + payload);
          return true;
      }
  } else {
      DEBUG_PRINT("[HTTP] GET... failed, error: "); DEBUG_PRINTLN(_http.errorToString(httpCode).c_str());
      _http.end();
      return -1;
  }

}

bool TridentTD_Ubidots::wificonnect(char* ssid, char* pass){
  WiFi.begin(ssid, pass);

  Serial.println();
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
}

String TridentTD_Ubidots::getVersion(){
  return _version;
}<commit_msg>Update TridentTD_Ubidots.cpp<commit_after>/*

 [TridentTD] : MANABU's Esp8266 IoT Library
 www.facebook.com/miniNodeMCU

 TridentTD_Ubidots.cpp - A simple client for UBIDOTS

 20/06/2559 Buddism Era  (2016)

Copyright (c) 2016 TridentTD

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 "TridentTD_Ubidots.h"

/**
 * Constructor.
 */
TridentTD_Ubidots::TridentTD_Ubidots(char* token){
    _token = token;
    maxValues       = 10;  //
    currentValue    = 0;
    _variable_count = 30;

    val        = (Value *)malloc(maxValues*sizeof(Value));
    ubidotsVar = (Variable *)malloc(_variable_count*sizeof(Variable));
}

bool TridentTD_Ubidots::loadAll(){
  if(WiFi.status() != WL_CONNECTED){ return -1; }

  float num;
  String response;
  int start_idx;
  int end_idx;

  //------------ Ubidots API ----------------------------
  String url = "http://things.ubidots.com/api/v1.6/variables/";
         url += "?token=";
         url += _token;
  _http.begin(url);

  int httpCode = _http.GET();
  if(httpCode > 0) {
      //DEBUG_PRINT("[UBIDOTS] http code: "); DEBUG_PRINTLN(httpCode);
      // file found at server
      if(httpCode == HTTP_CODE_OK) {
          String payload = _http.getString();
          DEBUG_PRINTLN(payload);

          _http.end();

          _variable_count = payload.substring( 9+ payload.indexOf("\"count\":"), payload.indexOf(", \"next\"")).toInt();

          DEBUG_PRINTLN(_variable_count);

          int start_idx = 12+ payload.indexOf("\"results\":");
          for(byte i =0; i < _variable_count ; i++){
            int end_idx = payload.indexOf("{\"id\":", payload.indexOf("\"derived_expr\":" , start_idx) );
            String variable_json = payload.substring(start_idx,end_idx);

			DEBUG_PRINTLN(variable_json);
            start_idx = end_idx;

            (ubidotsVar+i)->variable_id   = variable_json.substring( 8+ variable_json.indexOf("{\"id\": \""),  variable_json.indexOf("\", \"name\""));
            (ubidotsVar+i)->variable_name = variable_json.substring( 9+ variable_json.indexOf("\"name\": \""), variable_json.indexOf("\", \"icon\""));
            (ubidotsVar+i)->timestamp     = variable_json.substring( 28+ variable_json.indexOf("\"last_value\": {\"timestamp\":"), variable_json.indexOf("\", \"value\"")).toFloat();
            (ubidotsVar+i)->last_value    = variable_json.substring( 9+ variable_json.indexOf( "\"value\":" , variable_json.indexOf("\"last_value\": {\"timestamp\":")), variable_json.indexOf("\", \"context\"")).toFloat();

            DEBUG_PRINTLN((ubidotsVar+i)->variable_id);
            DEBUG_PRINTLN((ubidotsVar+i)->variable_name);
            DEBUG_PRINTLN((ubidotsVar+i)->timestamp);
            DEBUG_PRINTLN((ubidotsVar+i)->last_value);
          }

          return true;
      }
  } else {
      DEBUG_PRINT("[HTTP] GET... failed, error: "); DEBUG_PRINTLN(_http.errorToString(httpCode).c_str());
      _http.end();
      return false;
  }
}

float TridentTD_Ubidots::getValue(String variable_name){
  if(WiFi.status() != WL_CONNECTED){ return -10000; }

  float num;
  String response;
  int start_idx;
  int end_idx;

  String variable_id = "";

  for(byte i =0; i < _variable_count ; i++){
    if((ubidotsVar+i)->variable_name == variable_name ) {
      variable_id = ((ubidotsVar+i)->variable_id);
    }
  }

  if(variable_id == "") {
	Serial.println("[Ubidots] "+variable_name+" Not Found");
	return -10002;
  }

  //------------ Ubidots API ----------------------------
  String url = "http://things.ubidots.com/api/v1.6/variables/";
         url += variable_id;
         url += "/values/?page_size=1&token=";
         url += _token;
  _http.begin(url);

  int httpCode = _http.GET();
  if(httpCode > 0) {
      //DEBUG_PRINT("[UBIDOTS] http code: "); DEBUG_PRINTLN(httpCode);
      // file found at server
      if(httpCode == HTTP_CODE_OK) {
          String payload = _http.getString();
          _http.end();

          //DEBUG_PRINTLN(payload);
          start_idx = 9+ payload.indexOf("\"value\":");
          end_idx   = payload.indexOf(", \"timestamp\"");
          num       = payload.substring(start_idx,end_idx).toFloat();

          //DEBUG_PRINTLN("[UBIDOTS] variable_id : "+ String(variable_id) + ";value : "+payload.substring(start_idx,end_idx));
          return num;
      }
  } else {
      //DEBUG_PRINT("[HTTP] GET... failed, error: "); DEBUG_PRINTLN(_http.errorToString(httpCode).c_str());
      _http.end();
      return -10001;
  }
}

void TridentTD_Ubidots::setValue(String variable_name, double value){
  uint8_t i;
  int8_t variable_idx = -1;

  String variable_id = "";
  for(byte i =0; i < _variable_count ; i++){
    if((ubidotsVar+i)->variable_name == variable_name ) {
      variable_id = ((ubidotsVar+i)->variable_id);
    }
  }
  if(variable_id == "") { return; }

  for(i=0; i<= currentValue; i++){
    if( (val+i)->variable_id == variable_id) { variable_idx = i; }
  }
  if(variable_idx == -1) {
    (val+currentValue)->variable_id = variable_id;
    (val+currentValue)->value_id = value;
    currentValue++;
  }else{
    (val+variable_idx)->variable_id = variable_id;
    (val+variable_idx)->value_id = value;
  }

  if(currentValue>maxValues){
    Serial.println(F("You are sending more than 5 consecutives variables, you just could send 10 variables. Then other variables will be deleted!"));
    currentValue = maxValues;
  }
}

bool TridentTD_Ubidots::sendAll(){
    int i;
    String allvalues;
    String str;
    allvalues = "[";
    for(i=0; i<currentValue;){
        str = String(((val+i)->value_id),5);
        allvalues += "{\"variable\": \"";
        allvalues += String((val + i)->variable_id);
        allvalues += "\", \"value\":";
        allvalues += str;
        allvalues += "}";
        i++;
        if(i<currentValue){
            allvalues += ", ";
        }
    }
    allvalues += "]";
    i = allvalues.length();

    currentValue=1;  // reset ตัวแปร value

    DEBUG_PRINTLN("[UBIDOTS] allvalues : " +allvalues);

  //------------ Ubidots API ----------------------------
  String url = "http://things.ubidots.com/api/v1.6/collections/values/?token=";
         url += _token;
  _http.begin(url);
  _http.addHeader("Content-Type","application/json");

  int httpCode = _http.POST(allvalues);
  if(httpCode > 0) {
      //DEBUG_PRINT("[UBIDOTS] http code: "); DEBUG_PRINTLN(httpCode);
      // file found at server
      if(httpCode == HTTP_CODE_OK) {
          String payload = _http.getString();
          _http.end();

          DEBUG_PRINTLN("[UBIDOTS] return    : " + payload);
          return true;
      }
  } else {
      DEBUG_PRINT("[HTTP] GET... failed, error: "); DEBUG_PRINTLN(_http.errorToString(httpCode).c_str());
      _http.end();
      return -1;
  }

}

bool TridentTD_Ubidots::wificonnect(char* ssid, char* pass){
  WiFi.begin(ssid, pass);

  Serial.println();
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
}

String TridentTD_Ubidots::getVersion(){
  return _version;
}
<|endoftext|>


<commit_before>#include "rendering/object3d.h"

void Object3D::setSimpleDirection(const glm::vec3 &dir){
    glm::mat4 rotmat;
    rotmat[0] = vec4(glm::normalize(glm::cross(dir,vec3(0,1,0))),0);
    rotmat[1] = vec4(0,1,0,0);
    rotmat[2] = vec4(-dir,0);

    this->rot = glm::normalize(glm::quat(rotmat));

//    calculateModel();
}

void Object3D::turn(float angleX, float angleY){
    rotateGlobal(vec3(0,1,0),angleX);
    mat4 modeltmp = model;
    rotateLocal(vec3(1,0,0),angleY);
    if (model[1][1] < 0){
        model = modeltmp;
    }
//    calculateModel();

//    std::cout<<this->getDirection()<<" "<<(rot*vec4(0,0,1,0))<<std::endl;
//    std::cout<<this->getRightVector()<<" "<<(rot*vec4(1,0,0,0))<<std::endl;
//    std::cout<<this->getUpVector()<<" "<<(rot*vec4(0,1,0,0))<<std::endl;
}

void Object3D::rotateAroundPoint(const glm::vec3& point, const glm::vec3& axis, float angle){
    rotateLocal(axis,angle);

    translateGlobal(-point);
    mat4 rot = glm::rotate(mat4(),degreesToRadians(angle),axis);
    position = vec3(rot*vec4(position,1));
    translateGlobal(point);
}

<commit_msg>object3d<commit_after>#include "rendering/object3d.h"

void Object3D::setSimpleDirection(const glm::vec3 &dir){
    glm::mat4 rotmat;
    rotmat[0] = vec4(glm::normalize(glm::cross(dir,vec3(0,1,0))),0);
    rotmat[1] = vec4(0,1,0,0);
    rotmat[2] = vec4(-dir,0);

    this->rot = glm::normalize(glm::quat(rotmat));

//    calculateModel();
}

void Object3D::turn(float angleX, float angleY){
    rotateGlobal(vec3(0,1,0),angleX);
    mat4 modeltmp = model;
    rotateLocal(vec3(1,0,0),angleY);
    if (model[1][1] < 0){
        model = modeltmp;
    }
//    calculateModel();

//    std::cout<<this->getDirection()<<" "<<(rot*vec4(0,0,1,0))<<std::endl;
//    std::cout<<this->getRightVector()<<" "<<(rot*vec4(1,0,0,0))<<std::endl;
//    std::cout<<this->getUpVector()<<" "<<(rot*vec4(0,1,0,0))<<std::endl;
}

void Object3D::rotateAroundPoint(const glm::vec3& point, const glm::vec3& axis, float angle){
    rotateLocal(axis,angle);

    translateGlobal(-point);
    quat qrot = glm::angleAxis(degreesToRadians(angle),axis);
    position = vec3(qrot*vec4(position,1));
    translateGlobal(point);
}

<|endoftext|>


<commit_before>/* Luwra
 * Minimal-overhead Lua wrapper for C++
 *
 * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
 */

#ifndef LUWRA_USERTYPES_H_
#define LUWRA_USERTYPES_H_

#include "common.hpp"
#include "types.hpp"
#include "stack.hpp"
#include "functions.hpp"

#include <map>

LUWRA_NS_BEGIN

namespace internal {
	using UserTypeID = const void*;

	template <typename T>
	using StripUserType = std::remove_cv_t<T>;

	/**
	 * User type identifier
	 */
	template <typename T> extern
	const UserTypeID user_type_id = (void*) INTPTR_MAX;

	/**
	 * Registry name for a metatable which is associated with a user type
	 */
	template <typename T> extern
	const std::string user_type_reg_name =
		"UD#" + std::to_string(uintptr_t(&user_type_id<StripUserType<T>>));

	/**
	 * Register a new metatable for a user type T.
	 */
	template <typename U> static inline
	void new_user_type_metatable(State* state) {
		using T = StripUserType<U>;
		luaL_newmetatable(state, user_type_reg_name<T>.c_str());
	}

	/**
	 * Check if the value at the given index if a user type T.
	 */
	template <typename U> static inline
	StripUserType<U>* check_user_type(State* state, int index) {
		using T = StripUserType<U>;

		return static_cast<T*>(luaL_checkudata(state, index, user_type_reg_name<T>.c_str()));
	}

	/**
	 * Apply U's metatable for the value at the top of the stack.
	 */
	template <typename U> static inline
	void apply_user_type_meta_table(State* state) {
		using T = StripUserType<U>;

		luaL_getmetatable(state, user_type_reg_name<T>.c_str());
		lua_setmetatable(state, -2);
	}

	/**
	 * Lua C function to construct a user type T with parameters A
	 */
	template <typename U, typename... A> static inline
	int construct_user_type(State* state) {
		return internal::Layout<int(A...)>::direct(
			state,
			1,
			&Value<StripUserType<U>&>::template push<A...>,
			state
		);
	}

	/**
	 * Lua C function to destruct a user type T
	 */
	template <typename U> static inline
	int destruct_user_type(State* state) {
		using T = StripUserType<U>;

		if (!lua_islightuserdata(state, 1))
			Value<T&>::read(state, 1).~T();

		return 0;
	}

	/**
	 * Create a string representation for user type T.
	 */
	template <typename U> static
	int stringify_user_type(State* state) {
		using T = StripUserType<U>;

		return Value<std::string>::push(
			state,
			internal::user_type_reg_name<T>
				+ "@"
				+ std::to_string(uintptr_t(Value<T*>::read(state, 1)))
		);
	}

	/**
	 * Helper struct for wrapping user type fields
	 */
	template <typename U, typename R>
	struct FieldWrapper {
		using T = StripUserType<U>;

		template <R T::* field_pointer> static inline
		int invoke(State* state) {
			if (lua_gettop(state) > 1) {
				// Setter
				Value<T*>::read(state, 1)->*field_pointer = Value<R>::read(state, 2);
				return 0;
			} else {
				// Getter
				return push(state, Value<T*>::read(state, 1)->*field_pointer);
			}
		}
	};

	// 'const'-qualified fields
	template <typename U, typename R>
	struct FieldWrapper<U, const R> {
		using T = StripUserType<U>;

		template <const R T::* field_pointer> static inline
		int invoke(State* state) {
			return push(state, Value<T*>::read(state, 1)->*field_pointer);
		}
	};

	template <typename T>
	struct FieldWrapperHelper {
		static_assert(
			sizeof(T) == -1,
			"Parameter to FieldWrapperHelper is not a function pointer"
		);
	};

	template <typename T, typename R>
	struct FieldWrapperHelper<R T::*>: FieldWrapper<T, R> {};

	/**
	 * Helper struct for wrapping user type methods
	 */
	template <typename T>
	struct MethodWrapper {
		static_assert(
			sizeof(T) == -1,
			"Undefined template MethodWrapper"
		);
	};

	// 'const volatile'-qualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...) const volatile> {
		using MethodPointerType = R (T::*)(A...) const volatile;
		using FunctionSignature = R (const volatile T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(const volatile T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};

	// 'const'-qualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...) const> {
		using MethodPointerType = R (T::*)(A...) const;
		using FunctionSignature = R (const T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(const T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};

	// 'volatile'-qualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...) volatile> {
		using MethodPointerType = R (T::*)(A...) volatile;
		using FunctionSignature = R (volatile T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(volatile T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};

	// unqualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...)> {
		using MethodPointerType = R (T::*)(A...);
		using FunctionSignature = R (T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};
}

/**
 * User type T.
 * Instances created using this specialization are allocated and constructed as full user data
 * types in Lua. The default garbage-collecting hook will destruct the user type, once it has
 * been marked.
 */
template <typename U>
struct Value<U&> {
	using T = internal::StripUserType<U>;

	static inline
	U& read(State* state, int n) {
		// T is unqualified, therefore conversion from T& to U& is allowed
		return *internal::check_user_type<T>(state, n);
	}

	template <typename... A> static inline
	int push(State* state, A&&... args) {
		void* mem = lua_newuserdata(state, sizeof(T));

		if (!mem) {
			luaL_error(state, "Failed to allocate user type");
			return -1;
		}

		// Construct
		new (mem) T {std::forward<A>(args)...};

		// Apply metatable for unqualified type T
		internal::apply_user_type_meta_table<T>(state);

		return 1;
	}
};

/**
 * User type T.
 * Instances created using this specialization are allocated as light user data in Lua.
 * The default garbage-collector does not destruct light user data types.
 */
template <typename U>
struct Value<U*> {
	using T = internal::StripUserType<U>;

	static inline
	U* read(State* state, int n) {
		// T is unqualified, therefore conversion from T* to U* is allowed
		return internal::check_user_type<T>(state, n);
	}

	static inline
	int push(State* state, T* instance) {
		if (instance == nullptr)
			return 0;

		// Push instance as light user data
		lua_pushlightuserdata(state, instance);

		// Apply metatable for unqualified type T
		internal::apply_user_type_meta_table<T>(state);

		return 1;
	}
};

/**
 * Constructor function for a type `T`. Variadic arguments must be used to specify which parameters
 * to use during construction.
 */
template <typename T, typename... A>
constexpr CFunction wrap_constructor =
	&internal::construct_user_type<internal::StripUserType<T>, A...>;

/**
 * This macros has no additional use whatsoever, but I makes the style consistent.
 */
#define LUWRA_WRAP_CONSTRUCTOR(type, ...) \
	(luwra::wrap_constructor<type, __VA_ARGS__>)

/**
 * Property accessor method
 *
 *   struct T {
 *     R my_property;
 *   };
 *
 * The wrapped property accessor is also a function:
 *
 *   CFunction wrapped_property = wrap_field<T, R, &T::my_property>;
 */
template <
	typename T,
	typename R,
	R T::* field_pointer
>
constexpr CFunction wrap_field =
	&internal::FieldWrapper<T, R>::template invoke<field_pointer>;

/**
 * This macro allows you to wrap fields without supplying template parameters.
 */
#define LUWRA_WRAP_FIELD(field) \
	(&luwra::internal::FieldWrapperHelper<decltype(&field)>::invoke<&field>)

/**
 * Register the metatable for user type `T`. This function allows you to register methods
 * which are shared across all instances of this type. A garbage-collector hook is also inserted.
 * Meta-methods can be added and/or overwritten aswell.
 */
template <typename U> static inline
void register_user_type(
	State* state,
	const std::map<const char*, CFunction>& methods = std::map<const char*, CFunction>(),
	const std::map<const char*, CFunction>& meta_methods = std::map<const char*, CFunction>()
) {
	using T = internal::StripUserType<U>;

	// Setup an appropriate metatable name
	internal::new_user_type_metatable<T>(state);

	// Register methods
	if (methods.size() > 0 && meta_methods.count("__index") == 0) {
		push(state, "__index");
		lua_newtable(state);

		for (auto& method: methods) {
			setFields(state, -1, method.first, method.second);
		}

		lua_rawset(state, -3);
	}

	// Register garbage-collection hook
	if (meta_methods.count("__gc") == 0) {
		setFields(state, -1, "__gc", &internal::destruct_user_type<T>);
	}

	// Register string representation function
	if (meta_methods.count("__tostring") == 0) {
		setFields(state, -1, "__tostring", &internal::stringify_user_type<T>);
	}

	// Insert meta methods
	for (const auto& metamethod: meta_methods) {
		setFields(state, -1, metamethod.first, metamethod.second);
	}

	// Pop metatable off the stack
	lua_pop(state, -1);
}

LUWRA_NS_END

/**
 * Generate a `lua_CFunction` wrapper for a method.
 * \param fun Fully qualified method name (Do not supply a pointer)
 * \return Wrapped function as `lua_CFunction`
 */
#define LUWRA_WRAP_METHOD(meth) \
	(&luwra::internal::MethodWrapper<decltype(&meth)>::template invoke<&meth>)

#endif
<commit_msg>Remove 'wrap_constructor'<commit_after>/* Luwra
 * Minimal-overhead Lua wrapper for C++
 *
 * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
 */

#ifndef LUWRA_USERTYPES_H_
#define LUWRA_USERTYPES_H_

#include "common.hpp"
#include "types.hpp"
#include "stack.hpp"
#include "functions.hpp"

#include <map>

LUWRA_NS_BEGIN

namespace internal {
	using UserTypeID = const void*;

	template <typename T>
	using StripUserType = std::remove_cv_t<T>;

	/**
	 * User type identifier
	 */
	template <typename T> extern
	const UserTypeID user_type_id = (void*) INTPTR_MAX;

	/**
	 * Registry name for a metatable which is associated with a user type
	 */
	template <typename T> extern
	const std::string user_type_reg_name =
		"UD#" + std::to_string(uintptr_t(&user_type_id<StripUserType<T>>));

	/**
	 * Register a new metatable for a user type T.
	 */
	template <typename U> static inline
	void new_user_type_metatable(State* state) {
		using T = StripUserType<U>;
		luaL_newmetatable(state, user_type_reg_name<T>.c_str());
	}

	/**
	 * Check if the value at the given index if a user type T.
	 */
	template <typename U> static inline
	StripUserType<U>* check_user_type(State* state, int index) {
		using T = StripUserType<U>;

		return static_cast<T*>(luaL_checkudata(state, index, user_type_reg_name<T>.c_str()));
	}

	/**
	 * Apply U's metatable for the value at the top of the stack.
	 */
	template <typename U> static inline
	void apply_user_type_meta_table(State* state) {
		using T = StripUserType<U>;

		luaL_getmetatable(state, user_type_reg_name<T>.c_str());
		lua_setmetatable(state, -2);
	}

	/**
	 * Lua C function to construct a user type T with parameters A
	 */
	template <typename U, typename... A> static inline
	int construct_user_type(State* state) {
		return internal::Layout<int(A...)>::direct(
			state,
			1,
			&Value<StripUserType<U>&>::template push<A...>,
			state
		);
	}

	/**
	 * Lua C function to destruct a user type T
	 */
	template <typename U> static inline
	int destruct_user_type(State* state) {
		using T = StripUserType<U>;

		if (!lua_islightuserdata(state, 1))
			Value<T&>::read(state, 1).~T();

		return 0;
	}

	/**
	 * Create a string representation for user type T.
	 */
	template <typename U> static
	int stringify_user_type(State* state) {
		using T = StripUserType<U>;

		return Value<std::string>::push(
			state,
			internal::user_type_reg_name<T>
				+ "@"
				+ std::to_string(uintptr_t(Value<T*>::read(state, 1)))
		);
	}

	/**
	 * Helper struct for wrapping user type fields
	 */
	template <typename U, typename R>
	struct FieldWrapper {
		using T = StripUserType<U>;

		template <R T::* field_pointer> static inline
		int invoke(State* state) {
			if (lua_gettop(state) > 1) {
				// Setter
				Value<T*>::read(state, 1)->*field_pointer = Value<R>::read(state, 2);
				return 0;
			} else {
				// Getter
				return push(state, Value<T*>::read(state, 1)->*field_pointer);
			}
		}
	};

	// 'const'-qualified fields
	template <typename U, typename R>
	struct FieldWrapper<U, const R> {
		using T = StripUserType<U>;

		template <const R T::* field_pointer> static inline
		int invoke(State* state) {
			return push(state, Value<T*>::read(state, 1)->*field_pointer);
		}
	};

	template <typename T>
	struct FieldWrapperHelper {
		static_assert(
			sizeof(T) == -1,
			"Parameter to FieldWrapperHelper is not a function pointer"
		);
	};

	template <typename T, typename R>
	struct FieldWrapperHelper<R T::*>: FieldWrapper<T, R> {};

	/**
	 * Helper struct for wrapping user type methods
	 */
	template <typename T>
	struct MethodWrapper {
		static_assert(
			sizeof(T) == -1,
			"Undefined template MethodWrapper"
		);
	};

	// 'const volatile'-qualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...) const volatile> {
		using MethodPointerType = R (T::*)(A...) const volatile;
		using FunctionSignature = R (const volatile T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(const volatile T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};

	// 'const'-qualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...) const> {
		using MethodPointerType = R (T::*)(A...) const;
		using FunctionSignature = R (const T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(const T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};

	// 'volatile'-qualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...) volatile> {
		using MethodPointerType = R (T::*)(A...) volatile;
		using FunctionSignature = R (volatile T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(volatile T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};

	// unqualified methods
	template <typename T, typename R, typename... A>
	struct MethodWrapper<R (T::*)(A...)> {
		using MethodPointerType = R (T::*)(A...);
		using FunctionSignature = R (T*, A...);

		template <MethodPointerType method_pointer> static inline
		R call(T* parent, A... args) {
			return (parent->*method_pointer)(std::forward<A>(args)...);
		}

		template <MethodPointerType method_pointer> static inline
		int invoke(State* state) {
			return FunctionWrapper<FunctionSignature>::template invoke<call<method_pointer>>(state);
		}
	};
}

/**
 * User type T.
 * Instances created using this specialization are allocated and constructed as full user data
 * types in Lua. The default garbage-collecting hook will destruct the user type, once it has
 * been marked.
 */
template <typename U>
struct Value<U&> {
	using T = internal::StripUserType<U>;

	static inline
	U& read(State* state, int n) {
		// T is unqualified, therefore conversion from T& to U& is allowed
		return *internal::check_user_type<T>(state, n);
	}

	template <typename... A> static inline
	int push(State* state, A&&... args) {
		void* mem = lua_newuserdata(state, sizeof(T));

		if (!mem) {
			luaL_error(state, "Failed to allocate user type");
			return -1;
		}

		// Construct
		new (mem) T {std::forward<A>(args)...};

		// Apply metatable for unqualified type T
		internal::apply_user_type_meta_table<T>(state);

		return 1;
	}
};

/**
 * User type T.
 * Instances created using this specialization are allocated as light user data in Lua.
 * The default garbage-collector does not destruct light user data types.
 */
template <typename U>
struct Value<U*> {
	using T = internal::StripUserType<U>;

	static inline
	U* read(State* state, int n) {
		// T is unqualified, therefore conversion from T* to U* is allowed
		return internal::check_user_type<T>(state, n);
	}

	static inline
	int push(State* state, T* instance) {
		if (instance == nullptr)
			return 0;

		// Push instance as light user data
		lua_pushlightuserdata(state, instance);

		// Apply metatable for unqualified type T
		internal::apply_user_type_meta_table<T>(state);

		return 1;
	}
};

/**
 * Property accessor method
 *
 *   struct T {
 *     R my_property;
 *   };
 *
 * The wrapped property accessor is also a function:
 *
 *   CFunction wrapped_property = wrap_field<T, R, &T::my_property>;
 */
template <
	typename T,
	typename R,
	R T::* field_pointer
>
constexpr CFunction wrap_field =
	&internal::FieldWrapper<T, R>::template invoke<field_pointer>;

/**
 * This macro allows you to wrap fields without supplying template parameters.
 */
#define LUWRA_WRAP_FIELD(field) \
	(&luwra::internal::FieldWrapperHelper<decltype(&field)>::invoke<&field>)

/**
 * Register the metatable for user type `T`. This function allows you to register methods
 * which are shared across all instances of this type. A garbage-collector hook is also inserted.
 * Meta-methods can be added and/or overwritten aswell.
 */
template <typename U> static inline
void register_user_type(
	State* state,
	const std::map<const char*, CFunction>& methods = std::map<const char*, CFunction>(),
	const std::map<const char*, CFunction>& meta_methods = std::map<const char*, CFunction>()
) {
	using T = internal::StripUserType<U>;

	// Setup an appropriate metatable name
	internal::new_user_type_metatable<T>(state);

	// Register methods
	if (methods.size() > 0 && meta_methods.count("__index") == 0) {
		push(state, "__index");
		lua_newtable(state);

		for (auto& method: methods) {
			setFields(state, -1, method.first, method.second);
		}

		lua_rawset(state, -3);
	}

	// Register garbage-collection hook
	if (meta_methods.count("__gc") == 0) {
		setFields(state, -1, "__gc", &internal::destruct_user_type<T>);
	}

	// Register string representation function
	if (meta_methods.count("__tostring") == 0) {
		setFields(state, -1, "__tostring", &internal::stringify_user_type<T>);
	}

	// Insert meta methods
	for (const auto& metamethod: meta_methods) {
		setFields(state, -1, metamethod.first, metamethod.second);
	}

	// Pop metatable off the stack
	lua_pop(state, -1);
}

LUWRA_NS_END

/**
 * Generate a `lua_CFunction` wrapper for a constructor.
 * \param type Type to instantiate
 * \param ...  Constructor parameter types
 * \return Wrapped function as `lua_CFunction`
 */
#define LUWRA_WRAP_CONSTRUCTOR(type, ...) \
	(&luwra::internal::construct_user_type<luwra::internal::StripUserType<type>, __VA_ARGS__>)

/**
 * Generate a `lua_CFunction` wrapper for a method.
 * \param fun Fully qualified method name (Do not supply a pointer)
 * \return Wrapped function as `lua_CFunction`
 */
#define LUWRA_WRAP_METHOD(meth) \
	(&luwra::internal::MethodWrapper<decltype(&meth)>::template invoke<&meth>)

#endif
<|endoftext|>


<commit_before>#include "HalideRuntime.h"

#include <stdarg.h>

#define WEAK __attribute__((weak))

extern "C" {

extern void __android_log_vprint(int, const char *, const char *, va_list);

extern uint32_t fwrite(void *, uint32_t, uint32_t, void *);
extern void *fopen(const char *, const char *);
extern void fclose(void *);

WEAK int halide_printf(const char * fmt, ...) {
    va_list args;
    va_start(args,fmt);
    __android_log_vprint(7, "halide", fmt, args);
    va_end(args);
    return 0;
}

static bool write_stub(const void *bytes, size_t size, void *f) {
    return fwrite(const_cast<void *>(bytes), size, 1, f) == 1;
}

WEAK int32_t halide_debug_to_file(const char *filename, uint8_t *data,
                                  int32_t s0, int32_t s1, int32_t s2, int32_t s3,
                                  int32_t type_code, int32_t bytes_per_element) {
    void *f = fopen(filename, "wb");
    if (!f) return -1;

    int result = halide_write_debug_image(filename, data, s0, s1, s2, s3,
					  type_code, bytes_per_element, write_stub, (void *)f);

    fclose(f);
    return result;
}

}
<commit_msg>halide_printf needs to return a nonzero value<commit_after>#include "HalideRuntime.h"

#include <stdarg.h>

#define WEAK __attribute__((weak))

extern "C" {

extern void __android_log_vprint(int, const char *, const char *, va_list);

extern uint32_t fwrite(void *, uint32_t, uint32_t, void *);
extern void *fopen(const char *, const char *);
extern void fclose(void *);

WEAK int halide_printf(const char * fmt, ...) {
    va_list args;
    va_start(args,fmt);
    __android_log_vprint(7, "halide", fmt, args);
    va_end(args);
    // Profiler assumes that return value <=0 is failure,
    // so return something else here.
    return 1;
}

static bool write_stub(const void *bytes, size_t size, void *f) {
    return fwrite(const_cast<void *>(bytes), size, 1, f) == 1;
}

WEAK int32_t halide_debug_to_file(const char *filename, uint8_t *data,
                                  int32_t s0, int32_t s1, int32_t s2, int32_t s3,
                                  int32_t type_code, int32_t bytes_per_element) {
    void *f = fopen(filename, "wb");
    if (!f) return -1;

    int result = halide_write_debug_image(filename, data, s0, s1, s2, s3,
					  type_code, bytes_per_element, write_stub, (void *)f);

    fclose(f);
    return result;
}

}
<|endoftext|>